diff --git a/.github/workflows/run-tests.yaml b/.github/workflows/run-tests.yaml index 28d3601676..121c46f1fc 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 f55376e50e..25babb53cc 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`, `update_records`, `delete_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`, `update_records`, `delete_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 backend the session resolves to: the one `CONSTRUCTIVE_*` names, else the current context. Given that backend's own api endpoint, it signs in with all of that backend's planes, as `constructive login` does; any other endpoint is a new backend whose auth, modules, agent and compute endpoints are derived 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; at the account's key limit, run `agent logout` first, which revokes this computer's key, or revoke a key in the app. 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` deletes the session and revokes its key, and says so when the revoke fails. -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__/api-key.test.ts b/agentic/cli/__tests__/api-key.test.ts deleted file mode 100644 index 5176387b9f..0000000000 --- a/agentic/cli/__tests__/api-key.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { - API_KEY_NAME, - buildCreateApiKeyInput, - classifyApiKeyError, - MintedApiKey, - needsRemint, - parseMintedKey, - REMINT_THRESHOLD_MS, - remintApiKey -} from '../src/api-key'; - -describe('buildCreateApiKeyInput', () => { - it('names the key agentic-cli with full access and no MFA', () => { - expect(buildCreateApiKeyInput({ years: 5 })).toEqual({ - keyName: API_KEY_NAME, - accessLevel: 'full_access', - mfaLevel: 'none', - expiresIn: { years: 5 } - }); - expect(API_KEY_NAME).toBe('agentic-cli'); - }); -}); - -describe('parseMintedKey', () => { - it('returns the minted key and maps expiresAt', () => { - expect(parseMintedKey({ apiKey: 'k', keyId: 'id', expiresAt: '2031-01-01' })).toEqual({ - apiKey: 'k', - keyId: 'id', - apiKeyExpiresAt: '2031-01-01' - }); - expect(parseMintedKey({ apiKey: 'k', keyId: 'id' })).toEqual({ apiKey: 'k', keyId: 'id' }); - }); - - it('throws when the backend returns no secret', () => { - expect(() => parseMintedKey(undefined)).toThrow('createApiKey returned no API key.'); - expect(() => parseMintedKey({ keyId: 'id' })).toThrow('createApiKey returned no API key.'); - }); -}); - -describe('classifyApiKeyError', () => { - it('maps extension codes', () => { - const err = { errors: [{ extensions: { code: 'STEP_UP_REQUIRED' } }] }; - 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'); - expect(classifyApiKeyError(new Error('nope'))).toBe('unknown'); - expect(classifyApiKeyError(undefined)).toBe('unknown'); - }); -}); - -describe('needsRemint', () => { - 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); - }); - - it('is true at or inside the 7-day threshold, 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); - }); -}); - -describe('remintApiKey', () => { - const minted: MintedApiKey = { apiKey: 'new', keyId: 'new-id' }; - - it('mints first, then revokes the old key', async () => { - const calls: string[] = []; - const result = await remintApiKey({ - currentKeyId: 'old-id', - revoke: async keyId => { - calls.push(`revoke:${keyId}`); - }, - mint: async () => { - calls.push('mint'); - return minted; - } - }); - expect(result).toEqual(minted); - expect(calls).toEqual(['mint', 'revoke:old-id']); - }); - - it('on limit-reached, revokes first and retries the mint once', async () => { - const calls: string[] = []; - let attempts = 0; - const result = await remintApiKey({ - currentKeyId: 'old-id', - revoke: async keyId => { - calls.push(`revoke:${keyId}`); - }, - mint: async () => { - calls.push('mint'); - attempts += 1; - if (attempts === 1) throw { errors: [{ extensions: { code: 'API_KEY_LIMIT_REACHED' } }] }; - return minted; - } - }); - expect(result).toEqual(minted); - expect(calls).toEqual(['mint', 'revoke:old-id', 'mint']); - }); - - it('rethrows non-limit errors 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(); - expect(revoke).not.toHaveBeenCalled(); - }); - - it('tolerates a failing revoke', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); - const result = await remintApiKey({ - currentKeyId: 'old-id', - revoke: async () => { - throw new Error('offline'); - }, - mint: async () => minted - }); - expect(result).toEqual(minted); - expect(warn).toHaveBeenCalled(); - warn.mockRestore(); - }); -}); 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..6a81da717f 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,59 @@ 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', 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'); + expect(output()).toContain('session stored in context example.com'); }); - 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' + it("signs in with every stored plane of the current context when the API endpoint is that context's", async () => { + const custom = backendFromEndpoints({ + api: 'https://graphql.example.com/graphql', + auth: 'https://identity.example.net/graphql', + modules: 'https://modules.example.net/graphql', + agent: 'https://agent.example.net/graphql', + compute: 'https://compute.example.net/graphql' }); + selectBackend(config.store, addBackend(config.store, custom, 'custom').name); + signInMock.mockResolvedValue({ session, context: 'custom', previousKey: { kind: 'absent' } }); - 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' - }); + await login(config, { apiUrl: custom.apiEndpoint, email: 'dev@example.com', password: 'pw' }); + + expect(signInMock).toHaveBeenCalledWith(expect.objectContaining({ backend: custom, context: 'custom' })); + }); + + it('signs in with the planes CONSTRUCTIVE_* names when the API endpoint is the one CONSTRUCTIVE_API_ENDPOINT names', async () => { + const saved = { api: process.env.CONSTRUCTIVE_API_ENDPOINT, auth: process.env.CONSTRUCTIVE_AUTH_ENDPOINT }; + process.env.CONSTRUCTIVE_API_ENDPOINT = REMOTE.apiEndpoint; + process.env.CONSTRUCTIVE_AUTH_ENDPOINT = 'https://identity.example.net/graphql'; + try { + signInMock.mockResolvedValue({ session, context: 'example.com', previousKey: { kind: 'absent' } }); + await login(config, { apiUrl: REMOTE.apiEndpoint, email: 'dev@example.com', password: 'pw' }); + expect(signInMock).toHaveBeenCalledWith( + expect.objectContaining({ backend: expect.objectContaining({ apiEndpoint: REMOTE.apiEndpoint, authEndpoint: 'https://identity.example.net/graphql' }) }) + ); + } finally { + for (const [name, value] of [['CONSTRUCTIVE_API_ENDPOINT', saved.api], ['CONSTRUCTIVE_AUTH_ENDPOINT', saved.auth]] as const) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + } }); 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 +130,61 @@ 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 the replaced key could not be revoked', async () => { + signInMock.mockResolvedValue({ session, context: 'localhost-3000', 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('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 +195,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 fdba1f86f0..004570ea6d 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,14 +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('update_records'); - expect(registered).not.toContain('delete_records'); - expect(registered).not.toContain('create_api_key'); - const excluded = ['add_records', 'update_records', 'delete_records', 'create_api_key']; - const expected = constructiveDbTools.map((tool) => tool.name).filter((name) => !excluded.includes(name)); - expect(registered.sort()).toEqual(expected.sort()); + return registered; + } + + it('registers every db tool except add_records, update_records and delete_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) => !['add_records', 'update_records', 'delete_records', 'create_api_key'].includes(name)); + expect(registeredTools().sort()).toEqual(expected.sort()); }); function loadHost() { @@ -71,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 () => { @@ -156,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 8275684318..ce2530a230 100644 --- a/agentic/cli/package.json +++ b/agentic/cli/package.json @@ -34,10 +34,9 @@ "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.8" + "inquirerer": "^4.10.1" }, "keywords": [ "agentic-kit", 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..71bb7bdd34 100644 --- a/agentic/cli/src/commands.ts +++ b/agentic/cli/src/commands.ts @@ -1,13 +1,14 @@ +import { + type KeyRevocation, + resolveSession, + sessionProblem, + signIn, + signInTarget, + 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 +62,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); + // The backend the session resolves to (CONSTRUCTIVE_* first, else the current context) is the default. + const resolved = signInTarget({ store: config.store }); const prompter = new Inquirerer({ noTty: !process.stdin.isTTY }); try { const answers = await prompter.prompt(argv, [ @@ -73,71 +75,92 @@ 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 — commands use the access token until it ends. Run `agent login` for a 30-day key.'); + } + 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('API key: none — db tools stay signed out. Run `agent login` to mint one.'); + log(`credential: not checked — ${check.reason}`); } - if (session.accessTokenExpiresAt) log(`access token expires: ${session.accessTokenExpiresAt}`); - log(`context: ${config.store.getCurrentContext()?.name ?? 'none'}`); } 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 021f1d0253..58d5e9f28f 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', 'update_records', 'delete_records', 'create_api_key'] }); +module.exports = createDbTools( + sessionToolsHost({ signInHint: 'Run \`agent login\` to sign in.', repairHint: ${JSON.stringify(REPAIR_HINT)} }), + { excludeTools: ['add_records', 'update_records', 'delete_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..7bcebeef99 --- /dev/null +++ b/agentic/command/README.md @@ -0,0 +1,85 @@ +# @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() + .then((code) => { + process.exitCode = code; + }); +``` + +## 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, and it refuses `--approve`, since it has no plan. +- **A change** (`effect: 'write' | 'destructive'`, `plan(input, ctx)` and `apply(input, planned, ctx)`): the layer calls `plan`, then decides from the run alone. Every plan has an id (`approvalId` of `@agentic-kit/harness`): a hash of the command, its input and global flags without their `x-delivery` parts, the directory and the plan. `--dry-run` returns `{ applied: false, plan, planId }` with the same command and `--approve ` as the next step. `--approve ` applies the change only while the new plan has that id; otherwise it stops with `plan-changed`, exit 3 and the new plan. `--yes` or `-y` approves any plan, for a script that shows no plan to anyone. 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`, its id in `error.details.planId` and the `--approve ` step. `apply` runs only after one of those approvals. `--approve` goes with neither `--yes` nor `--dry-run`. `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 `--approve` step after `--dry-run` and after exit 3. Mark such an input `x-delivery`, so the step that adds it still applies the approved plan. 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`) and `--approve`. 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` and `--approve` (`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. + +Which approval flags each kind takes is one table, so every kind names every flag: + +| Kind | `--dry-run` | `--yes` | `--approve ` | +| --- | --- | --- | --- | +| read | means nothing | means nothing | refused | +| change | shows the plan | approves any plan | applies that plan only | +| at once | refused | means nothing | refused | +| server | refused | refused | refused | +| passthrough | its own flag | its own flag | its own flag | + +A run has two phases: it reads its input (flags, `--input`, stdin, prompts), then it runs the command. SIGINT in the first phase stops the run before the command starts; in the second it aborts `ctx.signal`, waits up to 2 s for the command to settle, and reports `interrupted`, exit 130, either way. A change interrupted while it was planned is never applied. + +## 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), 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, in objects and in list items alike, with the union branch that applies. 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. +- A secret is never a flag or an `--input` value: argv shows in the process list and in the shell history. A command reads it from stdin, behind a boolean flag marked `.meta({ 'x-delivery': true })`, as `--password-stdin` does; an approval leaves that flag out. `createCli` refuses a schema that marks anything `x-secret`. `.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`; a path that matches nothing fails a read (exit 2) and warns after a change, also when its parent is kept whole beside it. +- 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` records the approval of that plan with the gate (`recordApproval`) and calls the tool with its params and a call id, so a tool wrapped with `requireApproval` makes the plan again and runs only while it is the approved one. +- 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..552686c4b5 --- /dev/null +++ b/agentic/command/__tests__/approval.test.ts @@ -0,0 +1,27 @@ +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); + }); +}); + +describe('decideApproval with --approve', () => { + it.each([true, false])('applies only the plan with that id, without a prompt (interactive %s)', (interactive) => { + expect(decideApproval({ dryRun: false, yes: false, interactive, approve: 'abcdef123456' })).toBe('apply-if-same'); + }); +}); diff --git a/agentic/command/__tests__/command-process.test.ts b/agentic/command/__tests__/command-process.test.ts new file mode 100644 index 0000000000..2633e2cfaf --- /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, ...(tty ? ['--fixture-tty'] : []), ...args], { + cwd: packageDir, + env: { ...process.env, TS_NODE_PROJECT: join(packageDir, 'tsconfig.json'), 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?'], + ['ask', 'City'] + ])('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): Cancelled (Ctrl-C). Nothing changed.']); + expect(exit.stderr).not.toContain('applied'); + }); + + it.each([ + ['approve', 'Ctrl-D', 'Apply?', '\u0004'], + ['approve', 'a closed stdin', 'Apply?', ''], + ['ask', 'Ctrl-D', 'City', '\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): No answer: the input ended. Nothing changed.']); + 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?', 'n\n') }); + expect(exit.code).toBe(1); + expect(exit.stderr).toContain('Error (cancelled): Not approved. Nothing 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?', '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..168e9abd25 --- /dev/null +++ b/agentic/command/__tests__/command.test.ts @@ -0,0 +1,1767 @@ +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() + }), + examples: [{ command: 'demo table add users --kind audit', description: 'Add users' }], + notes: ['Run demo table list afterwards.'], + run: record +}; + +const applied: string[] = []; +const bumped: string[] = []; +// What the target "moving" looks like now: a change to it between two runs changes its plan. +let moving = 'before'; + +/** + * 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().meta({ description: 'Read the key from stdin', 'x-delivery': true }) }), + 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 === 'moving' ? `moving ${moving}` : 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'), + org: z.string().describe('Organization') + }), + run: (input, ctx) => { + throw new CliError({ + code: 'signed-out', + message: `Sign-in failed for ${input.email}.`, + next: [ctx.next(['login', '--email', String(input.email), '--org', String(input.org)], 'Sign in again')] + }); + } + }, + 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(), + 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)], '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(), + vault: z.strictObject({ tier: z.enum(['gold', 'silver']).optional() }).optional() + }), + 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() + }), + 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 }] + ])('%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', '--org']); + 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('help, --schema and --llms', () => { + it.each([[['--help']], [['-h']], [[]]])('%j prints the root help, which points agents to --llms', 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: run "demo --llms" for the command index and the notes for agents.'); + 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 --kind audit\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', 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); + const expected = z.toJSONSchema(tableAdd.input, { io: 'input' }) as Record; + delete expected.$schema; + expect(schema.input).toEqual(expected); + }); + + 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 --kind audit', description: 'Add users' }]); + 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 a command or topic\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 without a prompt\n'); + expect(reference).toContain('demo table add users --kind audit'); + 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', '--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('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?', '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 into a placeholder word', async () => { + const ctx = await contextOf(); + const step = ctx.nextFor('shape', { name: { placeholder: 'name' }, count: 3 }, 'Shape it'); + expect(step).toEqual({ + command: 'demo shape --count 3', + argv: ['demo', 'shape', '', '--count', '3'], + 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']); + }); +}); + +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 yes\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 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.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 = (planId: string) => ({ command: `demo deploy web --json --approve ${planId}`, argv: ['demo', 'deploy', 'web', '--json', '--approve', planId], why: 'Apply after approval' }); + + it('stops before the change with exit 3, the plan and its --approve step, when there is no terminal', async () => { + const result = await exec(cli, ['deploy', 'web', '--json']); + expect(result.code).toBe(ExitCode.approvalRequired); + const { planId } = result.json().error.details; + expect(result.json()).toEqual({ + ok: false, + error: { + code: 'approval-required', + message: 'Nothing changed. The plan needs approval, and there is no terminal to ask.', + hint: 'Show the plan to the person, then run the --approve step.', + details: { plan: PLAN, planId } + }, + meta: { command: 'deploy', next: [rerun(planId)] } + }); + 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 {2}[\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); + const { planId } = result.json().data; + expect(result.json().data).toEqual({ applied: false, plan: PLAN, planId }); + expect(result.json().meta.next).toEqual([rerun(planId)]); + 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: 'Apply after approval' }); + const stopped = (await exec(cli, ['deploy', 'keyed', '--json'])).json(); + const id = stopped.error.details.planId; + expect(stopped.meta.next).toEqual([step(`demo deploy keyed --json --from-stdin --approve ${id}`)]); + expect((await exec(cli, ['deploy', 'keyed', '--dry-run', '--json'])).json().meta.next).toEqual([step(`demo deploy keyed --json --from-stdin --approve ${id}`)]); + const given = (await exec(cli, ['deploy', 'keyed', '--from-stdin', '--dry-run', '--json'])).json(); + expect(given.meta.next).toEqual([step(`demo deploy keyed --from-stdin --json --approve ${given.data.planId}`)]); + expect((await exec(cli, ['deploy', 'keyed', '--dry-run', '--json'], { tty: true })).json().meta.next).toEqual([step(`demo deploy keyed --json --approve ${id}`)]); + 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([]); + }); + + describe('an approval of one plan, with --approve ', () => { + const planIdOf = async (argv: string[]): Promise => (await exec(cli, [...argv, '--json'])).json().error.details.planId; + + it('gives each plan an id, in the data of --dry-run and in the error of exit 3, and offers --approve as the next step', async () => { + const stopped = (await exec(cli, ['deploy', 'web', '--json'])).json(); + const { planId } = stopped.error.details; + expect(planId).toMatch(/^[0-9a-f]{12}$/); + const next = { command: `demo deploy web --json --approve ${planId}`, argv: ['demo', 'deploy', 'web', '--json', '--approve', planId], why: 'Apply after approval' }; + expect(stopped.meta.next).toEqual([next]); + const dry = (await exec(cli, ['deploy', 'web', '--dry-run', '--json'])).json(); + expect(dry.data).toEqual({ applied: false, plan: PLAN, planId }); + expect(dry.meta.next).toEqual([next]); + expect(applied).toEqual([]); + }); + + it('applies the change while its plan is the one with that id', async () => { + const result = await exec(cli, ['deploy', 'web', '--approve', await planIdOf(['deploy', 'web']), '--json']); + expect(result.code).toBe(0); + expect(applied).toEqual(['web']); + }); + + it('refuses the id once the plan has changed, shows the new plan with its id, and changes nothing', async () => { + moving = 'before'; + const approved = await planIdOf(['deploy', 'moving']); + moving = 'after'; + const result = await exec(cli, ['deploy', 'moving', '--approve', approved, '--json']); + expect(result.code).toBe(ExitCode.approvalRequired); + const { error, meta } = result.json(); + expect(error).toMatchObject({ code: 'plan-changed', details: { plan: planOf('moving after') } }); + expect(error.details.planId).not.toBe(approved); + expect(meta.next[0].argv).toEqual(['demo', 'deploy', 'moving', '--json', '--approve', error.details.planId]); + expect(applied).toEqual([]); + }); + + it('applies with the step that adds the flags the plan needs, since they only say how a secret arrives', async () => { + const stopped = (await exec(cli, ['deploy', 'keyed', '--json'])).json(); + const result = await exec(cli, stopped.meta.next[0].argv.slice(1)); + expect(result.code).toBe(0); + expect(applied).toEqual(['keyed']); + }); + + it('binds the input a plan does not show', async () => { + const rotate: ChangeCommand> = { + name: 'rotate', + summary: 'Rotate the key', + effect: 'write', + input: z.object({ key_name: z.string().describe('The key to rotate'), label: z.string().describe('The label of the new key') }), + plan: () => ({ plan: planOf('the key') }), + apply: () => ({ data: {} }) + }; + const small = createCli({ name: 'demo', version: '1.0.0', commands: [rotate] }); + const idFor = async (key: string, label: string) => (await exec(small, ['rotate', '--key-name', key, '--label', label, '--json'])).json().error.details.planId; + const first = await idFor('deploy-key', 'ci'); + expect(first).toMatch(/^[0-9a-f]{12}$/); + expect(await idFor('deploy-key', 'ci')).toBe(first); + expect(await idFor('other-key', 'ci')).not.toBe(first); + expect(await idFor('deploy-key', 'deploy')).not.toBe(first); + }); + + it('binds the global flags and the directory of the run', async () => { + const id = await planIdOf(['deploy', 'web', '--context', 'staging']); + expect(await planIdOf(['deploy', 'web', '--context', 'production'])).not.toBe(id); + expect(await planIdOf(['deploy', 'web', '--context', 'staging', '--cwd', 'elsewhere'])).not.toBe(id); + }); + + it.each([[['--yes']], [['--dry-run']]])('is a usage error beside %j', async (flags) => { + const result = await exec(cli, ['deploy', 'web', '--approve', 'abcdef123456', ...flags, '--json']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error.code).toBe('invalid-input'); + expect(applied).toEqual([]); + }); + + it('is a usage error for a read, which has no plan to approve', async () => { + const result = await exec(cli, ['table', 'list', '--approve', 'abcdef123456', '--json']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error).toMatchObject({ code: 'invalid-input', details: { flag: '--approve' } }); + }); + + it('is a usage error for a change that has no plan', async () => { + const result = await exec(cli, ['bump', '--approve', 'abcdef123456', '--json']); + expect(result.code).toBe(ExitCode.usage); + expect(result.json().error).toMatchObject({ code: 'invalid-input', details: { flag: '--approve' } }); + expect(bumped).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?', '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?', 'n\n']] }); + expect(result.code).toBe(ExitCode.failure); + expect(result.json().error).toEqual({ code: 'cancelled', message: 'Not approved. Nothing 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\n/); + expect((await exec(cli, ['--help'])).stdout).toMatch(/server +Run the server +own flags\n/); + }); +}); + +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('it changes at once'); + 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 +at once\n/); + }); +}); + +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); + } + ); +}); + +describe('the fixes of the second review', () => { + const ran: string[] = []; + const stamp: CommandDefinition = { name: 'stamp', summary: 'Stamp', effect: 'read', input: z.object({}), run: () => ({ data: { createdAt: new Date(0) } }) }; + const say: CommandDefinition = { + name: 'say', + summary: 'Say a word', + effect: 'read', + positionals: ['word'], + input: z.object({ word: z.string().describe('The word') }), + run: (input) => ({ data: { word: input.word } }) + }; + const slow: CommandDefinition = { + name: 'slow', + summary: 'Plan slowly', + effect: 'write', + input: z.object({}), + plan: async () => { + process.emit('SIGINT'); + await new Promise((settle) => setTimeout(settle, 20)); + return { plan: planOf('slowly') }; + }, + apply: () => { + ran.push('slow'); + return { data: {} }; + } + } as CommandDefinition; + const spec: CommandDefinition = { + name: 'spec', + summary: 'Read a spec', + effect: 'read', + input: z.object({ spec: z.discriminatedUnion('kind', [z.object({ kind: z.literal('a'), limit: z.number().optional() }), z.object({ kind: z.literal('b') })]) }), + run: (input) => ({ data: input }) + }; + const review = createCli({ name: 'demo', version: '1.0.0', commands: [stamp, say, slow, spec] }); + + it('gives a Date in the data as its JSON text', async () => { + expect((await exec(review, ['stamp', '--json'])).json().data).toEqual({ createdAt: '1970-01-01T00:00:00.000Z' }); + }); + + it('applies no change that was interrupted while it was planned', async () => { + const result = await exec(review, ['slow', '--yes']); + expect(result.code).toBe(130); + expect(ran).not.toContain('slow'); + }); + + it('keeps the word after a layer flag as the positional of the command', async () => { + const result = await exec(review, ['--json', 'say', 'false']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ word: 'false' }); + }); + + it('gives a delivery flag once in the approval step, in place of the false value given', async () => { + const result = await exec(cli, ['deploy', 'keyed', '--from-stdin=false', '--dry-run', '--json']); + const argv: string[] = result.json().meta.next[0].argv; + expect(argv.filter((word) => word.startsWith('--from-stdin'))).toEqual(['--from-stdin']); + }); + + it('keeps the required global flags in the manifest', () => { + const strict = createCli({ name: 'strict', version: '1.0.0', globals: z.object({ context: z.string().describe('Backend') }), commands: [say] }); + expect(strict.manifest().globals.required).toEqual(['context']); + }); + + it('reads null as not given for an optional key of a union branch', async () => { + const result = await exec(review, ['spec', '--input', '{"spec":{"kind":"a","limit":null}}', '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ spec: { kind: 'a' } }); + }); +}); + +describe('the fixes of the third review', () => { + const tagged: CommandDefinition = { + name: 'tagged', + summary: 'Read a tagged spec', + effect: 'read', + input: z.object({ spec: z.discriminatedUnion('kind', [z.object({ kind: z.literal('a'), limit: z.number().optional() }), z.object({ kind: z.literal('b'), limit: z.number() })]) }), + run: (input) => ({ data: input }) + }; + const third = createCli({ name: 'demo', version: '1.0.0', commands: [tagged] }); + + it('reads null as not given by the union branch the discriminator picks', async () => { + const result = await exec(third, ['tagged', '--input', '{"spec":{"kind":"a","limit":null}}', '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ spec: { kind: 'a' } }); + }); +}); + +describe('the redesign: explicit rules where the run decides', () => { + it('refuses a secret in a slot of a tuple too', () => { + const pair: CommandDefinition = { + name: 'pair', + summary: 'Take a pair', + effect: 'read', + input: z.object({ pair: z.tuple([z.string(), z.string().meta({ 'x-secret': true })]) }), + run: () => ({ data: {} }) + }; + expect(() => createCli({ name: 'demo', version: '1.0.0', commands: [pair] })).toThrow('"pair[1]" is marked x-secret'); + }); + + it('names a server among the commands that print their own output in --llms', async () => { + const serve = { name: 'serve', summary: 'Speak a protocol on stdout', effect: 'write', stdout: 'reserved', serve: async () => ({ data: {} }) } as CommandDefinition; + const result = await exec(createCli({ name: 'demo', version: '1.0.0', commands: [serve] }), ['--llms']); + expect(result.stdout).toMatch(/but `demo serve`[^)]*print their own output/); + }); + + it('refuses a schema that marks a secret, since a secret is never a flag or an --input value', () => { + const login: CommandDefinition = { + name: 'login', + summary: 'Sign in', + effect: 'read', + input: z.object({ creds: z.object({ password: z.string().meta({ 'x-secret': true }) }) }), + run: () => ({ data: {} }) + }; + expect(() => createCli({ name: 'demo', version: '1.0.0', commands: [login] })).toThrow('"creds.password" is marked x-secret'); + }); + + it('reads null as not given in the items of a list that is one branch of a union', async () => { + const listed: CommandDefinition = { + name: 'listed', + summary: 'Read a list or nothing', + effect: 'read', + input: z.object({ rules: z.union([z.array(z.object({ limit: z.number().optional() })), z.null()]) }), + run: (input) => ({ data: input }) + }; + const result = await exec(createCli({ name: 'demo', version: '1.0.0', commands: [listed] }), ['listed', '--input', '{"rules":[{"limit":null}]}', '--json']); + expect(result.code).toBe(0); + expect(result.json().data).toEqual({ rules: [{}] }); + }); + + it('refuses a --fields path under a parent that is kept whole when that path matches nothing', async () => { + const result = await exec(cli, ['status', '--fields', 'owner,owner.nope', '--json']); + expect(result.code).toBe(2); + expect(result.json().error.details.unmatched).toEqual(['owner.nope']); + expect((await exec(cli, ['status', '--fields', 'owner,owner.id', '--json'])).code).toBe(0); + }); + + it('reports exit 130 when a command is interrupted in its first synchronous step', async () => { + const eager: CommandDefinition = { + name: 'eager', + summary: 'Stop at once', + effect: 'read', + passthrough: async () => { + process.emit('SIGINT'); + return { data: { ran: true } }; + } + }; + const result = await exec(createCli({ name: 'demo', version: '1.0.0', commands: [eager] }), ['eager']); + expect(result.code).toBe(ExitCode.interrupted); + }); + + it('never runs a command that was interrupted while it read its input', async () => { + const ran: string[] = []; + const later: CommandDefinition = { + name: 'later', + summary: 'Run after the input', + effect: 'read', + input: z.object({ name: z.string().optional() }), + run: () => { + ran.push('later'); + return { data: {} }; + } + }; + const stdin = new PassThrough(); + const out = capture(); + const err = capture(); + const run = createCli({ name: 'demo', version: '1.0.0', commands: [later] }).run(['later', '--input', '-', '--json'], { stdin, stdout: out.stream, stderr: err.stream, env: {}, cwd: dir }); + setImmediate(() => { + process.emit('SIGINT'); + setImmediate(() => stdin.end('{}')); + }); + expect(await run).toBe(ExitCode.interrupted); + await new Promise((settle) => setTimeout(settle, 20)); + expect(ran).toEqual([]); + }); +}); diff --git a/agentic/command/__tests__/tool-command.test.ts b/agentic/command/__tests__/tool-command.test.ts new file mode 100644 index 0000000000..4363cd54b2 --- /dev/null +++ b/agentic/command/__tests__/tool-command.test.ts @@ -0,0 +1,601 @@ +import { type ConfirmPrompt, defineHarnessTool, type GatePolicy, identifierParam, type PlanTarget, requireApproval, 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.' } + }; + } +}); + +// Gated as a db tool is: it runs only while its plan is the one the run approved. +const deleteTool = requireApproval(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; +const TABLE_TARGET: PlanTarget = { + kind: 'database', + database: { id: 'db-1', name: 'app' }, + apiEndpoint: 'http://api.localhost:3000/graphql', + account: { userId: 'user-1' }, + table: { id: 'table-1', schemaId: 'schema-1' } +}; +let target: PlanTarget = TARGET; + +// 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, + preview: { kind: 'policies', tableName: name, policies: ['AuthzDirectOwner'] } + }, + input: event.input + }; + } +}; + +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; + target = TARGET; +}); + +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, the plan and its --approve step when it is not interactive and has no approval', 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, planId: expect.stringMatching(/^[0-9a-f]{12}$/) }); + expect(error.hint).toMatch(/plan/); + const id = error.details.planId; + expect(meta.next).toEqual([{ command: `demo thing delete posts --approve ${id}`, argv: ['demo', 'thing', 'delete', 'posts', '--approve', id], 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 thing\?\n[\s\S]*Change the thing "posts"\.\n\nError \(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); + const id = result.json().data.planId; + expect(result.json().data).toEqual({ applied: false, plan, planId: id }); + expect(result.json().meta.next).toEqual([{ command: `demo thing delete posts --approve ${id}`, argv: ['demo', 'thing', 'delete', 'posts', '--approve', id], 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.each([ + ['--yes', ['--yes'], {}], + ['a yes on a terminal', ['--json'], { tty: true, answers: [['Apply?', 'y\n']] as Array<[string, string]> }] + ])('applies the approved plan through the tool\'s own check (%s), and refuses when the plan changes before apply', async (_how, flags, options) => { + target = TABLE_TARGET; + expect((await run(['thing', 'delete', 'posts', ...flags], options)).code).toBe(0); + expect(calls).toEqual([{ tool: 'delete_thing', params: { thing_name: 'posts' }, cwd }]); + calls.length = 0; + // The table is replaced while the person reads the plan: the tool makes the plan again at apply and refuses. + const replaced: PlanTarget = { ...TABLE_TARGET, table: { id: 'table-2', schemaId: 'schema-1' } } as PlanTarget; + let planned = 0; + const realResolve = gate.resolvePrompt; + gate.resolvePrompt = async (event, gateCwd) => { + planned += 1; + if (planned > 1) target = replaced; + return realResolve(event, gateCwd); + }; + try { + const result = await run(['thing', 'delete', 'posts', ...flags], options); + expect(result.code).toBe(1); + expect(result.json().error.code).toBe('plan-changed'); + expect(calls).toEqual([]); + } finally { + gate.resolvePrompt = realResolve; + } + }); + + it('binds the input a plan does not show', async () => { + const idOf = async (size: string) => (await run(['thing', 'create', 'widgets', '--size', size, '--dry-run'])).json().data.planId; + expect(await idOf('1')).not.toBe(await idOf('2')); + }); + + 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?', '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?', '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('the inputs a binding requires', () => { + it('come from the input schema, so building the CLI runs no transform of a tool parameter', () => { + let made = 0; + const tagTool = defineHarnessTool({ + name: 'tag_thing', + label: 'Tag thing', + description: 'Tag a thing.', + parameters: z.object({ name: z.string(), tag: z.string().optional().transform((tag) => tag ?? `tag-${++made}`) }), + effect: 'read', + async execute() { + return { content: [{ type: 'text', text: 'Tagged.' }], details: {} }; + } + }); + createCli({ name: 'demo', version: '1.0.0', commands: toCliCommands([toolCommand(tagTool, { name: 'thing tag' })], { gate }) }); + expect(made).toBe(0); + }); +}); + +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 grow', + input: z.object({ thing_name: z.string(), by: z.number() }), + positionals: ['thing_name'], + mapInput: ({ thing_name, by }: { thing_name: string; by: number }) => ({ thing_name, new_size: by }), + toInput: () => { + throw new Error('grow takes no absolute size'); + } + }), + toolCommand(changeTool, { + name: 'thing set', + input: z.object({ thing_name: z.string(), size: z.number(), mode: z.enum(['soft', 'hard']) }), + 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 }) + }), + 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..46c2a33d12 --- /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.10.1", + "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..14c4f97fff --- /dev/null +++ b/agentic/command/src/approval.ts @@ -0,0 +1,97 @@ +import { approvalId, 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' | 'apply-if-same' | 'ask' | 'approval-required'; + +/** + * --dry-run shows the plan, --approve applies it only if it is still that plan, --yes approves any plan, a + * terminal asks, and anything else stops before the change. + */ +export function decideApproval(run: { dryRun: boolean; yes: boolean; interactive: boolean; approve?: string }): Approval { + if (run.dryRun) return 'show-plan'; + if (run.approve !== undefined) return 'apply-if-same'; + if (run.yes) return 'apply'; + return run.interactive ? 'ask' : 'approval-required'; +} + +/** The data of a `--dry-run`: nothing was changed, this is what would be, and the id that approves exactly this. */ +export interface PlanData { + applied: false; + plan: ConfirmPrompt; + planId: string; +} + +/** The run a plan was made for besides its input: the global flags, and the JSON Schema of both, which marks what only says how a secret arrives. */ +export interface PlanRun { + globals: Record; + schema: { input?: object; globals?: object }; +} + +async function confirmed(ctx: CommandContext, shown: string): Promise { + const answers = await ctx.prompter.prompt<{ yes?: boolean }>({}, [{ type: 'confirm', name: 'yes', message: `${shown}\n\nApply?`, 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, + run: PlanRun +): Promise> { + const planned = await command.plan(input, ctx); + const { plan } = planned; + // The id binds the command, its input and global flags (but no x-delivery part), the directory and the plan. + const planId = approvalId({ + action: command.name, + input: { input, globals: run.globals }, + schema: { type: 'object', properties: { input: run.schema.input ?? {}, globals: run.schema.globals ?? {} } }, + cwd: ctx.cwd, + plan + }); + const needs = ctx.interactive ? [] : planned.needs ?? []; + const approve = [...needs, '--approve', planId]; + // A flag the step adds replaces the value the run gave it (--from-stdin=false), so the step names it once. + const replaced = needs.map((flag) => flag.replace(/^--/, '').split('=')[0]); + const shown = (): string => renderPlan(plan); + // A change interrupted while it was planned is not applied: the interrupt is reported whatever the plan was. + const apply = (): Promise> | CommandResult => { + if (ctx.signal?.aborted) throw layerError({ code: 'interrupted', message: 'The command was interrupted (SIGINT). Nothing changed.', exitCode: ExitCode.interrupted }); + return command.apply(input, planned, ctx); + }; + const stop = (code: CommandErrorCode, message: string): CliError => { + if (ctx.format === 'text') ctx.stderr.write(`${shown()}\n\n`); + return new CliError({ + code, + message, + hint: 'Show the plan to the person, then run the --approve step.', + next: [ctx.followUp(approve, { drop: ['yes', 'approve', ...replaced], why: 'Apply after approval' })], + exitCode: ExitCode.approvalRequired, + details: { plan, planId } + }); + }; + switch (decideApproval({ dryRun, yes: ctx.yes, interactive: ctx.interactive, approve: ctx.approve })) { + case 'show-plan': { + const data: PlanData = { applied: false, plan, planId }; + return { + data, + text: renderPlan(plan), + next: [ctx.followUp(approve, { drop: ['dry-run', 'yes', 'approve', ...replaced], why: 'Apply after approval' })] + }; + } + case 'apply-if-same': + if (ctx.approve === planId) return apply(); + throw stop('plan-changed', 'Nothing changed. The plan is no longer the one that was approved.'); + case 'apply': + return apply(); + case 'ask': + if (await confirmed(ctx, shown())) return apply(); + throw layerError({ code: 'cancelled', message: 'Not approved. Nothing changed.', exitCode: ExitCode.failure }); + case 'approval-required': + throw stop('approval-required', 'Nothing changed. The plan needs approval, and there is no terminal to ask.'); + } +} diff --git a/agentic/command/src/cli.ts b/agentic/command/src/cli.ts new file mode 100644 index 0000000000..539339f61f --- /dev/null +++ b/agentic/command/src/cli.ts @@ -0,0 +1,780 @@ +import { alignColumns } from '@agentic-kit/harness'; +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, + requestedFormat, + type Scope, + 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 (--approve , --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]]); + matched.add(prefix + head); + // The parent is kept whole, and each path below it that was asked for beside it must still exist. + const children = tails.filter(Boolean); + if (children.length) pick(data[head], children, matched, `${prefix}${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.' + }; +} + +/** A value as one cell: true is "yes", false and nothing are blank, and an object is its JSON. */ +const cell = (value: unknown): string => + value === null || value === undefined || value === false ? '' : value === true ? 'yes' : typeof value === 'object' ? JSON.stringify(value) : String(value); + +/** A data key as words: `apiEndpoint` and `api_endpoint` are "api endpoint". */ +const keyWords = (key: string): string => key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/_/g, ' ').toLowerCase(); + +function renderTable(rows: Record[]): string { + const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))]; + return alignColumns([keys.map((key) => keyWords(key).toUpperCase()), ...rows.map((row) => keys.map((key) => cell(row[key])))]).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 alignColumns(Object.entries(data).filter(([, value]) => value !== undefined).map(([key, value]) => [keyWords(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 { + 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 + ) {} + + 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 ?? [])]; + 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 = result.next?.length ? result.next : undefined; + 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 stack = !isCliError(thrown) && this.debug && thrown instanceof Error ? 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, cause, hint } = error; + const next = error.next?.length ? error.next : undefined; + if (this.format === 'json') { + this.emitJson({ + ok: false, + error: { code: error.code, message, cause, hint, retryable: error.retryable, 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; + } +} + +/** 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)}?` : undefined, + 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}".`, { + 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: `Prompts are off: ${blocker}.`, + hint: `Pass ${orList(flags, 'and')}, or the whole input with --input.`, + next: [scope.step([...scope.path, '--schema'], 'See every input property')], + details: { missing: flags } + }); +} + +type ApprovalFlag = 'dryRun' | 'yes' | 'approve'; + +/** + * What each kind of command does with the layer's approval flags: why it refuses one, or null where it takes it. + * Every kind names every flag, so a new kind or flag cannot be left out. A passthrough command owns its flags. + */ +const APPROVAL_FLAGS: Record, Record> = { + read: { dryRun: null, yes: null, approve: 'it only reads, so it has no plan to approve' }, + change: { dryRun: null, yes: null, approve: null }, + immediate: { dryRun: 'it changes at once', yes: null, approve: 'it changes at once, with no plan to approve' }, + serve: { dryRun: 'it serves a protocol, and its client approves each change', yes: 'its client approves each change', approve: 'its client approves each change' } +}; + +/** Refuses an approval flag the kind does not take, and --approve beside --yes or --dry-run: --approve applies one plan. */ +function rejectApprovalFlags(kind: Exclude, layer: LayerFlags, scope: Scope): void { + const refused = APPROVAL_FLAGS[kind]; + if (layer.dryRun && refused.dryRun) { + throw usageError('dry-run-unsupported', `"${scope.usage}" has no dry run: ${refused.dryRun}.`, { + hint: 'Run it without --dry-run.', + next: [helpStep(scope, 'See what the command changes')], + details: { flag: '--dry-run' } + }); + } + if (layer.approve !== undefined) { + const beside = layer.yes ? '--yes' : layer.dryRun ? '--dry-run' : undefined; + if (refused.approve || beside) { + throw usageError( + 'invalid-input', + refused.approve + ? `--approve does not apply to "${scope.usage}": ${refused.approve}.` + : `--approve and ${beside} do not go together: --approve applies one plan, and ${beside === '--yes' ? '--yes applies any plan' : '--dry-run applies none'}.`, + { + hint: refused.approve ? 'Run it without --approve.' : `Give --approve alone, or ${beside} alone.`, + next: [helpStep(scope, 'See what the command changes')], + details: { flag: '--approve' } + } + ); + } + } + if (layer.yes && refused.yes) { + throw usageError('invalid-input', `--yes does not apply to "${scope.usage}": ${refused.yes}.`, { + hint: 'Run it without --yes.', + next: [helpStep(scope, 'See what the command serves')], + details: { flag: '--yes' } + }); + } +} + +const interrupted = (message: string): CliError => layerError({ code: 'interrupted', message, exitCode: ExitCode.interrupted }); + +/** 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. The abort is watched before `work` + * starts, so an interrupt in its first synchronous step counts too. + */ +async function untilInterrupted(controller: AbortController, work: () => Promise): Promise { + const onSigint = (): void => controller.abort(); + process.on('SIGINT', onSigint); + const aborted = new Promise((resolve) => controller.signal.addEventListener('abort', () => resolve(false), { once: true })); + try { + const task = work(); + const settled = task.then(() => true, () => 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 a command or 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))); + rejectApprovalFlags(kind, layer, scope); + } + + 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, + ...(layer.approve === undefined ? {} : { approve: layer.approve }), + 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: 'Cancelled (Ctrl-C). Nothing changed.', + exitCode: ExitCode.interrupted + }); + case 'end-of-input': + return layerError({ + code: 'cancelled', + message: 'No answer: the input ended. Nothing changed.', + 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.`); + }; + + // A run reads its input, then runs the command: an interrupt while it reads stops it before the command starts. + const runIt = async (): Promise => { + if (kind === 'passthrough') return (command as PassthroughCommand).passthrough(parseArgv(['', '', ...rest]), ctx); + const input = await readValues(); + if (controller.signal.aborted) throw interrupted('The command was interrupted (SIGINT) while it read its input. Nothing ran.'); + 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, { globals, schema: { input: inputJson, globals: globalsJson } }); + } + }; + + 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 breaks = new Set(restIndexes.flatMap((at, index) => (index > 0 && at !== restIndexes[index - 1] + 1 ? [index] : []))); + const tokens = tokenize(rest, table, breaks); + // 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 line = commandLine(config.name, `${config.name} ${resolved.name}`, argv, path, (index) => restIndexes[index], tokens, 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..82ee7ef8fd --- /dev/null +++ b/agentic/command/src/help.ts @@ -0,0 +1,324 @@ +import { alignColumns } from '@agentic-kit/harness'; + +import { FlagDef, FlagKind, flagKind, FlagTable, kebabCase, LAYER_FLAGS, orList } from './input'; +import type { CliConfig, CliManifest, CommandDefinition, 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) + })); +} + +/** 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 and its id with --dry-run, asks on a terminal, and without a terminal stops with exit 3 and the plan. ' + + 'Show the plan to the person, then run the next step, --approve : it applies the change only while the plan is the same, and otherwise stops with plan-changed and the new plan. ' + + '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) 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; +} + +/** The effect column of a command list: blank for a read, so the commands that change something stand out. */ +function effectColumn(command: KindFacts): string { + if (command.passthrough) return 'own flags'; + if (command.stdout === 'reserved') return 'stdio'; + if (command.immediate) return 'at once'; + return command.effect === 'read' ? '' : command.effect; +} + +const commandRows = (commands: CommandDefinition[]): string[] => + alignColumns(commands.map((command) => [command.name, command.summary, effectColumn(command)])).map((line) => ` ${line}`); + +const EFFECT_LEGEND = '"write" and "destructive" commands show a plan and ask first; "at once" commands change without one.'; + +export function rootHelp(config: CliConfig, table: FlagTable): string { + const lines = [`${config.name} ${config.version}`]; + if (config.description) lines.push(config.description); + lines.push( + '', + 'Usage:', + ` ${config.name} [flags]`, + '', + 'Commands:', + ...commandRows(visible(config)), + '', + EFFECT_LEGEND, + '', + '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: run "${config.name} --llms" for the command index and the notes for agents.`); + 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), + '', + EFFECT_LEGEND, + `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 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: ${config.name} --help`); + if (command.examples?.length) { + lines.push('', 'Examples:'); + for (const example of command.examples) { + 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`; +} + +/** A topic as a terminal shows it: its Markdown without the fence lines of its code blocks or the backticks of inline code. */ +export const topicPage = (topic: HelpTopic): string => + `${topic.summary}\n\n${topic.body.replace(/^ {0,3}```.*\n?/gm, '').replace(/`([^`\n]+)`/g, '$1')}\n`; + +export function commandSchema(command: CommandDefinition, shown: Shown) { + return { + name: command.name, + summary: command.summary, + effect: command.effect, + positionals: positionalsOf(command), + input: 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 ownOutput = visible(config).filter((command) => 'passthrough' in command || 'serve' in command).map((command) => `\`${config.name} ${command.name}\``); + const own = ownOutput.length ? ` (but ${orList(ownOutput, 'and')}, which print their own output)` : ''; + lines.push( + `Version ${config.version}. Run \`${config.name} --schema\` for the JSON Schema of a command's input, and of its output when it declares one, ` + + `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, its plan in `error.details.plan` and its id in `error.details.planId`. `--approve ` applies that plan only, and `--yes` applies any plan. ' + + `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: { + type: 'object', + properties: { ...globals?.properties, ...LAYER_FLAGS.properties }, + ...(globals?.required?.length ? { required: globals.required } : {}) + }, + 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: shown.input, + output: shown.output, + examples: command.examples ?? [], + 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 JSON Schema of a command's input, and of its output when it declares one.`, + `\`${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..648b3d44e5 --- /dev/null +++ b/agentic/command/src/input.ts @@ -0,0 +1,1013 @@ +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; + 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('Same as --format json'), + format: z.enum(['text', 'json']).optional().describe('Default: text on a terminal, json otherwise'), + fields: z.string().optional().describe('Keep only these paths of data, for example id,owner.name'), + input: z.string().optional().describe('The whole input: JSON, @file.json, or - for stdin'), + dry_run: z.boolean().optional().describe('Show the plan; change nothing'), + yes: z.boolean().optional().meta({ description: 'Approve the plan without a prompt', 'x-short': 'y' }), + approve: z.string().optional().describe('Apply only the plan with this id, from --dry-run or exit 3'), + no_input: z.boolean().optional().describe('Never prompt'), + tty: z.boolean().optional().describe('false: never prompt'), + schema: z.boolean().optional().describe("Print the command's JSON Schema"), + llms: z.boolean().optional().describe('Print the command index for agents (with --json, the manifest)'), + cwd: z.string().optional().meta({ description: 'Run as if 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; + approve?: string; + noInput: boolean; + tty: boolean; + schema: boolean; + llms: boolean; + cwd?: string; + version: boolean; + help: boolean; +} + +const builtByLayer = new WeakSet(); + +/** An error the layer wrote itself, as opposed to one a command threw. */ +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; +} + +/** The path of the first node under `schema` marked x-secret, or undefined. */ +function secretMark(schema: JSONSchema | undefined, path: string): string | undefined { + if (!isPlainObject(schema)) return undefined; + if (schema['x-secret'] !== undefined) return path; + const additional = typeof schema.additionalProperties === 'object' ? schema.additionalProperties : undefined; + const branches = [...(schema.anyOf ?? []), ...(schema.oneOf ?? []), ...(schema.allOf ?? [])]; + const slots = Array.isArray(schema.prefixItems) ? (schema.prefixItems as JSONSchema[]) : []; + const children: Array<[string, JSONSchema | undefined]> = [ + ...Object.entries(schema.properties ?? {}).map(([key, child]): [string, JSONSchema] => [`${path}.${key}`, child]), + ...slots.map((slot, index): [string, JSONSchema] => [`${path}[${index}]`, slot]), + [`${path}[]`, schema.items], + [`${path}.*`, additional], + ...branches.map((branch): [string, JSONSchema] => [path, branch]) + ]; + for (const [childPath, child] of children) { + const found = secretMark(child, childPath); + if (found) return found; + } + return undefined; +} + +/** 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 marked = secretMark(propertySchema, property); + if (marked) { + throw new Error( + `${owner}: "${marked}" is marked x-secret, but a secret is never a flag or an --input value: argv shows in the process list and in the shell history. ` + + 'Read the secret from stdin behind a boolean flag marked x-delivery, as --password-stdin does, and remove the x-secret mark.' + ); + } + const def: FlagDef = { + property, + flag: kebabCase(property), + schema: propertySchema, + check: schema.shape[property] as z.ZodType, + kind: flagKind(propertySchema), + scope, + 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; +} + +/** `breaks`: the indexes of words that did not follow the word before them in the typed argv (a command word sat between). */ +export function tokenize(argv: readonly string[], table: FlagTable, breaks: ReadonlySet = new Set()): 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); + // A word the command name stood before belongs to the command, so no flag before the name takes it as its value. + const next = breaks.has(index + 1) ? undefined : 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) { + if (inline === undefined && next !== undefined && !next.startsWith('--')) { + 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 = (raw: string): string => `, got ${JSON.stringify(raw)}`; + +const DECIMAL = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; +const INTEGER_LITERAL = /^-?\d+$/; + +function coerceScalar(def: FlagDef, kind: ScalarKind, raw: string, label: string): unknown { + switch (kind.kind) { + case 'boolean': + if (raw === 'true' || raw === 'false') return raw === 'true'; + throw invalidInput(`${label} takes true or false${shown(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 = closest(raw, kind.values.map(String)); + throw invalidInput( + `${label} must be one of ${kind.values.map(String).join(', ')}${shown(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(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(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 at length, 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 JSON, or a file with ${label} @file.json. Text needs JSON quotes: ${label} '"text"'.`, + 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); + } + 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); + case 'list': { + return values.flatMap((raw) => { + if (!raw.trimStart().startsWith('[')) return [coerceScalar(def, kind.item, raw, label)]; + 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, + approve: values.approve as string | undefined, + 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); + +/** `schema` and the schemas of its union branches (anyOf, oneOf, allOf), nested ones included. */ +function branchesOf(schema: JSONSchema): JSONSchema[] { + const branches = [schema.anyOf, schema.oneOf, schema.allOf].flatMap((list) => (Array.isArray(list) ? list.filter(isPlainObject) : [])); + return [schema, ...branches.flatMap(branchesOf)]; +} + +/** + * `value` with each null that means "not given" removed, in nested objects and list items. The schema that applies + * is looked up the same way for both: in the schema and in its union branches. A key's null stays when any branch + * that applies requires the key or takes null. + */ +function withoutAbsentNulls(value: unknown, schema: JSONSchema | undefined): unknown { + if (!isPlainObject(schema)) return value; + if (Array.isArray(value)) { + const items = branchesOf(schema).find((branch) => isPlainObject(branch.items))?.items; + return items ? value.map((item) => withoutAbsentNulls(item, items)) : value; + } + if (!isPlainObject(value)) return value; + // A branch whose constant keys (a discriminator) disagree with the value is not the one that applies. + const record = value; + const branches = branchesOf(schema).filter((branch) => + Object.entries(branch.properties ?? {}).every(([key, child]) => !isPlainObject(child) || !('const' in child) || !(key in record) || record[key] === child.const) + ); + return Object.fromEntries(Object.entries(value).flatMap(([key, item]): Array<[string, unknown]> => { + const declaring = branches.flatMap((branch) => { + const additional = typeof branch.additionalProperties === 'object' ? branch.additionalProperties : undefined; + const child = own(branch.properties, key) ?? additional; + return child ? [{ child, required: (branch.required ?? []).includes(key) }] : []; + }); + const absent = declaring.length > 0 && declaring.every(({ child, required }) => isAbsentNull(item, child, required)); + return absent ? [] : [[key, withoutAbsentNulls(item, declaring[0]?.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. */ +function schemaAt(schema: JSONSchema | undefined, path: readonly PropertyKey[]): JSONSchema | undefined { + let node = schema; + for (const key of path) { + if (!isPlainObject(node)) return undefined; + const additional = typeof node.additionalProperties === 'object' ? node.additionalProperties : undefined; + node = typeof key === 'number' ? node.items : own(node.properties, String(key)) ?? additional; + } + return node; +} + +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. + */ +function problemOf(issue: z.core.$ZodIssue, value: unknown, schema: JSONSchema, display: (path: readonly PropertyKey[]) => string): Problem { + const node = schemaAt(schema, issue.path); + const at = display(issue.path); + 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 }; +} + +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 }; +} + +/** 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; 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); + if (valueAt === undefined || valueAt === at) return [{ def: token.def, words: [argv[at]] }]; + return [{ def: token.def, words: [argv[at], 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, 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. + */ +export function commandLine( + cliName: string, + usage: string, + argv: readonly string[], + path: readonly number[], + argvIndex: (tokenIndex: number) => number, + tokens: Token[], + table: FlagTable +): CommandLine { + const words = [...argv]; + const flagWords: Array<{ def: FlagDef; at: number[] }> = []; + let separator: number | undefined; + for (const token of tokens) { + if (token.kind === 'separator') { + separator = argvIndex(token.index); + } 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] }); + } + } + 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(words[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 `{ 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 = 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 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 = isPlaceholder(value) ? value : undefined; + 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); + if (isPlaceholder(value)) { + words.push(flagName(def.property), value); + } 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 { ...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..9e1be44b4f --- /dev/null +++ b/agentic/command/src/tool-command.ts @@ -0,0 +1,346 @@ +import { + type AnyHarnessTool, + approvalId, + callChange, + type GateDecision, + type GatePolicy, + type HarnessTool, + type HarnessToolContent, + type HarnessToolResult, + recordApproval, + type ToolCallSuggestion, + type ToolFailure, + type ToolFailureCode +} from '@agentic-kit/harness'; +import { randomUUID } from 'crypto'; +import { z } from 'zod'; + +import { jsonSchemaOf } from './input'; +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; + /** The properties it cannot run without: a call that gives none of them is made by another binding. */ + required: 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. The + * mapped value is parsed by the tool's schema, so it is that schema's input (before a transform), not its output. + */ +type ToolCommandInput = + | { input?: never; mapInput?: never } + | { input: TInput; mapInput(input: z.output, ctx: CommandContext): TMapped | 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); + +/** The properties the input JSON Schema requires, as the flag table reads them; no value is parsed, so no transform runs. */ +const requiredOf = (schema: InputSchema): string[] => [...(jsonSchemaOf(schema, 'input').required ?? [])]; + +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) ?? []) { + // A binding that cannot map the call (its toInput throws) is skipped like one that does not take it. + try { + 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; + } + // A placeholder the call asks to choose counts as given: the person fills it in. + const missing = [...binding.required].filter((key) => !(key in input)); + if (missing.length) { + reasons.push(`"${binding.command}" also needs ${missing.join(', ')}`); + continue; + } + 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, the params `apply` calls the tool with, and the parsed input the approval binds. */ +interface ToolPlanned extends Planned { + params: TParams; + input: Record | undefined; +} + +/** + * 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, input: decision.input }; + }, + async apply(_given, { params, plan, input }, ctx) { + // The tool makes its plan again at apply, with the same gate, and runs only while it is this one. + const toolCallId = randomUUID(); + recordApproval(toolCallId, ctx.cwd, { id: approvalId({ action: tool.name, input, cwd: ctx.cwd, plan }), gate: deps.gate }); + return finish(await tool.execute(params, { cwd: ctx.cwd, toolCallId, signal: ctx.signal }), params, ctx); + } + }; + return change; +} + +/** One entry for `toCliCommands`, typed by its tool. */ +export function toolCommand( + tool: HarnessTool, + options: ToolCommandOptions, TDetails, z.input> +): 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))), + required: new Set(requiredOf(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..a6048ff5dc --- /dev/null +++ b/agentic/command/src/types.ts @@ -0,0 +1,347 @@ +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-delivery': true })` on an input that only says how a secret arrives, such as + * `password_stdin`: an approval of a plan leaves it out, so the step that adds it still applies that plan. + */ + 'x-delivery'?: 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. 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. + */ + followUp(flags: string[], options: FollowUpOptions): NextStep; + /** A next step that runs another command: the CLI name, then `words`. */ + 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 becomes a placeholder word. + * 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; + /** The run was given --approve : a change it plans is applied only when its plan has that id. */ + approve?: string; + /** 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 reads it only for `--input -`, to its end, before + * the command runs; a command that needs a second payload then takes it from another source. + */ + 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, --approve + * approves it while it is the plan with that id, --yes approves any plan, 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': 'No command has these words, so nothing ran: the hint names the nearest one.', + 'unknown-topic': 'No command, group or help topic has this name, so nothing ran: the hint names the nearest one.', + 'unknown-flag': 'The command has no such flag, so nothing ran: the hint names the nearest one.', + 'unexpected-argument': 'The command takes fewer arguments, so nothing ran: pass the other values as flags.', + 'missing-input': 'A required value is missing and no prompt could ask, so nothing ran: error.details.missing names the flags.', + 'invalid-input': "A flag, an --input key or a value does not fit the command's schema, so nothing ran: see the command's --schema.", + 'dry-run-unsupported': 'The command changes at once or serves a protocol, so it has no plan and no dry run: run it without --dry-run.', + 'approval-required': 'There is no approval and no terminal to ask, so nothing changed: show error.details.plan to the person, then run the --approve step.', + 'plan-changed': 'The plan is no longer the one the --approve id names, so nothing changed: show the new error.details.plan to the person, then run its --approve step.', + cancelled: 'A prompt got no answer (Ctrl-C exits 130, the end of input exits 1), or the person declined: nothing changed.', + interrupted: 'The run got SIGINT, so a change may be partly made: check the state before you rerun.', + failed: 'An unexpected error: the message is its own, and DEBUG=1 adds the stack to 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..9aa368b172 --- /dev/null +++ b/agentic/command/test-utils/command-fixture.ts @@ -0,0 +1,76 @@ +import { z } from 'zod'; + +import { createCli } from '../src'; + +// With --fixture-tty first, the piped stdin and stdout pass for a terminal, so the layer prompts; no pty library is +// needed. The flag is the fixture's own, so it is taken off before the CLI reads the arguments. +const args = process.argv.slice(2); +const tty = args[0] === '--fixture-tty'; +const argv = tty ? args.slice(1) : args; +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: 'ask', + summary: 'Ask for a city', + effect: 'read', + input: z.object({ city: z.string().describe('City') }), + run: () => ({ data: { asked: true } }) + } + ] +}); + +cli.run(argv, 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/db-tools/README.md b/agentic/db-tools/README.md index 1dd6e8c01a..e3d1c91049 100644 --- a/agentic/db-tools/README.md +++ b/agentic/db-tools/README.md @@ -31,7 +31,7 @@ npm install @agentic-kit/db-tools The public `extensions.context` of the error that decided goes into `failure.context`: a query over the backend's request limits (`QUERY_TOO_COSTLY`, `QUERY_TOO_DEEP`, `PAGE_SIZE_TOO_LARGE`, `REQUEST_TOO_LARGE`) is `query-too-large` with its numbers there, for example `{ cost, limit }`. An update or delete that answers with no row in its payload changed nothing: that is how row-level security answers for a row this account cannot see, so every tool that updates or deletes fails `no-rows-changed` there instead of reporting success. A create that answers without the new row fails `no-rows-changed` as well: the row may not exist, or a policy lets the account create it but not read it, and the hint names the call that shows whether it exists. `STEP_UP_REQUIRED` is `step-up-required`: the change needs a recent sign-in. - `constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`. For `delete_records` the check resolves the exact rows once, as the person signed in to the app: each table's rows by key, by column values (`where`), its sample rows still there, or all its rows, at most 500 in all, ordered so a row goes before the rows it points at, with what the delete does to the rows it does not select: the rows that point at them, counted on the app API by the foreign keys and followed through each cascade (search chunk tables left out). The target names those rows (`rows`) and the card's preview shows them (`delete-records`). The tool then deletes only the rows the approved target names (`takeApprovedTable`). When a host leaves tables out of the target, the tool counts the effects of the approved rows again first, and deletes nothing when they would delete, clear or be blocked by rows of a table the person kept, or when it can't count or follow the rows that could reach one (too many related rows, a table with no single-column key, a key it can't read). + `constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`. For `delete_records` the check resolves the exact rows once, as the person signed in to the app: each table's rows by key, by column values (`where`), its sample rows still there, or all its rows, at most 500 in all, ordered so a row goes before the rows it points at, with what the delete does to the rows it does not select: the rows that point at them, counted on the app API by the foreign keys and followed through each cascade (search chunk tables left out). The target names those rows (`rows`) and the card's preview shows them (`delete-records`). The tool then deletes only the rows of the target `requireApproval` gives it (`approved`), and with no such target it deletes nothing. A host that lets the person untick tables records the approval with the tables they kept (`recordApproval`'s `tables`); when tables are left out, the tool counts the effects of the approved rows again first, and deletes nothing when they would delete, clear or be blocked by rows of a table the person kept, or when it can't count or follow the rows that could reach one (too many related rows, a table with no single-column key, a key it can't read). **Access.** The access of a table is its stored rules, grants and row security (`readTables`), and nothing here says who can or cannot reach a row. `explain_access` gives one plain sentence per stored rule (`explainPolicy`, from the words of the rule's Authz node), the grants, row security and the structural findings (`accessFindings`), each of which says what may happen. It and `describe_schema` return each stored rule through `asWritten`, in the one shape a caller writes (`{ $type, privileges, permissive, policy_role, data, with_check? }`), with every key the node's closed `parameter_schema` marks `readOnly` left out, nested nodes included, so a read carries no part the closed world refuses. A plan's rules use the same keys, with `words` in place of `data`. `set_access` replaces every rule of a table in one change with `owns: ['policies']`; the grants stay, and the Data nodes the rules need add their columns when the table lacks them. `add_policies` adds rules without replacing any. Both take rules only in the registry's blueprint shape (`{ $type, privileges, permissive, policy_role, policy_name, data }`, `AccessPolicyZod`), check each rule's shape against the registry's `BlueprintPolicy`, and check its data with `checkRule` (ajv over the node's closed `parameter_schema`, and the rule shapes these tools do not support) and its role before any plan. Every tool that sends rules, `provision_blueprint` included, sends them through `rulesToSend`: rules of one policy type, role, kind and data become one rule with all their privileges, and a rule the backend would skip (the same policy type and data as another) or refuse (a second policy row of one role, privilege and name) is refused before the plan. The plan holds the rules, grants and row security now and after, one sentence per rule, the findings the change adds and removes, the columns it adds (name, type, required, default) and the ones it reuses as they are. A reused column of another type than its Data node needs is blocked before the change (`conflict`, with `retype_field` and `delete_field`). When the person signed in to the app sees a row, a change that adds a required column with no value for the rows is blocked before anything is sent; otherwise the backend's refused NOT NULL comes back as a `conflict` with the `create_field` call that adds the column as optional first. After the change, the table is read back and compared with the plan by meaning (`policyDifference`); a difference is a `conflict`, and a read that fails is `unverified`. A refusal on the rows of an app table (`add_records`) suggests the read of its rules; a refusal on the control plane does not, because it is about the account's rights on the database. diff --git a/agentic/db-tools/__tests__/blueprint.test.ts b/agentic/db-tools/__tests__/blueprint.test.ts index 6015d35e11..5009c40d19 100644 --- a/agentic/db-tools/__tests__/blueprint.test.ts +++ b/agentic/db-tools/__tests__/blueprint.test.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { constructiveDbTools } from '../src'; import { expandBlueprintDefaults } from '../src/blueprint/blueprint-defaults'; +import { blueprintProblems } from '../src/blueprint/blueprint-schema'; import { fieldTypeToTypeName, toFieldDefault, toFieldType } from '../src/blueprint/field-type'; import { configureHost } from '../src/host'; import { DATABASE_ID, type FakeBackend, type GraphQLAnswer, projectAnswer, type SeenRequest, startFakeBackend } from './fake-backend'; @@ -27,6 +28,24 @@ type Expanded = { tables: Array> } & Record) => expandBlueprintDefaults(definition) as Expanded; const nodeTypes = (nodes: unknown) => (nodes as Array).map((node) => (typeof node === 'string' ? node : node.$type)); +describe('blueprintProblems', () => { + it('passes a node that leaves out a parameter the backend does not need', () => { + const definition = { + tables: [ + { + table_name: 'notes', + fields: [{ name: 'body', type: { name: 'text' } }], + nodes: [ + { $type: 'SearchBm25', data: { field_name: 'body' } }, + { $type: 'DataMemberOwner', data: { entity_type: 'org' } } + ] + } + ] + }; + expect(blueprintProblems(definition)).toEqual([]); + }); +}); + describe('expandBlueprintDefaults', () => { it('derives nodes, default grants and rule defaults for a bare table, and gives each field the backend form', () => { const [table] = expand({ diff --git a/agentic/db-tools/__tests__/delete-records.test.ts b/agentic/db-tools/__tests__/delete-records.test.ts index bb72adc38b..4627df1f2e 100644 --- a/agentic/db-tools/__tests__/delete-records.test.ts +++ b/agentic/db-tools/__tests__/delete-records.test.ts @@ -2,10 +2,11 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { type GateReadiness, rememberApprovedTable } from '@agentic-kit/harness'; +import { approvalId, createConstructiveGatePolicy, type GateReadiness, recordApproval } from '@agentic-kit/harness'; import { constructiveGateDeps } from '../src/gate'; import { configureHost, type ToolsHost } from '../src/host'; +import { servedTools } from '../src/tools'; import { deleteRecordsTool } from '../src/tools/delete-records'; import { DATABASE_ID, type FakeBackend, type GraphQLAnswer, projectAnswer, startFakeBackend } from './fake-backend'; @@ -272,9 +273,9 @@ describe('delete_records', () => { rows.people = [{ id: 'c1', name: 'Same key, other table' }]; const tables = [{ table_name: 'contact_rows', all: true as const }]; const { target } = ready(await precondition(tables)); - rememberApprovedTable('tc-1', cwd, target); + const approved = target; - const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1', approved }); expect(result.failure).toBeUndefined(); expect(rows.contacts).toEqual([]); @@ -286,9 +287,9 @@ describe('delete_records', () => { const tables = [{ table_name: 'companies', all: true as const }, { table_name: 'contacts', all: true as const }]; const { target } = ready(await precondition(tables)); if (target.kind !== 'database') throw new Error('not a database target'); - rememberApprovedTable('tc-1', cwd, { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'companies') }); + const approved = { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'companies') }; - const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1', approved }); expect(result.failure).toMatchObject({ code: 'conflict', @@ -305,9 +306,9 @@ describe('delete_records', () => { const tables = [{ table_name: 'companies', all: true as const }, { table_name: 'notes', all: true as const }]; const { target } = ready(await precondition(tables)); if (target.kind !== 'database') throw new Error('not a database target'); - rememberApprovedTable('tc-1', cwd, { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'companies') }); + const approved = { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'companies') }; - const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1', approved }); expect(result.failure).toMatchObject({ code: 'conflict', @@ -316,15 +317,30 @@ describe('delete_records', () => { expect(rows.companies.map((row) => row.id)).toEqual(['k1']); }); + it('deletes the rows a host approved through the gate, only of the tables the person kept', async () => { + const tool = servedTools.deleteRecordsTool; + const event = { toolName: tool.name, toolCallId: 'tc-2', input: { tables: [{ table_name: 'companies', all: true }, { table_name: 'contacts', all: true }] } }; + const policy = createConstructiveGatePolicy(constructiveGateDeps()); + const decision = await policy.resolvePrompt(event, cwd); + if (decision.kind !== 'ask') throw new Error('expected a card'); + recordApproval(event.toolCallId, cwd, { id: approvalId({ action: tool.name, input: decision.input, cwd, plan: decision.prompt }), gate: policy, tables: ['contacts'] }); + + const result = await tool.execute(tool.parameters.parse(event.input), { cwd, toolCallId: event.toolCallId }); + + expect(result.failure).toBeUndefined(); + expect(rows.contacts).toEqual([]); + expect(rows.companies.map((row) => row.id)).toEqual(['k1']); + }); + it('deletes only the rows of the approved target, and leaves a table the person unticked alone', async () => { const tables = [{ table_name: 'companies', all: true as const }, { table_name: 'contacts', all: true as const }]; const { target } = ready(await precondition(tables)); if (target.kind !== 'database') throw new Error('not a database target'); - rememberApprovedTable('tc-1', cwd, { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'contacts') }); + const approved = { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'contacts') }; // A row added after the card was approved is not one the person saw. rows.contacts.push({ id: 'c3', name: 'Cy', companyId: 'k1' }); - const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1', approved }); expect(result.failure).toBeUndefined(); expect(rows.contacts.map((row) => row.id)).toEqual(['c3']); diff --git a/agentic/db-tools/__tests__/gate-precondition.test.ts b/agentic/db-tools/__tests__/gate-precondition.test.ts index 8c402390bc..2cfbee48c2 100644 --- a/agentic/db-tools/__tests__/gate-precondition.test.ts +++ b/agentic/db-tools/__tests__/gate-precondition.test.ts @@ -2,8 +2,9 @@ import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { createConfirmGate, createConstructiveGatePolicy, type GateHost, type PlanTarget, rememberApprovedTable } from '@agentic-kit/harness'; +import { type AnyHarnessTool, approvalId, createConfirmGate, createConstructiveGatePolicy, type GateHost, type PlanTarget, recordApproval } from '@agentic-kit/harness'; +import * as dbTools from '../src'; import { constructiveDbTools, constructiveGateDeps } from '../src'; import type { RunCommand } from '../src/app-workspace'; import { configureHost } from '../src/host'; @@ -105,7 +106,7 @@ function namedAnswer({ host, query }: SeenRequest): GraphQLAnswer { if (host.startsWith('api-mydb.')) return { data: { _meta: { tables: [{ name: 'Post', query: { all: 'posts' }, inflection: { tableType: 'Post' }, fields: [{ name: 'title', columnName: 'title', type: { gqlType: 'String', isArray: false } }] }] } } }; if (/blueprintTemplates/.test(query)) return { data: { blueprintTemplates: { nodes: [{ id: 'tpl-1', displayName: 'Blog', definition: {} }] } } }; if (/uniqueConstraints/.test(query)) return { data: { uniqueConstraints: { nodes: [] } } }; - if (/\bfields\b/.test(query)) return { data: { fields: { nodes: [] } } }; + if (/\bfields\b/.test(query)) return { data: { fields: { nodes: [{ id: 'f1', name: 'body', tableId: 't1' }] } } }; if (/\btables\b/.test(query)) return { data: { tables: { nodes: [{ id: 't1', name: 'posts' }] } } }; return { data: {} }; } @@ -129,6 +130,10 @@ describe('the plan names what the call acts on', () => { it.each<[string, Record, () => PlanTarget]>([ ['delete_table', { table_name: 'posts' }, () => onDatabase({ table: { id: 't1', schemaId: 'schema-1' } })], + ['create_field', { table_name: 'posts', field_name: 'summary', type: 'text' }, () => onDatabase({ table: { id: 't1', schemaId: 'schema-1' } })], + ['update_field', { table_name: 'posts', field_name: 'body', is_required: true }, () => onDatabase({ table: { id: 't1', schemaId: 'schema-1', fieldId: 'f1' } })], + ['retype_field', { table_name: 'posts', field_name: 'body', type: 'text' }, () => onDatabase({ table: { id: 't1', schemaId: 'schema-1', fieldId: 'f1' } })], + ['delete_field', { table_name: 'posts', field_name: 'body' }, () => onDatabase({ table: { id: 't1', schemaId: 'schema-1', fieldId: 'f1' } })], ['add_records', { table_name: 'posts', records: [{ title: 'a' }] }, () => onDatabase({ appUserId: 'U1' })], ['delete_template', { templateName: 'Blog' }, () => onAccount()], ['provision_database', { database_name: 'next' }, () => onAccount()], @@ -139,20 +144,27 @@ describe('the plan names what the call acts on', () => { const ready = await deps.precondition(name, input, cwd); const decision = await createConstructiveGatePolicy(deps).resolvePrompt({ toolName: name, toolCallId: 'tc-1', input }, cwd); - expect(ready).toEqual({ kind: 'ready', target: target() }); - expect(decision).toMatchObject({ kind: 'ask', prompt: { target: target() } }); + expect(ready).toEqual({ kind: 'ready', target: target(), input }); + expect(decision).toMatchObject({ kind: 'ask', prompt: { target: target() }, input }); }); - it.each([false, true])('deletes only the approved table (table replaced: %s)', async (replaced) => { + it.each([ + ['delete_table', { table_name: 'posts' }, false], + ['delete_table', { table_name: 'posts' }, true], + ['delete_field', { table_name: 'posts', field_name: 'body' }, false], + ['delete_field', { table_name: 'posts', field_name: 'body' }, true], + ] as const)('%s %j changes only what the person approved (replaced while the plan was open: %s)', async (name, input, replaced) => { let tableId = 'original'; await backend.close(); backend = await startFakeBackend(({ query }) => { - if (/mutation/.test(query)) return { data: { deleteTable: { table: { id: tableId } } } }; + if (/mutation/.test(query)) return { data: { deleteTable: { table: { id: tableId } }, deleteField: { field: { id: `body-of-${tableId}` } } } }; + if (/uniqueConstraints/.test(query)) return { data: { uniqueConstraints: { nodes: [] } } }; + if (/\bfields\b/.test(query)) return { data: { fields: { nodes: [{ id: `body-of-${tableId}`, name: 'body', tableId }] } } }; if (/\btables\b/.test(query)) return { data: { tables: { nodes: [{ name: 'posts', id: tableId }] } } }; return projectAnswer(query, 'ME') ?? { data: {} }; }); - const tool = constructiveDbTools.find(({ name }) => name === 'delete_table')!; - const event = { toolName: tool.name, toolCallId: 'delete-1', input: { table_name: 'posts' } }; + const tool = constructiveDbTools.find((candidate) => candidate.name === name)!; + const event = { toolName: tool.name, toolCallId: `${name}-1`, input: { ...input } }; const blocked = await createConfirmGate(constructiveGateDeps()).onToolCall(event, { ...decliningHost(), confirmTool: async () => { @@ -162,10 +174,37 @@ describe('the plan names what the call acts on', () => { }, cwd); const result = await tool.execute(event.input, { cwd, toolCallId: event.toolCallId }); expect(blocked).toBeUndefined(); - expect(result.failure?.message).toBe(replaced ? 'The current table and project do not match the approved delete target.' : undefined); + expect(result.failure?.code).toBe(replaced ? 'plan-changed' : undefined); expect(backend.requests.some(({ query }) => /mutation/.test(query))).toBe(!replaced); }); + it('exports each tool that changes something only as the one that checks its approval at apply', () => { + const served = new Set(constructiveDbTools); + const changes = Object.entries(dbTools).filter(([, value]) => typeof value === 'object' && value !== null && 'execute' in value && (value as AnyHarnessTool).effect !== 'read'); + expect(changes.length).toBeGreaterThan(10); + expect(changes.filter(([, tool]) => !served.has(tool)).map(([name]) => name)).toEqual([]); + }); + + it('runs an approved call whose host sends a key it leaves out as null', async () => { + await backend.close(); + backend = await startFakeBackend(({ query }) => { + if (/mutation/.test(query)) return { data: { createField: { field: { id: 'title-of-posts', name: 'title' } } } }; + if (/uniqueConstraints/.test(query)) return { data: { uniqueConstraints: { nodes: [] } } }; + if (/\bfields\b/.test(query)) return { data: { fields: { nodes: [] } } }; + if (/\btables\b/.test(query)) return { data: { tables: { nodes: [{ name: 'posts', id: 'original' }] } } }; + return projectAnswer(query, 'ME') ?? { data: {} }; + }); + const tool = constructiveDbTools.find(({ name }) => name === 'create_field')!; + const event = { toolName: tool.name, toolCallId: 'create-1', input: { table_name: 'posts', field_name: 'title', type: 'text', is_unique: null as boolean | null } }; + const approved = await createConfirmGate(constructiveGateDeps()).onToolCall(event, { ...decliningHost(), confirmTool: async () => true }, cwd); + + const result = await tool.execute(tool.parameters.parse(event.input), { cwd, toolCallId: event.toolCallId }); + + expect(approved).toBeUndefined(); + expect(result.failure).toBeUndefined(); + expect(backend.requests.some(({ query }) => /mutation/.test(query))).toBe(true); + }); + it('deletes the table a host approved through its own approval channel', async () => { await backend.close(); backend = await startFakeBackend(({ query }) => { @@ -175,9 +214,10 @@ describe('the plan names what the call acts on', () => { }); const tool = constructiveDbTools.find(({ name }) => name === 'delete_table')!; const event = { toolName: tool.name, toolCallId: 'delete-2', input: { table_name: 'posts' } }; - const decision = await createConstructiveGatePolicy(constructiveGateDeps()).resolvePrompt(event, cwd); + const policy = createConstructiveGatePolicy(constructiveGateDeps()); + const decision = await policy.resolvePrompt(event, cwd); if (decision.kind !== 'ask') throw new Error('expected a card'); - rememberApprovedTable(event.toolCallId, cwd, decision.prompt.target); + recordApproval(event.toolCallId, cwd, { id: approvalId({ action: tool.name, input: event.input, cwd, plan: decision.prompt }), gate: policy }); const result = await tool.execute(event.input, { cwd, toolCallId: event.toolCallId }); diff --git a/agentic/db-tools/__tests__/host.test.ts b/agentic/db-tools/__tests__/host.test.ts index a3ad8c0b30..9f2e1c4037 100644 --- a/agentic/db-tools/__tests__/host.test.ts +++ b/agentic/db-tools/__tests__/host.test.ts @@ -6,6 +6,8 @@ import constructiveDbTools, { getHost, toolSchema } from '../src'; +import { resolveOrgName } from '../src/context'; +import { type FakeBackend, startFakeBackend } from './fake-backend'; describe('host configuration', () => { it('getHost throws before configureHost', () => { @@ -86,3 +88,31 @@ describe('constructiveDbTools', () => { } }); }); + +describe('resolveOrgName', () => { + let backend: FakeBackend; + beforeEach(async () => { + backend = await startFakeBackend(() => ({ data: { users: { nodes: [{ displayName: 'Acme', username: 'acme' }] } } })); + }); + afterEach(async () => { + await backend.close(); + }); + + it('asks the auth endpoint the host names', async () => { + configureHost({ + account: () => ({ userId: 'ME', accessToken: 'account-bearer' }), + backendConfig: () => ({ apiEndpoint: backend.endpoint('graphql.localhost'), authEndpoint: backend.endpoint('identity.localhost') }), + }); + expect(await resolveOrgName('owner-1')).toBe('Acme'); + expect(backend.requests.map((request) => request.host.split(':')[0])).toEqual(['identity.localhost']); + }); + + it('sends the bearer nowhere when the host names no auth endpoint and the api host gives none to derive', async () => { + configureHost({ + account: () => ({ userId: 'ME', accessToken: 'account-bearer' }), + backendConfig: () => ({ apiEndpoint: backend.endpoint('graphql.localhost') }), + }); + expect(await resolveOrgName('owner-1')).toBeUndefined(); + expect(backend.requests).toEqual([]); + }); +}); diff --git a/agentic/db-tools/__tests__/provision-guard.test.ts b/agentic/db-tools/__tests__/provision-guard.test.ts index 77f350af51..150df1d81b 100644 --- a/agentic/db-tools/__tests__/provision-guard.test.ts +++ b/agentic/db-tools/__tests__/provision-guard.test.ts @@ -310,6 +310,20 @@ describe('replace mode', () => { expect(persistBinding).toHaveBeenCalledWith(expect.objectContaining({ databaseId: 'd0000000-0000-4000-8000-000000000002', replaces: 'd0000000-0000-4000-8000-0000000000a0' })); }); + it('keeps the Windows line endings of a .env when it archives the old binding', async () => { + writeEnv('APP_NAME=shop\r\nDATABASE_ID=d0000000-0000-4000-8000-0000000000a0\r\nDATABASE_NAME=myapp\r\n'); + mockProbe.mockImplementation(async ({ databaseId }) => + databaseId === 'd0000000-0000-4000-8000-0000000000a0' ? { status: 'missing', databaseId } : found(databaseId), + ); + mockRequestDatabase.mockResolvedValue(requested(completed('a0000000-0000-4000-8000-000000000002', 'd0000000-0000-4000-8000-000000000002'))); + + const result = await hostProvision({ mode: 'replace', replaces: 'd0000000-0000-4000-8000-0000000000a0' }); + + expect(result).toMatchObject({ success: true }); + expect(envFile().split('\r\n')[0]).toBe('APP_NAME=shop'); + expect(envFile().replace(/\r\n/g, '')).not.toContain('\n'); + }); + it("refuses the tool's reprovision when the host turned it off", async () => { useHost({ toolReprovision: false, reprovisionHint: 'Approve the rebuild card in the app.' }); writeEnv('DATABASE_ID=d0000000-0000-4000-8000-0000000000a0\n'); @@ -339,6 +353,19 @@ describe('saving the binding', () => { expect(envFile()).toMatch(/^DATABASE_ID=d0000000-0000-4000-8000-000000000001$/m); }); + it('writes into a .env with Windows line endings in place, and keeps them', async () => { + mockRequestDatabase.mockResolvedValue(requested(completed('a0000000-0000-4000-8000-000000000001', 'd0000000-0000-4000-8000-000000000001'))); + writeEnv('# my app\r\nAPP_NAME=shop\r\nPORT=3000\r\n'); + + const result = await provision('myapp'); + + expect(result.details.success).toBe(true); + const lines = envFile().split('\r\n'); + expect(lines.slice(0, 3)).toEqual(['# my app', 'APP_NAME=shop', 'PORT=3000']); + expect(lines.filter((line) => line.startsWith('DATABASE_ID='))).toEqual(['DATABASE_ID=d0000000-0000-4000-8000-000000000001']); + expect(envFile().replace(/\r\n/g, '')).not.toContain('\n'); + }); + it('keeps the ticket when the host cannot save it, and the retry binds it without a second request', async () => { mockRequestDatabase.mockResolvedValue(requested(completed('a0000000-0000-4000-8000-000000000001', 'd0000000-0000-4000-8000-000000000001'))); mockFindTicket.mockResolvedValue(ticketRead(completed('a0000000-0000-4000-8000-000000000001', 'd0000000-0000-4000-8000-000000000001'))); diff --git a/agentic/db-tools/__tests__/schema-checks.test.ts b/agentic/db-tools/__tests__/schema-checks.test.ts index a83e82ffee..821c427d21 100644 --- a/agentic/db-tools/__tests__/schema-checks.test.ts +++ b/agentic/db-tools/__tests__/schema-checks.test.ts @@ -186,7 +186,7 @@ describe('no plan for a change that cannot work', () => { it('does not resolve a schema-qualified relation endpoint to an existing table in a different schema', async () => { const input = { name: 'todo', description: 'Todo', definition: { tables: [{ table_name: 'notes', policies: [{ $type: 'AuthzAllowAll' }] }], - relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'users', target_schema: 'app_private', field_name: 'parent_id' }], + relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'users', target_schema: 'app_private', field_name: 'parent_id', delete_action: 'c' }], } }; await backend.close(); backend = await startFakeBackend((request) => /schemas/.test(request.query) @@ -222,7 +222,7 @@ describe('no plan for a change that cannot work', () => { description: 'Notes', definition: { tables: [{ table_name: 'notes', policies: [{ $type: 'AuthzAppMembership' }] }], - relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'no_such_table', field_name: 'thing_id' }], + relations: [{ $type: 'RelationBelongsTo', source_table: 'notes', target_table: 'no_such_table', field_name: 'thing_id', delete_action: 'c' }], }, }, 'not-found', diff --git a/agentic/db-tools/src/blueprint/blueprint-schema.ts b/agentic/db-tools/src/blueprint/blueprint-schema.ts index 9cf0ad9691..fc12fb961d 100644 --- a/agentic/db-tools/src/blueprint/blueprint-schema.ts +++ b/agentic/db-tools/src/blueprint/blueprint-schema.ts @@ -60,8 +60,11 @@ export function ruleShapeProblems(rule: unknown, { withCheck = false }: { withCh if (envelope.privileges === undefined) problems.push({ path: 'privileges', code: 'privileges', message: '"privileges" is missing: give the privileges the rule covers, from select, insert, update and delete.' }); if (!withCheck && envelope.with_check !== undefined) problems.push({ path: 'with_check', code: 'not-supported', message: `"with_check" ${RULE_KEY_HINTS.with_check}` }); const validate = blueprintValidator('BlueprintPolicy'); + // The rule's own data is left out here, and checkRule reports what it lacks. + const dataLeftOut = (error: { instancePath: string; keyword: string; params: Record }) => + error.instancePath === '' && error.keyword === 'required' && error.params.missingProperty === 'data'; if (!validate(jsonCopy(withCheck ? envelope : unchecked))) { - for (const error of validate.errors.filter(reported)) { + for (const error of validate.errors.filter((error) => reported(error) && !dataLeftOut(error))) { const path = error.instancePath.split('/').slice(1).join('.'); if (error.keyword === 'additionalProperties') { const key = String(error.params.additionalProperty); diff --git a/agentic/db-tools/src/context.ts b/agentic/db-tools/src/context.ts index f7aa9f99d5..b177635411 100644 --- a/agentic/db-tools/src/context.ts +++ b/agentic/db-tools/src/context.ts @@ -412,15 +412,26 @@ export function deriveSubdomainEndpoint(baseEndpoint: string, firstLabel: string // binding health never depends on it. Authenticates with the account bearer // against the app-configured auth endpoint (the platform rejects per-database // keys, and the bearer never goes to a .env-pinned endpoint). +// The bearer goes only to an auth plane the host names, or to the one an `api.` host implies (api.x -> auth.x): +// any other host would be a guess. +function derivedAuthEndpoint(apiEndpoint: string | undefined): string | undefined { + if (!apiEndpoint) return undefined; + try { + if (new URL(apiEndpoint).hostname.split('.')[0] !== 'api') return undefined; + } catch { + return undefined; + } + return deriveSubdomainEndpoint(apiEndpoint, 'auth') || undefined; +} + export async function resolveOrgName(ownerId: string): Promise { try { const host = getHost(); const account = await host.account(); const bearer = account?.apiKey ?? account?.accessToken; if (!bearer) return undefined; - const apiEndpoint = host.backendConfig()?.apiEndpoint; - if (!apiEndpoint) return undefined; - const authEndpoint = deriveSubdomainEndpoint(apiEndpoint, 'auth'); + const config = host.backendConfig(); + const authEndpoint = config?.authEndpoint ?? derivedAuthEndpoint(config?.apiEndpoint); if (!authEndpoint) return undefined; const client = auth.createClient({ endpoint: authEndpoint, diff --git a/agentic/db-tools/src/gate.ts b/agentic/db-tools/src/gate.ts index a07a24e1ed..9f5953db60 100644 --- a/agentic/db-tools/src/gate.ts +++ b/agentic/db-tools/src/gate.ts @@ -42,7 +42,7 @@ async function toolPrecondition( if (!parsed.success) return blocked(invalidInput(parsed.error)); try { const ready = await check(parsed.data, cwd); - return ready.kind === 'ok' ? { kind: 'ready', ...ready.value } : blocked(ready.failure); + return ready.kind === 'ok' ? { kind: 'ready', ...ready.value, input: parsed.data as Record } : blocked(ready.failure); } catch (err) { // A check that cannot finish blocks the call rather than let it through. return blocked({ diff --git a/agentic/db-tools/src/host.ts b/agentic/db-tools/src/host.ts index 53334e3eea..bac33da14e 100644 --- a/agentic/db-tools/src/host.ts +++ b/agentic/db-tools/src/host.ts @@ -28,6 +28,8 @@ export type HostAccount = { export type HostBackendConfig = { apiEndpoint?: string; + /** The auth plane, when the host knows it; without it, it is derived only from an `api.` host. */ + authEndpoint?: string; modulesEndpoint?: string; agentEndpoint?: string; computeEndpoint?: string; diff --git a/agentic/db-tools/src/index.ts b/agentic/db-tools/src/index.ts index 694d7b01be..3e669792ab 100644 --- a/agentic/db-tools/src/index.ts +++ b/agentic/db-tools/src/index.ts @@ -1,7 +1,7 @@ import type { AnyHarnessTool } from '@agentic-kit/harness'; import { configureHost, type ToolsHost } from './host'; -import { constructiveDbTools } from './tools'; +import { constructiveDbTools, servedTools } from './tools'; export { constructiveDbTools }; @@ -169,34 +169,42 @@ export { } from './schema-model'; export { accessState, asWritten, grantWords, planRule, ruleWords, type WrittenRule } from './table-access'; export { toolSchema } from './tool-schema'; -export { describePolicyTypeTool, explainAccessTool, type ExplainedRule, type ExplainedTable, setAccessTool } from './tools/access'; -export { type AddPoliciesDetails, addPoliciesTool } from './tools/add-policies'; -export { addRecordsTool } from './tools/add-records'; -export { type AddRelationDetails, addRelationTool } from './tools/add-relation'; -export { type CreateApiKeyDetails, createApiKeyTool } from './tools/create-api-key'; -export { type DescribeSchemaDetails, describeSchemaTool } from './tools/describe-schema'; -export { createEntityTypeTool, deleteEntityTypeTool, type EntityTypesDetails, type EntityTypeSummary, listEntityTypesTool } from './tools/entity-types'; -export { +export { type ExplainedRule, type ExplainedTable } from './tools/access'; +export { type AddPoliciesDetails } from './tools/add-policies'; +export { type AddRelationDetails } from './tools/add-relation'; +export { type CreateApiKeyDetails } from './tools/create-api-key'; +export { type DescribeSchemaDetails } from './tools/describe-schema'; +export { type EntityTypesDetails, type EntityTypeSummary } from './tools/entity-types'; +export { type MutationDetails } from './tools/mutations'; +export { type ProvisionBlueprintDetails } from './tools/provision-blueprint'; +export { type RunCodegenDetails, type RunCodegenTimings } from './tools/run-codegen'; +export { type CreateTemplateDetails, createTemplatePreviewTables, type ListTemplatesDetails, type TemplateDetails } from './tools/templates'; +export const { + addPoliciesTool, + addRecordsTool, + addRelationTool, + applyTemplateTool, + createApiKeyTool, + createEntityTypeTool, createFieldTool, + createTemplateTool, + deleteEntityTypeTool, deleteFieldTool, deleteTableTool, - type MutationDetails, - retypeFieldTool, - updateFieldTool, -} from './tools/mutations'; -export { type ProvisionBlueprintDetails, provisionBlueprintTool } from './tools/provision-blueprint'; -export { provisionDatabaseTool, replaceDatabaseTool } from './tools/provision-database'; -export { type RunCodegenDetails, type RunCodegenTimings, runCodegenTool } from './tools/run-codegen'; -export { - applyTemplateTool, - type CreateTemplateDetails, - createTemplatePreviewTables, - createTemplateTool, deleteTemplateTool, - type ListTemplatesDetails, + describePolicyTypeTool, + describeSchemaTool, + explainAccessTool, + listEntityTypesTool, listTemplatesTool, - type TemplateDetails, - updateTemplateTool, -} from './tools/templates'; + provisionBlueprintTool, + provisionDatabaseTool, + replaceDatabaseTool, + retypeFieldTool, + runCodegenTool, + setAccessTool, + updateFieldTool, + updateTemplateTool +} = servedTools; export default constructiveDbTools; diff --git a/agentic/db-tools/src/provision-database/env-file.ts b/agentic/db-tools/src/provision-database/env-file.ts index 6d96823fc1..e8f19936d6 100644 --- a/agentic/db-tools/src/provision-database/env-file.ts +++ b/agentic/db-tools/src/provision-database/env-file.ts @@ -21,11 +21,14 @@ const QUOTES = new Set(['"', "'", '`']); type EnvEntry = { key: string | null; exported: boolean; lines: string[] }; +// The line ending the file uses, so an edit keeps it: a file written on Windows stays CRLF. +const eolOf = (content: string): string => (content.includes('\r\n') ? '\r\n' : '\n'); + // Group lines into entries: a key with the lines its value spans (a quoted // value left open continues to the line that closes it), or a non-entry line // (comment, blank, anything else) with a null key. function envEntries(content: string): EnvEntry[] { - const lines = content.split('\n'); + const lines = content.split(/\r?\n/); const entries: EnvEntry[] = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; @@ -66,9 +69,10 @@ export function mergeEnv(content: string, vars: EnvVars): string { out.push(...entry.lines); } } - let text = out.join('\n'); - for (const [key, value] of remaining) text += `\n${key}=${value}`; - return text.trim() + '\n'; + const eol = eolOf(content); + let text = out.join(eol); + for (const [key, value] of remaining) text += `${eol}${key}=${value}`; + return text.trim() + eol; } /** @@ -79,7 +83,7 @@ export function removeEnvKeys(content: string, keys: readonly string[]): string const keySet = new Set(keys); const entries = envEntries(content); const kept = entries.filter((entry) => entry.key === null || !keySet.has(entry.key)); - return kept.length === entries.length ? content : kept.flatMap((entry) => entry.lines).join('\n'); + return kept.length === entries.length ? content : kept.flatMap((entry) => entry.lines).join(eolOf(content)); } /** @@ -196,5 +200,5 @@ export function archiveBindingKeys( ? entry.lines.map((line) => `# archived ${archivedOn}: ${line.trim()}`) : entry.lines, ) - .join('\n'); + .join(eolOf(content)); } diff --git a/agentic/db-tools/src/tools/delete-records.ts b/agentic/db-tools/src/tools/delete-records.ts index ed5d9e570e..ef0898ec39 100644 --- a/agentic/db-tools/src/tools/delete-records.ts +++ b/agentic/db-tools/src/tools/delete-records.ts @@ -1,4 +1,4 @@ -import { type HarnessTool, type HarnessToolResult, identifierParam, listed, type PlanTarget, strictObject, takeApprovedTable, type ToolFailure } from '@agentic-kit/harness'; +import { type HarnessTool, type HarnessToolResult, identifierParam, listed, type PlanTarget, strictObject, type ToolFailure } from '@agentic-kit/harness'; import { buildPostGraphileDelete, toDeleteMutationName } from '@constructive-io/graphql-query/generators'; import { z } from 'zod'; @@ -186,7 +186,7 @@ export const deleteRecordsTool: HarnessTool recordsFailed(failure, { deletedCount: 0, tables: [] }); if (!approved?.rows) { // The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes diff --git a/agentic/db-tools/src/tools/index.ts b/agentic/db-tools/src/tools/index.ts index 1730cf4db8..be0b2326c0 100644 --- a/agentic/db-tools/src/tools/index.ts +++ b/agentic/db-tools/src/tools/index.ts @@ -1,4 +1,4 @@ -import type { AnyHarnessTool, ConfirmPreview, PlanTableAccess, PlanTarget } from '@agentic-kit/harness'; +import { type AnyHarnessTool, type ConfirmPreview, type PlanTableAccess, type PlanTarget, requireApproval } from '@agentic-kit/harness'; import type { BlueprintPolicy } from 'node-type-registry'; import { type TableAccessInput, tablePolicyFromBlueprint } from '../access'; @@ -49,9 +49,11 @@ import { updateRecordsReady, updateRecordsTool } from './update-records'; * * Plain `HarnessTool`s: a harness gets them by mapping them into its own tool * shape, which is the adapter's job, so this package stays free of any harness - * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding). + * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding). Each tool + * that changes something checks at apply that its plan is still the one the + * person approved (`requireApproval`), when a gated host gives it a call id. */ -export const constructiveDbTools: readonly AnyHarnessTool[] = [ +export const servedTools = gated({ provisionDatabaseTool, replaceDatabaseTool, describeSchemaTool, @@ -79,7 +81,14 @@ export const constructiveDbTools: readonly AnyHarnessTool[] = [ explainAccessTool, setAccessTool, describePolicyTypeTool, -]; +}); + +export const constructiveDbTools: readonly AnyHarnessTool[] = Object.values(servedTools); + +/** The tools by name, each that changes something wrapped by `requireApproval`, so no unwrapped one leaves the package. */ +function gated>(tools: T): T { + return Object.fromEntries(Object.entries(tools).map(([name, tool]) => [name, requireApproval(tool as AnyHarnessTool)])) as T; +} /** * What a plan names that the tool's check resolved: its target, the access of the tables it creates or changes, what @@ -151,6 +160,12 @@ const blueprintAccess = ({ definition, related }: Pick projectReady(cwd); const onDatabase = (check: (params: any, cwd: string) => Promise>) => targeting(check, (context) => databaseTarget(context)); +// A call on an existing table (and field) names it by id, so a plan made for one cannot apply to one that replaced it. +const onTable = ({ context, table, field }: { context: ProjectContext; table: { id: string }; field?: { id: string } }): PlanTarget => ({ + ...databaseTarget(context), + table: { id: table.id, schemaId: context.schemaId, ...(field ? { fieldId: field.id } : {}) }, +}); + /** * The check each db tool runs first, before it changes anything, by tool name, * for the gate to run on the same parsed params; its target is what the plan @@ -165,15 +180,12 @@ export const toolPreconditions: ReadonlyMap = new Map databaseTarget(context), blueprintAccess)], [addRelationTool.name, targeting(addRelationReady, (context) => databaseTarget(context), undefined, newRelationNotes)], - [deleteTableTool.name, targeting(deleteTableReady, ({ context, table }) => ({ - ...databaseTarget(context), - table: { id: table.id, schemaId: context.schemaId }, - }))], - [createFieldTool.name, targeting(createFieldReady, ({ context }) => databaseTarget(context), undefined, newFieldNote)], - [updateFieldTool.name, targeting(updateFieldReady, ({ context }) => databaseTarget(context))], - [retypeFieldTool.name, targeting(retypeFieldReady, ({ context }) => databaseTarget(context))], - [deleteFieldTool.name, targeting(deleteFieldReady, ({ context }) => databaseTarget(context))], - [addPoliciesTool.name, targeting(addPoliciesReady, ({ context }) => databaseTarget(context), addPoliciesPlan)], + [deleteTableTool.name, targeting(deleteTableReady, onTable)], + [createFieldTool.name, targeting(createFieldReady, onTable, undefined, newFieldNote)], + [updateFieldTool.name, targeting(updateFieldReady, onTable)], + [retypeFieldTool.name, targeting(retypeFieldReady, onTable)], + [deleteFieldTool.name, targeting(deleteFieldReady, onTable)], + [addPoliciesTool.name, targeting(addPoliciesReady, onTable, addPoliciesPlan)], [applyTemplateTool.name, targeting(applyTemplateReady, ({ context }) => databaseTarget(context), blueprintAccess)], [createTemplateTool.name, targeting((_params, cwd) => ownedProjectReady(cwd), accountTarget)], [updateTemplateTool.name, targeting(templateReady, ({ context }) => accountTarget(context))], @@ -201,5 +213,5 @@ export const toolPreconditions: ReadonlyMap = new Map databaseTarget(context), setAccessPlan)], + [setAccessTool.name, targeting(setAccessReady, onTable, setAccessPlan)], ]); diff --git a/agentic/db-tools/src/tools/mutations.ts b/agentic/db-tools/src/tools/mutations.ts index 29972b4150..178a72632a 100644 --- a/agentic/db-tools/src/tools/mutations.ts +++ b/agentic/db-tools/src/tools/mutations.ts @@ -1,4 +1,4 @@ -import { type HarnessTool, identifierParam, strictObject, takeApprovedTable, textParam, type ToolCallSuggestion, type ToolFailure } from '@agentic-kit/harness'; +import { type HarnessTool, identifierParam, strictObject, textParam, type ToolCallSuggestion, type ToolFailure } from '@agentic-kit/harness'; import { z } from 'zod'; import { toFieldDefault, toFieldType } from '../blueprint/field-type'; @@ -85,21 +85,9 @@ export const deleteTableTool: HarnessTool, ctx) { - const approved = ctx.toolCallId ? takeApprovedTable(ctx.toolCallId, ctx.cwd) : undefined; const ready = await deleteTableReady(params, ctx.cwd); if (ready.kind === 'failed') return fail(ready.failure); const { context, table } = ready.value; - if (ctx.toolCallId && ( - !approved || approved.database.id !== context.databaseId || approved.apiEndpoint !== context.controlApiEndpoint || - approved.account.userId !== context.accountUserId || approved.account.agent?.principalId !== context.accountAgent?.principalId || - approved.table?.schemaId !== context.schemaId || approved.table.id !== table.id - )) { - return fail({ - code: 'failed', - message: 'The current table and project do not match the approved delete target.', - hint: 'Review the current target and approve a new request.', - }); - } try { const result = await context.api.table .delete({ where: { id: table.id }, select: { id: true } }) diff --git a/agentic/dsh/__tests__/plugin.test.ts b/agentic/dsh/__tests__/plugin.test.ts index aada09c77c..893e1f92b4 100644 --- a/agentic/dsh/__tests__/plugin.test.ts +++ b/agentic/dsh/__tests__/plugin.test.ts @@ -66,8 +66,9 @@ const mutating = defineHarnessTool({ const gate = { effectOf: (toolName: string) => (toolName === mutating.name ? mutating.effect : undefined), - precondition: async (): Promise => ({ + precondition: async (_toolName: string, input: Record | undefined): Promise => ({ kind: 'ready', + input, target: { kind: 'database', database: { name: 'shop', id: 'db-1' }, apiEndpoint: 'http://api.localhost:3000/graphql', account: { userId: 'user-1' } } }), resolveTemplatePreview: async (): Promise => undefined diff --git a/agentic/harness/__tests__/gating.test.ts b/agentic/harness/__tests__/gating.test.ts index 3ad9389969..93a0dcedd0 100644 --- a/agentic/harness/__tests__/gating.test.ts +++ b/agentic/harness/__tests__/gating.test.ts @@ -1,10 +1,13 @@ +import { z } from 'zod'; + +import { approvalId, recordApproval, requireApproval } from '../src/gating/approval'; import { ConfirmGate, ConfirmGateDeps, createConfirmGate, GateHost } from '../src/gating/confirm-gate'; import { createConstructiveGatePolicy, type GateReadiness } from '../src/gating/constructive-policy'; import { createDeclineGuard } from '../src/gating/decline-guard'; import type { GatePolicy } from '../src/gating/policy'; import type { PlanRule, PlanTableAccess, PlanTarget } from '../src/gating/preview'; import { buildConfirmPrompt } from '../src/gating/prompts'; -import type { ToolEffect, ToolFailure } from '../src/tools/tool'; +import { defineHarnessTool, type ToolEffect, type ToolFailure } from '../src/tools/tool'; // What the precondition resolved: the bound database of the directory, and a new database's backend and account. const TARGET: PlanTarget = { @@ -14,7 +17,8 @@ const TARGET: PlanTarget = { account: { userId: 'user-1' }, }; const NEW_DATABASE: PlanTarget = { kind: 'account', apiEndpoint: 'http://api.localhost:3000/graphql', account: { userId: 'user-1' } }; -const READY: GateReadiness = { kind: 'ready', target: TARGET }; +// A fake check that takes the input as it is, the way a tool's parse leaves input it does not change. +const ready = (input: Record | undefined): GateReadiness => ({ kind: 'ready', target: TARGET, input }); type Harness = { gate: ConfirmGate; @@ -50,7 +54,7 @@ function createHarness(deps?: Partial): Harness { }; const gateDeps: ConfirmGateDeps = { effectOf: (toolName) => EFFECTS[toolName], - precondition: async () => READY, + precondition: async (_toolName, input) => ready(input), resolveTemplatePreview: async () => undefined, ...deps, }; @@ -184,7 +188,7 @@ describe('confirm gate: declines are respected', () => { const { gate, host } = createHarness({ precondition: async (toolName, input, cwd) => { seen.push([toolName, input, cwd]); - return READY; + return ready(input); }, }); await gate.onToolCall(call('delete_table', 'tc-1', { table_name: 'posts' }), host, CWD); @@ -196,13 +200,14 @@ describe('confirm gate: declines are respected', () => { const DELETE_POSTS = ['- posts the table and all its rows', '! This cannot be undone.'].join('\n'); const policy = createConstructiveGatePolicy({ effectOf: (toolName) => EFFECTS[toolName], - precondition: async () => READY, + precondition: async (_toolName, input) => ready(input), resolveTemplatePreview: async () => undefined, }); const decision = await policy.resolvePrompt(call('delete_table', 'tc-1', { table_name: 'posts' }), CWD); expect(decision).toEqual({ kind: 'ask', prompt: { title: 'Delete table posts', message: DELETE_POSTS, target: TARGET }, + input: { table_name: 'posts' }, }); const shown: unknown[][] = []; @@ -299,6 +304,7 @@ describe('confirm gate: a host can supply its own policy', () => { resolvePrompt: async (event, cwd) => ({ kind: 'ask', prompt: { title: 'Run a destructive command?', message: `Allow \`${commandOf(event.input)}\`?`, target: { kind: 'workspace', cwd } }, + input: event.input, }), }; return { gate: createConfirmGate({ policy }), host, confirmed: () => confirmed }; @@ -653,3 +659,156 @@ describe('buildConfirmPrompt', () => { expect(scoped.message).toContain('read-only'); }); }); + +describe('the approval of one call', () => { + const plan = (message: string) => ({ title: 'Change it', message, target: TARGET }); + const base = { action: 'delete_table', input: { table_name: 'posts' }, cwd: CWD, plan: plan('- posts') }; + + it('is one id for the action, its input, the directory and the plan, and another when any of them differs', () => { + const id = approvalId(base); + expect(id).toMatch(/^[0-9a-f]{12}$/); + expect(approvalId({ ...base, input: { table_name: 'posts' } })).toBe(id); + for (const other of [{ action: 'delete_field' }, { input: { table_name: 'tags' } }, { cwd: '/tmp/other' }, { plan: plan('- tags') }]) { + expect(approvalId({ ...base, ...other })).not.toBe(id); + } + }); + + it('leaves out each part of the input the schema marks x-delivery, and nothing else', () => { + const schema = { + type: 'object', + properties: { + name: { type: 'string' }, + password_stdin: { type: 'boolean', 'x-delivery': true }, + nested: { type: 'object', properties: { from_stdin: { type: 'boolean', 'x-delivery': true }, size: { type: 'number' } } } + } + }; + const idOf = (input: Record) => approvalId({ action: 'login', input, schema, cwd: CWD, plan: plan('+ session') }); + expect(idOf({ name: 'n', password_stdin: true, nested: { from_stdin: true, size: 1 } })).toBe(idOf({ name: 'n', nested: { size: 1 } })); + expect(idOf({ name: 'm' })).not.toBe(idOf({ name: 'n' })); + expect(idOf({ name: 'n', nested: { size: 2 } })).not.toBe(idOf({ name: 'n', nested: { size: 1 } })); + }); +}); + +describe('requireApproval', () => { + let shown = 'first'; + const runs: unknown[] = []; + const gate: GatePolicy = { isGated: () => true, resolvePrompt: async (event) => ({ kind: 'ask', prompt: { title: 'Change it', message: shown, target: TARGET }, input: event.input }) }; + const tool = requireApproval( + defineHarnessTool({ + name: 'change_it', + label: 'Change it', + description: 'Change it.', + parameters: z.object({ name: z.string() }), + effect: 'write', + async execute(params) { + runs.push(params); + return { content: [{ type: 'text', text: 'changed' }], details: { changed: true } }; + } + }) + ); + const approve = async (toolCallId: string, input: Record) => { + const decision = await gate.resolvePrompt({ toolName: 'change_it', toolCallId, input }, CWD); + if (decision.kind !== 'ask') throw new Error('the test gate always asks'); + recordApproval(toolCallId, CWD, { id: approvalId({ action: 'change_it', input, cwd: CWD, plan: decision.prompt }), gate }); + }; + beforeEach(() => { + shown = 'first'; + runs.length = 0; + }); + + it('runs a call while its plan is still the one the person approved', async () => { + await approve('call-1', { name: 'a' }); + const result = await tool.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'call-1' }); + expect(result.failure).toBeUndefined(); + expect(runs).toEqual([{ name: 'a' }]); + }); + + it('refuses a call whose plan changed after the approval, or whose input is not the approved one, and changes nothing', async () => { + await approve('call-2', { name: 'a' }); + shown = 'second'; + expect((await tool.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'call-2' })).failure?.code).toBe('plan-changed'); + await approve('call-3', { name: 'a' }); + expect((await tool.execute({ name: 'b' }, { cwd: CWD, toolCallId: 'call-3' })).failure?.code).toBe('plan-changed'); + expect(runs).toEqual([]); + }); + + it('refuses a call id that no one approved, and an approval that was used already', async () => { + expect((await tool.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'never' })).failure?.code).toBe('not-approved'); + await approve('call-4', { name: 'a' }); + await tool.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'call-4' }); + expect((await tool.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'call-4' })).failure?.code).toBe('not-approved'); + expect(runs).toEqual([{ name: 'a' }]); + }); + + it('runs a call that carries no call id as it is, since no gated host made it', async () => { + await tool.execute({ name: 'a' }, { cwd: CWD }); + expect(runs).toEqual([{ name: 'a' }]); + }); + + it('gives the tool the approved target, with only the rows of the tables the person kept', async () => { + const rows = [{ tableName: 'companies', keys: ['k1'] }, { tableName: 'contacts', keys: ['c1', 'c2'] }]; + const rowsGate: GatePolicy = { isGated: () => true, resolvePrompt: async (event) => ({ kind: 'ask', prompt: { title: 'Delete', message: '', target: { ...TARGET, rows } }, input: event.input }) }; + const approved: unknown[] = []; + const deleteIt = requireApproval( + defineHarnessTool({ + name: 'delete_it', + label: 'Delete it', + description: 'Delete it.', + parameters: z.object({ name: z.string() }), + effect: 'write', + async execute(_params, ctx) { + approved.push(ctx.approved); + return { content: [{ type: 'text', text: 'deleted' }], details: {} }; + } + }) + ); + const decision = await rowsGate.resolvePrompt({ toolName: 'delete_it', toolCallId: 'call-5', input: { name: 'a' } }, CWD); + if (decision.kind !== 'ask') throw new Error('the test gate always asks'); + const id = approvalId({ action: 'delete_it', input: { name: 'a' }, cwd: CWD, plan: decision.prompt }); + recordApproval('call-5', CWD, { id, gate: rowsGate, tables: ['contacts', 'deals'] }); + recordApproval('call-6', CWD, { id, gate: rowsGate }); + + await deleteIt.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'call-5' }); + await deleteIt.execute({ name: 'a' }, { cwd: CWD, toolCallId: 'call-6' }); + + expect(approved).toEqual([{ ...TARGET, rows: [rows[1]] }, { ...TARGET, rows }]); + }); +}); + +describe('a plan shows every input that changes what the call does', () => { + const message = (tool: string, input: Record) => buildConfirmPrompt(tool, input, { target: TARGET }).message; + + it('add_relation: the delete action and whether the link is required', () => { + const link = { source_table: 'tasks', target_table: 'projects', field_name: 'project_id' }; + expect(message('add_relation', { ...link, delete_action: 'r', is_required: true })).toBe('+ tasks.project_id -> projects on delete restrict required'); + expect(message('add_relation', { ...link, delete_action: 'c' })).toBe('+ tasks.project_id -> projects on delete cascade'); + expect(message('add_relation', link)).toBe('+ tasks.project_id -> projects on delete no action'); + }); + + it('create_entity_type: each option it is created with', () => { + expect(message('create_entity_type', { name: 'team', prefix: 'team', parent_entity: 'org', is_visible: true, has_invites: true, has_storage: true })).toBe( + '+ entity type team a table for its rows, and tables for who belongs to each one\n prefix team, under org, visible, with invites, storage' + ); + }); + + it('apply_template and create_template: the name and the catalog text they give', () => { + expect(message('apply_template', { templateName: 'Blog', nameOverride: 'blog_two' })).toContain('+ blueprint blog_two from template Blog'); + const saved = message('create_template', { displayName: 'Blog', description: 'A blog', categories: ['content', 'cms'] }); + expect(saved).toContain('description: A blog'); + expect(saved).toContain('categories: content, cms'); + }); + + it('provision_blueprint: the nodes of each table, and the kind and delete action of each relation', () => { + const shown = message('provision_blueprint', { + definition: { + tables: [{ table_name: 'tasks', nodes: ['DataId', { $type: 'DataSoftDelete', data: {} }], fields: [{ name: 'title', type: 'text' }] }, { table_name: 'projects' }], + relations: [{ $type: 'RelationBelongsTo', source_table: 'tasks', target_table: 'projects', field_name: 'project_id', delete_action: 'c' }], + indexes: [{ table_name: 'tasks', columns: ['title'] }] + } + }); + expect(shown).toContain('nodes DataId, DataSoftDelete'); + expect(shown).toContain('+ link tasks -> projects (RelationBelongsTo, on delete cascade)'); + expect(shown).toContain('+ 1 index'); + }); +}); + diff --git a/agentic/harness/__tests__/plan.test.ts b/agentic/harness/__tests__/plan.test.ts index 79555adc31..ed7d830f21 100644 --- a/agentic/harness/__tests__/plan.test.ts +++ b/agentic/harness/__tests__/plan.test.ts @@ -95,7 +95,7 @@ describe('the rows of delete_records', () => { }; const policy = createConstructiveGatePolicy({ effectOf: () => 'write', - precondition: async () => ({ kind: 'ready', target: TARGET, preview, notes: ['deals has no sample rows left.'] }), + precondition: async (_toolName, input) => ({ kind: 'ready', target: TARGET, preview, notes: ['deals has no sample rows left.'], input }), resolveTemplatePreview: async () => undefined, }); const input = { tables: [{ table_name: 'companies', all: true }, { table_name: 'contacts', all: true }, { table_name: 'deals', sample: true }] }; @@ -113,6 +113,7 @@ describe('the rows of delete_records', () => { ].join('\n'), preview, }), + input, }); }); @@ -126,7 +127,7 @@ describe('the tables of create_template', () => { it('lists the tables the template takes under the change, one line each', async () => { const policy = createConstructiveGatePolicy({ effectOf: () => 'write', - precondition: async () => ({ kind: 'ready', target: TARGET }), + precondition: async (_toolName, input) => ({ kind: 'ready', target: TARGET, input }), resolveTemplatePreview: async () => ({ kind: 'template', displayName: 'Shop', blueprintName: 'shop-v1', tables: [products, { ...products, name: '', fields: [], policies: [] }] }), }); const decision = await policy.resolvePrompt({ toolName: 'create_template', toolCallId: 'tc-1', input: { displayName: 'Shop', blueprintName: 'shop-v1' } }, '/tmp'); diff --git a/agentic/harness/src/gating/approval.ts b/agentic/harness/src/gating/approval.ts new file mode 100644 index 0000000000..1b1a456861 --- /dev/null +++ b/agentic/harness/src/gating/approval.ts @@ -0,0 +1,116 @@ +import { createHash } from 'crypto'; + +import { type AnyHarnessTool, failureText, type HarnessToolResult, type ToolFailure } from '../tools/tool'; +import type { GatePolicy } from './policy'; +import type { ConfirmPrompt, PlanTarget } from './preview'; + +type Schema = { + [key: string]: unknown; + properties?: Record; + items?: Schema | Schema[]; + additionalProperties?: boolean | Schema; + anyOf?: Schema[]; + oneOf?: Schema[]; + allOf?: Schema[]; +}; + +// A value an approval leaves out: one that only says how a secret arrives (`--password-stdin`), which a run without a +// terminal adds to the approved command. +const unbound = (schema: Schema | undefined): boolean => + !!schema && (schema['x-delivery'] === true || [schema.anyOf, schema.oneOf, schema.allOf].some((branches) => branches?.some(unbound) ?? false)); + +// The value with its keys sorted and its unbound parts left out, so the same call always reads the same. +function bound(value: unknown, schema: Schema | undefined): unknown { + if (Array.isArray(value)) return value.map((item) => bound(item, Array.isArray(schema?.items) ? undefined : schema?.items)); + if (value === null || typeof value !== 'object') return value; + const extra = typeof schema?.additionalProperties === 'object' ? schema.additionalProperties : undefined; + return Object.fromEntries( + Object.keys(value) + .sort() + .flatMap((key) => { + const child = schema?.properties?.[key] ?? extra; + return unbound(child) ? [] : [[key, bound((value as Record)[key], child)]]; + }) + ); +} + +/** One call a person approves: the tool or command, its input (with its JSON Schema, which marks what only says how a secret arrives), the directory it acts in, and the plan they saw. */ +export type ApprovedCall = { action: string; input: unknown; schema?: object; cwd: string; plan: ConfirmPrompt }; + +/** + * The id of one approval. The same call with the same plan has the same id, and a change to the action, the input, + * the directory or the plan gives another, so an approval of one plan cannot apply another. The input parts its + * schema marks `x-delivery` are left out. + */ +export function approvalId({ action, input, schema, cwd, plan }: ApprovedCall): string { + const call = { action, input: bound(input, schema as Schema | undefined), cwd, plan: bound(plan, undefined) }; + return createHash('sha256').update(JSON.stringify(call)).digest('hex').slice(0, 12); +} + +/** + * What a person approved for one call, and the gate that made its plan, so the tool can make the plan again at apply. + * `tables`, for a plan that names rows by table, keeps only the rows of the tables the person left ticked. + */ +export type RecordedApproval = { id: string; gate: GatePolicy; tables?: readonly string[] }; + +const approvals = new Map(); +const keyOf = (toolCallId: string, cwd: string): string => JSON.stringify([cwd, toolCallId]); + +/** Keeps the approval of one call for 60 seconds, until the tool takes it at apply. */ +export function recordApproval(toolCallId: string, cwd: string, approval: RecordedApproval): void { + const key = keyOf(toolCallId, cwd); + approvals.set(key, approval); + setTimeout(() => { + if (approvals.get(key) === approval) approvals.delete(key); + }, 60_000).unref(); +} + +/** The approval of one call, once: a second take finds none. */ +export function takeApproval(toolCallId: string, cwd: string): RecordedApproval | undefined { + const key = keyOf(toolCallId, cwd); + const approval = approvals.get(key); + approvals.delete(key); + return approval; +} + +const kept = (target: PlanTarget, tables: readonly string[] | undefined): PlanTarget => + target.kind === 'database' && target.rows && tables ? { ...target, rows: target.rows.filter((row) => tables.includes(row.tableName)) } : target; + +function refused(failure: ToolFailure): HarnessToolResult { + return { content: [{ type: 'text', text: failureText(failure) }], details: { success: false, message: failureText(failure) }, failure }; +} + +/** + * `tool` with the check a gated host relies on at apply. A gated host passes a call id and records the approval + * under it (recordApproval); the call then runs only while the plan the approving gate makes now is the plan the + * person approved, for the same input and directory, and the tool gets that plan's target as `approved`. A call + * without a call id comes from a host that does not gate, and runs as it is. A read is returned unchanged. + */ +export function requireApproval(tool: T): T { + if (tool.effect === 'read') return tool; + const checked: AnyHarnessTool = { + ...tool, + async execute(params, ctx) { + if (!ctx.toolCallId) return tool.execute(params, ctx); + const approval = takeApproval(ctx.toolCallId, ctx.cwd); + if (!approval) { + return refused({ + code: 'not-approved', + message: `No approval of this ${tool.name} call is waiting (it was never given, was used, or ran out after 60 seconds), so nothing changed.`, + hint: 'Show the plan to the person, and call again once they approve it.' + }); + } + const decision = await approval.gate.resolvePrompt({ toolName: tool.name, toolCallId: ctx.toolCallId, input: params as Record }, ctx.cwd); + if (decision.kind === 'blocked') return refused(decision.failure); + if (approvalId({ action: tool.name, input: decision.input, cwd: ctx.cwd, plan: decision.prompt }) !== approval.id) { + return refused({ + code: 'plan-changed', + message: `The plan of this ${tool.name} call is no longer the one the person approved (what it acts on or its input changed), so nothing changed.`, + hint: 'Show the new plan to the person, and call again once they approve it.' + }); + } + return tool.execute(params, { ...ctx, approved: kept(decision.prompt.target, approval.tables) }); + } + }; + return checked as T; +} diff --git a/agentic/harness/src/gating/confirm-gate.ts b/agentic/harness/src/gating/confirm-gate.ts index c1deca55f2..dbfc1453e3 100644 --- a/agentic/harness/src/gating/confirm-gate.ts +++ b/agentic/harness/src/gating/confirm-gate.ts @@ -1,4 +1,5 @@ import { failureText, type ToolFailure } from '../tools/tool'; +import { approvalId, recordApproval } from './approval'; import type { ConstructiveGateDeps } from './constructive-policy'; import { createConstructiveGatePolicy } from './constructive-policy'; import { buildDeclineReason, createDeclineGuard } from './decline-guard'; @@ -20,31 +21,6 @@ import type { ConfirmPreview, PlanTarget } from './preview'; */ export type GateResult = { block: true; reason: string; failure?: ToolFailure } | undefined; -const approvedTables = new Map>(); - -/** - * Remember the table, or the rows, a person approved for a call, so the tool acts only on what the card named - * (`takeApprovedTable`). Every approval path calls it once the call is approved: this gate, and a host that asks - * through its own approval channel. A host that lets the person leave tables of a records delete out passes the - * target with only the tables they kept ticked in `rows`. - */ -export function rememberApprovedTable(toolCallId: string, cwd: string, target: PlanTarget): void { - if (target.kind !== 'database' || (!target.table && !target.rows)) return; - const key = JSON.stringify([cwd, toolCallId]); - const approved = structuredClone(target); - approvedTables.set(key, approved); - setTimeout(() => { - if (approvedTables.get(key) === approved) approvedTables.delete(key); - }, 60_000).unref(); -} - -export function takeApprovedTable(toolCallId: string, cwd: string) { - const key = JSON.stringify([cwd, toolCallId]); - const target = approvedTables.get(key); - approvedTables.delete(key); - return target; -} - export type GateHost = { /** Whether a confirmation UI is available (headless hosts return false). */ hasUI: boolean; @@ -103,7 +79,7 @@ export function createConfirmGate(options: ConfirmGateOptions): ConfirmGate { if (decision.kind === 'blocked') { return { block: true, reason: failureText(decision.failure), failure: decision.failure }; } - const { prompt } = decision; + const { prompt, input: parsed } = decision; if (!host.hasUI) { return { @@ -112,7 +88,8 @@ export function createConfirmGate(options: ConfirmGateOptions): ConfirmGate { }; } - const target = structuredClone(prompt.target); + // The id of the plan as the person sees it, before the host can touch it. + const id = approvalId({ action: event.toolName, input: parsed, cwd, plan: prompt }); const approved = await host.confirmTool( event.toolCallId, prompt.title, @@ -124,7 +101,7 @@ export function createConfirmGate(options: ConfirmGateOptions): ConfirmGate { declineGuard.recordDecline(event.toolName, input); return { block: true, reason: buildDeclineReason(event.toolName) }; } - rememberApprovedTable(event.toolCallId, cwd, target); + recordApproval(event.toolCallId, cwd, { id, gate: policy }); // An approved mutation changes state, so earlier declines may no longer // describe the same effect (e.g. a create_template preview derives from // the blueprint, not the input) — let them re-prompt with fresh eyes. diff --git a/agentic/harness/src/gating/constructive-policy.ts b/agentic/harness/src/gating/constructive-policy.ts index 555d96aaa7..aba7c3ff39 100644 --- a/agentic/harness/src/gating/constructive-policy.ts +++ b/agentic/harness/src/gating/constructive-policy.ts @@ -12,7 +12,7 @@ import { buildConfirmPrompt } from './prompts'; */ export type GateReadiness = | { kind: 'blocked'; failure: ToolFailure } - | { kind: 'ready'; target: PlanTarget; access?: PlanTableAccess[]; notes?: string[]; preview?: ConfirmPreview }; + | { kind: 'ready'; target: PlanTarget; access?: PlanTableAccess[]; notes?: string[]; preview?: ConfirmPreview; input: Record | undefined }; /** * Host capabilities the Constructive database policy needs. These are @@ -29,7 +29,8 @@ export type ConstructiveGateDeps = { * Why the call cannot run now, or what it acts on when it can. It must be * the check the tool itself makes before it changes anything (the same * project context, plane and sign-in), so the gate and the tool cannot - * disagree; the target it resolved goes into the plan. + * disagree; the target it resolved goes into the plan, and the input as the + * tool parses it goes into the decision. */ precondition( toolName: string, @@ -61,9 +62,9 @@ export function createConstructiveGatePolicy(deps: ConstructiveGateDeps): GatePo }, resolvePrompt: async (event, cwd) => { - const input = event.input; - const ready = await deps.precondition(event.toolName, input, cwd); + const ready = await deps.precondition(event.toolName, event.input, cwd); if (ready.kind === 'blocked') return { kind: 'blocked', failure: ready.failure }; + const { input } = ready; const prompt = buildConfirmPrompt(event.toolName, input, { target: ready.target, @@ -78,10 +79,10 @@ export function createConstructiveGatePolicy(deps: ConstructiveGateDeps): GatePo const preview = await deps.resolveTemplatePreview(cwd, blueprintName, displayName); if (preview) { const tables = preview.kind === 'template' ? templateTableLines(preview.tables).map((line) => ` ${line}`) : []; - return { kind: 'ask', prompt: { ...prompt, message: [prompt.message, ...tables].join('\n'), preview } }; + return { kind: 'ask', prompt: { ...prompt, message: [prompt.message, ...tables].join('\n'), preview }, input }; } } - return { kind: 'ask', prompt }; + return { kind: 'ask', prompt, input }; }, }; } diff --git a/agentic/harness/src/gating/policy.ts b/agentic/harness/src/gating/policy.ts index cc63136a64..3ec6c0eced 100644 --- a/agentic/harness/src/gating/policy.ts +++ b/agentic/harness/src/gating/policy.ts @@ -17,10 +17,12 @@ export type GateToolCallEvent = { * What happens to a gated call. `ask` puts the prompt in front of a human, * and the call runs only if they approve. `blocked` stops the call with the * failure, which says what is missing and the next step; the tool is not - * called. No decision lets a gated call run unasked. + * called. No decision lets a gated call run unasked. `input` is the call's + * input as the tool parses it, which an approval binds: every host binds the + * same value, whatever form its raw arguments took. */ export type GateDecision = - | { kind: 'ask'; prompt: ConfirmPrompt } + | { kind: 'ask'; prompt: ConfirmPrompt; input: Record | undefined } | { kind: 'blocked'; failure: ToolFailure }; /** diff --git a/agentic/harness/src/gating/preview.ts b/agentic/harness/src/gating/preview.ts index ec44209c31..a2a3cd6e62 100644 --- a/agentic/harness/src/gating/preview.ts +++ b/agentic/harness/src/gating/preview.ts @@ -66,7 +66,7 @@ export type PlanAccount = { userId: string; email?: string; agent?: PlanAgent }; */ export type PlanTarget = | { kind: 'database'; database: PlanDatabase; apiEndpoint: string; account: PlanAccount; appUserId?: string; - table?: { id: string; schemaId: string }; rows?: Array<{ tableName: string; keys: Array }> } + table?: { id: string; schemaId: string; fieldId?: string }; rows?: Array<{ tableName: string; keys: Array }> } | { kind: 'account'; apiEndpoint: string; account: PlanAccount; replaces?: PlanDatabase } | { kind: 'no-credential'; endpoint: string } | { kind: 'workspace'; cwd: string }; @@ -186,6 +186,7 @@ export function planTargetLines(target: PlanTarget): string[] { ['as', accountWords(target.account)], ...(target.appUserId ? [['app user', target.appUserId]] : []), ...(target.table ? [['schema id', target.table.schemaId], ['table id', target.table.id]] : []), + ...(target.table?.fieldId ? [['field id', target.table.fieldId]] : []), ]); } } diff --git a/agentic/harness/src/gating/prompts.ts b/agentic/harness/src/gating/prompts.ts index f231f719d0..15a432b91e 100644 --- a/agentic/harness/src/gating/prompts.ts +++ b/agentic/harness/src/gating/prompts.ts @@ -75,14 +75,15 @@ function blueprintMessage(input: Record | undefined, access: Pl return [ `+ ${tableLabel(name, schema)}`, ...under(newTableFieldLines(arr(table.fields).map(previewField), found)), + ...under(nodeLines(table)), ...under(accessOf(found, arr(table.policies))), + ...under(countedLines(table)), ]; }); - const links = arr(definition?.relations).map((relation) => { - const kind = typeof relation.relation_type === 'string' ? ` (${relation.relation_type})` : ''; - return `+ link ${String(relation.source_table ?? '?')} -> ${String(relation.target_table ?? '?')}${kind}`; - }); - return [...tables, ...links].join('\n'); + const links = arr(definition?.relations).map( + (relation) => `+ link ${String(relation.source_table ?? '?')} -> ${String(relation.target_table ?? '?')}${relationKind(relation)}` + ); + return [...tables, ...links, ...countedLines(definition)].join('\n'); } function accessMessage(tableName: string, access: PlanTableAccess[] | undefined, policies: Record[]): string { @@ -118,6 +119,60 @@ function templateChanges(input: Record | undefined): string[] { const UNDONE = '! This cannot be undone.'; +const DELETE_ACTIONS: Record = { c: 'cascade', r: 'restrict', n: 'set null', d: 'set default', a: 'no action' }; +const onDelete = (value: unknown): string => `on delete ${DELETE_ACTIONS[typeof value === 'string' ? value : 'a'] ?? String(value)}`; + +// The parts of a blueprint, of a table or of the whole definition, that a plan counts: name, singular, plural. +const COUNTED: ReadonlyArray<[string, string, string]> = [ + ['indexes', 'index', 'indexes'], + ['unique_constraints', 'unique constraint', 'unique constraints'], + ['check_constraints', 'check constraint', 'check constraints'], + ['full_text_searches', 'full-text search', 'full-text searches'], + ['entity_types', 'entity type', 'entity types'], + ['achievements', 'achievement', 'achievements'], + ['namespaces', 'namespace', 'namespaces'], + ['functions', 'function', 'functions'], + ['agents', 'agent', 'agents'], +]; + +function countedLines(part: Record | undefined): string[] { + const lines = COUNTED.flatMap(([key, one, many]) => { + const items = part?.[key]; + return Array.isArray(items) && items.length ? [`+ ${items.length} ${items.length === 1 ? one : many}`] : []; + }); + return [...lines, ...(obj(part?.storage) ? ['+ storage'] : [])]; +} + +const nodeName = (node: unknown): string | undefined => (typeof node === 'string' ? node : str(obj(node), '$type')); + +function nodeLines(table: Record): string[] { + const names = (Array.isArray(table.nodes) ? table.nodes : []).map(nodeName).filter((name): name is string => !!name); + return names.length ? [`nodes ${names.join(', ')}`] : []; +} + +function relationKind(relation: Record): string { + const facts = [ + ...(str(relation, '$type') ? [str(relation, '$type') as string] : []), + ...('delete_action' in relation ? [onDelete(relation.delete_action)] : []), + ...(relation.is_required === true ? ['required'] : []), + ]; + return facts.length ? ` (${facts.join(', ')})` : ''; +} + +function entityTypeOptions(input: Record | undefined): string[] { + const modules = ['invites', 'profiles', 'limits', 'levels', 'storage']; + const options = [ + ...(str(input, 'prefix') ? [`prefix ${str(input, 'prefix')}`] : []), + ...(str(input, 'parent_entity') ? [`under ${str(input, 'parent_entity')}`] : []), + ...(typeof input?.is_visible === 'boolean' ? [input.is_visible ? 'visible' : 'hidden'] : []), + ]; + const on = modules.filter((name) => input?.[`has_${name}`] === true); + const off = modules.filter((name) => input?.[`has_${name}`] === false); + if (on.length) options.push(`with ${on.join(', ')}`); + if (off.length) options.push(`without ${off.join(', ')}`); + return [...(options.length ? [options.join(', ')] : []), ...(str(input, 'description') ? [`description: ${str(input, 'description')}`] : [])]; +} + /** * What a person reads before a call changes something: what it acts on * (`target`, as the gate resolved it), and what the call does as a change @@ -181,7 +236,7 @@ function describeCall( const linked = str(input, 'target_table') ?? '?'; const message = str(input, 'relation_type') === 'many_to_many' ? `+ ${str(input, 'junction_table_name') ?? '?'} links ${source} <-> ${linked}` - : `+ ${source}.${str(input, 'field_name') ?? '?'} -> ${linked}`; + : `+ ${source}.${str(input, 'field_name') ?? '?'} -> ${linked} ${onDelete(input?.delete_action)}${input?.is_required === true ? ' required' : ''}`; return { title: `Link ${source} to ${linked}`, message }; } case 'delete_table': { @@ -231,14 +286,19 @@ function describeCall( case 'apply_template': { const name = str(input, 'templateName') ?? '?'; const lines = access?.flatMap((table) => [`+ ${tableLabel(table.table, table.schema)}`, ...under(planAccessLines(table))]); - return { title: `Apply template ${name}`, message: lines?.length ? lines.join('\n') : `+ the tables of template ${name}` }; + const blueprint = str(input, 'nameOverride') ? [`+ blueprint ${str(input, 'nameOverride')} from template ${name}`] : []; + return { title: `Apply template ${name}`, message: [...blueprint, ...(lines?.length ? lines : [`+ the tables of template ${name}`])].join('\n') }; } case 'create_template': { const source = str(input, 'blueprintName'); const name = str(input, 'displayName') ?? '?'; + const categories = Array.isArray(input?.categories) ? input.categories.filter((item): item is string => typeof item === 'string') : []; return { title: `Save template ${name}`, - message: `+ template ${name} from ${source ? `blueprint ${source}` : 'the latest blueprint of this project'}; private until made public`, + message: [ + `+ template ${name} from ${source ? `blueprint ${source}` : 'the latest blueprint of this project'}; private until made public`, + ...under([...(str(input, 'description') ? [`description: ${str(input, 'description')}`] : []), ...(categories.length ? [`categories: ${categories.join(', ')}`] : [])]), + ].join('\n'), }; } case 'update_template': { @@ -277,7 +337,10 @@ function describeCall( } case 'create_entity_type': { const name = str(input, 'name') ?? '?'; - return { title: `Create entity type ${name}`, message: `+ entity type ${name} a table for its rows, and tables for who belongs to each one` }; + return { + title: `Create entity type ${name}`, + message: [`+ entity type ${name} a table for its rows, and tables for who belongs to each one`, ...under(entityTypeOptions(input))].join('\n'), + }; } case 'delete_entity_type': { const id = str(input, 'entity_type_id') ?? '?'; diff --git a/agentic/harness/src/index.ts b/agentic/harness/src/index.ts index 741ad2522e..d8e06d2c3d 100644 --- a/agentic/harness/src/index.ts +++ b/agentic/harness/src/index.ts @@ -1,5 +1,6 @@ export * from './adapter'; export type { Blueprint } from './blueprint'; +export * from './gating/approval'; export * from './gating/approvals'; export * from './gating/confirm-gate'; export * from './gating/constructive-policy'; diff --git a/agentic/harness/src/tools/tool.ts b/agentic/harness/src/tools/tool.ts index 39c8d8a794..f351b8c874 100644 --- a/agentic/harness/src/tools/tool.ts +++ b/agentic/harness/src/tools/tool.ts @@ -1,5 +1,7 @@ import { z } from 'zod'; +import type { PlanTarget } from '../gating/preview'; + /** * A tool a harness can run, described without reference to any harness. * @@ -80,6 +82,8 @@ export const TOOL_FAILURE_CODES = [ 'provision-stuck', 'ticket-lost', 'unverified', + 'not-approved', + 'plan-changed', 'failed' ] as const; @@ -127,6 +131,8 @@ export const TOOL_FAILURE_MEANINGS: Record = { 'provision-stuck': 'The database is still not ready after many waits: the backend operator checks the provisioning jobs.', 'ticket-lost': 'The recorded request is gone from the backend, and nothing was created: calling again requests a new database.', unverified: 'The backend says the change applied, but reading it back failed: read the state before anything else.', + 'not-approved': 'No approval of this call is waiting, so nothing changed: show the plan to the person, and call again once they approve it.', + 'plan-changed': 'The plan is no longer the one the person approved, so nothing changed: show the new plan to the person, and call again once they approve it.', failed: 'A failure no other code covers: read the message, and give its error id to the backend operator.' }; @@ -206,6 +212,8 @@ export interface HarnessToolContext { readonly toolCallId?: string; /** Aborted when the run is cancelled, if the harness offers one. */ readonly signal?: AbortSignal; + /** The target of the plan the person approved, with only the rows of the tables they kept. `requireApproval` sets it. */ + readonly approved?: PlanTarget; } /** 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..9b98bb4801 --- /dev/null +++ b/agentic/mcp/__tests__/server.test.ts @@ -0,0 +1,408 @@ +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), input: 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-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-1)'); + expect(runs).toEqual([{ tool: 'create_thing', params: { thing_name: 'a' }, cwd }]); + }); + + it('shows the new plan when the plan changed while the form was open, and applies only the plan the person accepted', async () => { + const messages: string[] = []; + const client = await open({ + era, + elicit: (message) => { + messages.push(message); + if (messages.length === 1) state.database = 'db-2'; + return { action: 'accept', content: {} }; + } + }); + const result = await client.callTool({ name: 'create_thing', arguments: { thing_name: 'a' } }); + expect(messages).toHaveLength(2); + expect(messages[0]).toContain('database db-1 (id-1)'); + expect(messages[1]).toContain('database db-2 (id-1)'); + expect(envelope(result)).toEqual({ ok: true, data: { created: 'a' }, plan: planOf({ thing_name: 'a' }) }); + 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-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..2d2cc8327f --- /dev/null +++ b/agentic/mcp/src/server.ts @@ -0,0 +1,321 @@ +import { + type AnyHarnessTool, + approvalId, + callChange, + type Change, + type ConfirmPrompt, + failureText, + type GatePolicy, + type HarnessToolContent, + type HarnessToolResult, + normalizeToolParams, + recordApproval, + renderPlan, + type ToolCallSuggestion, + type ToolFailure +} from '@agentic-kit/harness'; +import { + type CallToolResult, + CLIENT_CAPABILITIES_META_KEY, + type ClientCapabilities, + createRequestStateCodec, + inputRequired, + type InputRequiredResult, + inputResponse, + McpServer, + type RequestStateCodec, + type ServerContext, + type ToolAnnotations +} from '@modelcontextprotocol/server'; +import { serveStdio as serveSdkStdio, type StdioServerHandle, StdioServerTransport } from '@modelcontextprotocol/server/stdio'; +import { randomBytes, randomUUID } from 'crypto'; +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.' +}; + +// What the preview's requestState carries back: the id of the plan the person was shown, signed by the server. +type Shown = { approval: string }; + +const CHANGED = 'The plan changed after it was shown, so this is the new plan.'; + +async function previewQuestion(plan: ConfirmPrompt, approval: string, codec: RequestStateCodec, changed = false): Promise { + return inputRequired({ + requestState: await codec.mint({ approval }), + inputRequests: { + [APPLY]: inputRequired.elicit({ + mode: 'form', + message: changed ? `${CHANGED}\n\n${renderPlan(plan)}` : renderPlan(plan), + 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 as a preview, with its approval id signed in the request state: a + * decline there changes nothing, and an accepted plan applies only while the + * plan made again on the answer is the same one, which the tool checks once more + * at apply. A changed plan is shown again. A client that cannot show questions + * gets no question. + */ +function handlerFor(tool: AnyHarnessTool, server: McpServer, options: McpToolsOptions, codec: RequestStateCodec) { + return async (params: Record, ctx: ServerContext): Promise => { + const run = async (approved?: string): Promise => { + const toolCallId = approved === undefined ? undefined : randomUUID(); + if (toolCallId) recordApproval(toolCallId, options.cwd, { id: approved, gate: options.gate }); + try { + return toolResult(await tool.execute(params, { cwd: options.cwd, ...(toolCallId ? { toolCallId } : {}), 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 approval = approvalId({ action: tool.name, input: change.decision.input, cwd: options.cwd, plan }); + const answer = previewAnswer(ctx); + if (!answer) return previewQuestion(plan, approval, codec); + 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); + } + if (ctx.mcpReq.requestState()?.approval !== approval) return previewQuestion(plan, approval, codec, true); + return withPlan(await run(approval), 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); + // One key for every server this factory makes, so a preview minted by one can be answered on another (HTTP). + const codec = createRequestStateCodec({ key: randomBytes(32) }); + return () => { + const server = new McpServer( + { name: options.name, version: options.version }, + { capabilities: { tools: {} }, instructions, requestState: { verify: codec.verify } } + ); + 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, codec) + ); + }); + 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/pi/__tests__/confirm-gate.test.ts b/agentic/pi/__tests__/confirm-gate.test.ts index 16f3d628c0..956e0d8a7f 100644 --- a/agentic/pi/__tests__/confirm-gate.test.ts +++ b/agentic/pi/__tests__/confirm-gate.test.ts @@ -10,7 +10,7 @@ const target: PlanTarget = { account: { userId: 'user-1' }, }; const deps = { - precondition: async (): Promise => ({ kind: 'ready', target }), + precondition: async (_toolName: string, input: Record | undefined): Promise => ({ kind: 'ready', target, input }), createTemplatePreviewTables: async () => ({ blueprintName: '', tables: [] }) as never, }; diff --git a/agentic/session/README.md b/agentic/session/README.md new file mode 100644 index 0000000000..eaed34cb5c --- /dev/null +++ b/agentic/session/README.md @@ -0,0 +1,131 @@ +# @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. The binaries (the `agent` CLI, the `constructive` CLI, the desktop app) read the same [appstash](https://github.com/constructive-io/appstash) store under the stash name `constructive`, so a sign-in through one is a sign-in through the others when its session records the whole backend it was issued for. A session that records only its auth endpoint, as the desktop app writes it, is not used (`issuer-mismatch`), and a new sign-in replaces it. 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 eight 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-backend` | The stored context holds an endpoint that fails the endpoint check (`plane`, `problem`), for example plain http to another machine; nothing is sent to it | +| `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`, `incomplete-backend` and `invalid-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, 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` stores a new session with a new key, or changes nothing. It runs these steps, filed under `context` when the caller passes one (see [Operations](#operations)): + +```text +check the store -> sign in [undo: end it] -> make a 30-day key [undo: revoke it] + -> store the endpoints [undo: put the old ones back] -> choose the context [undo: choose the old one] + -> COMMIT: store the session -> revoke the replaced key (previousKey) -> end the password sign-in +``` + +The stored bearer is the key, so no password sign-in session is left behind, and the new session records its issuer. A key is revoked only after its replacement is stored, so a failed store never leaves the old session pointing to a revoked key. When no key can be made, for example at the account's key limit, the sign-in throws a `SignInError` and stores nothing: at the limit, sign out of that backend first, which revokes the key this computer holds, or revoke a key in the app. 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, the key limit; `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. + +`signInTarget({ api?, context?, env?, store? })` is where a sign-in goes, the same for every binary: the backend the session resolves to (the environment's, else the context's), with all its planes, also when `api` names its api endpoint; another `api` is a new backend whose planes are derived. It is `no-backend` when nothing is chosen and no `api` is given, and `unusable` (with the session) when the resolved backend cannot be used. + +`signOut({ store, session })` acts on exactly the session `resolveSession` gave, so a CLI's `logout` removes what its `whoami` reported. It clears the stored session first, in every state, then revokes the API key at the auth endpoint the credential records (from `issuedFor`, else Desktop's `authEndpoint`, checked like any endpoint), with that credential's own bearer, never at whatever the context names now. It returns `{ kind: 'cleared', key }`, where `key` says whether the API key was `revoked`, `absent`, or `failed` and why (a session with no recorded issuer, or one that fails the check, sends nothing and says so). A key that was not revoked stays valid until it ends; revoke it in the app. 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. It takes a person's session only: an agent's session, usable or not, carries the person's context, so `signOut` refuses it and changes nothing. + +`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 cached token.** The cache only saves a mint: a token is used only for the key that minted it, so reading, writing or deleting the cache never fails an operation, and a token that cannot be cached is minted again next time. +- **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), `unreadable` when 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. When its entry cannot be removed after that, the answer is `entry-left`, and removing the agent again removes it. +- **A record edited by hand** that no longer parses makes the agent `unreadable`; `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. Every endpoint is https, or plain http on this machine only (a host whose last label is localhost, an address in 127/8, or ::1): plain http to another host would send the password and keys unencrypted, so it is refused (`EndpointError` with the reason `insecure`). A `BackendConfig` is made only by `backendFromEndpoints` or by reading the store, which checks a stored context the same way (one that fails is `invalid-backend`), so no request goes to an endpoint that was not checked. A request that carries a password or a key never follows a redirect: the error names where the server pointed, to use as the endpoint if it is the right one. 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 clears the session and revokes its key (check `key`: a revoke that failed leaves the key valid until it ends); `signIn` replaces a session of another backend itself, and revokes that session's key once the new session is stored. + +## Operations + +Every operation that changes the backend and the store runs as steps with one commit point. Before the commit, a failed step undoes the steps done so far, last first, and the error says what was undone; after the commit nothing is undone, and what is left cannot fail the operation. + +| Operation | Steps before the commit (undo) | Commit | After the commit | +| --- | --- | --- | --- | +| `signIn` | sign in (end it), make a key (revoke it), store the endpoints (put the old ones back), choose the context (choose the old one) | store the session | revoke the replaced key, end the sign-in | +| `signOut` | none | clear the session | revoke its key | +| `createAgent` | create the principal (delete it), set its scope, cap its keys, create its key | store the agent | none | +| `renewAgentKey` | create the new key (revoke it) | store it | drop the cached token, revoke the old key | +| `grantSchemaChanges`, `revokeSchemaChanges` | change the scope (set it back) | store the record | none | +| `removeAgent` | none | delete the principal | remove the entry (`entry-left` when it fails) | + +## Environment + +`getConstructiveEnv(env?)` is the one reader of these variables: it returns the `CONSTRUCTIVE_*` variables of `env`, or of the process when none is given, and every function here takes that view (`env` in `resolveSession`, `agentBinding`, `agentSession`, `sessionToolsHost`, `stashBaseDir`), so a host or a test passes its own. + +- `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..75cee5671f --- /dev/null +++ b/agentic/session/__tests__/agent.test.ts @@ -0,0 +1,774 @@ +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 { clearSession, openStore, saveSession } from '../src/account-store'; +import { AgentError, agentSession, createAgent, grantSchemaChanges, listAgents, removeAgent, renewAgentKey, revokeSchemaChanges, SCHEMA_READ_ONLY_MASK } from '../src/agent'; +import { signIn, signOut } from '../src/auth'; +import { SignInError } from '../src/auth-error'; +import { addBackend, backendFromEndpoints, ContextInUseError, removeBackend, 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'); +const diskFailure = () => { + throw Object.assign(new Error('disk failed'), { code: 'EIO' }); +}; +/** Make the next write of a record fail, as a full disk would. */ +const failNextSync = () => jest.spyOn(require('fs') as typeof fs, 'fsyncSync').mockImplementationOnce(diskFailure); + +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.each(['not a date', '2020-01-01T00:00:00Z'])('uses no minted token whose end is %j, and says to retry', async (end) => { + await create('helper'); + auth.tokenEnd = end; + expect(await agentSession({ store, name: 'helper', env: {} })).toMatchObject({ kind: 'agent-unusable', reason: 'mint-failed' }); + expect(fs.existsSync(cacheFile('helper'))).toBe(false); + }); + + 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('names the principal it made when storing the new agent fails and the principal cannot be deleted', async () => { + auth.fail.deletePrincipal = { status: 502 }; + const sync = failNextSync(); + try { + await expect(create('helper')).rejects.toThrow(/disk failed[\s\S]*could not be deleted/); + } finally { + sync.mockRestore(); + delete auth.fail.deletePrincipal; + } + }); + + it('revokes the new key when the renewed record cannot be stored, and keeps the old record and key', async () => { + await create('helper'); + const before = readAgent('helper'); + const sync = failNextSync(); + try { + await expect(renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' })).rejects.toThrow('disk failed'); + } finally { + sync.mockRestore(); + } + expect(readAgent('helper')).toEqual(before); + expect(auth.keys.map((key) => key.revoked)).toEqual([false, true]); + }); + + it("refuses to sign out with an agent's session, and keeps the person's session and key", async () => { + await create('helper'); + const agent = await agentSession({ store, name: 'helper', env: {} }); + const calls = auth.calls.length; + await expect(signOut({ store, session: agent as never })).rejects.toThrow('session of the agent "helper"'); + expect(auth.calls.length).toBe(calls); + expect(store.getCredentials(auth.context())).toBeTruthy(); + }); + + it("refuses to sign out with the session of an agent it cannot use, and keeps the person's session and key", async () => { + const unusable = await agentSession({ store, name: 'ghost', env: {} }); + const calls = auth.calls.length; + expect(unusable).toMatchObject({ kind: 'agent-unusable', context: auth.context() }); + await expect(signOut({ store, session: unusable as never })).rejects.toThrow('the agent "ghost"'); + expect(auth.calls.length).toBe(calls); + expect(store.getCredentials(auth.context())).toBeTruthy(); + }); + + it('leaves no temporary copy of the record, which holds the key, when writing it fails', async () => { + await create('helper'); + // The real module object: the source reads fs through it, so the failure reaches the write. + const sync = jest.spyOn(require('fs') as typeof fs, 'fsyncSync').mockImplementationOnce(() => { + throw Object.assign(new Error('disk failed'), { code: 'EIO' }); + }); + try { + await expect(grantSchemaChanges({ store, session: personSession(), name: 'helper' })).rejects.toThrow('disk failed'); + } finally { + sync.mockRestore(); + } + expect(fs.readdirSync(path.dirname(agentFile('helper'))).filter((file) => file.endsWith('.tmp'))).toEqual([]); + }); + + it('keeps a new agent whose record was published when removing its temporary copy fails', async () => { + const rm = jest.spyOn(require('fs') as typeof fs, 'rmSync').mockImplementationOnce(() => { + throw Object.assign(new Error('busy'), { code: 'EBUSY' }); + }); + try { + await create('helper'); + } finally { + rm.mockRestore(); + } + expect(fs.existsSync(agentFile('helper'))).toBe(true); + expect(auth.principals.size).toBe(1); + }); + + it('reads a record copied under another name as unreadable, so removing that name deletes no principal', async () => { + await create('helper'); + fs.copyFileSync(agentFile('helper'), agentFile('backup')); + expect(listAgents({ store }).find((info) => info.name === 'backup')).toMatchObject({ state: 'unreadable' }); + const before = auth.ops().length; + await removeAgent({ store, session: personSession(), name: 'backup' }); + expect(auth.ops().slice(before)).not.toContain('deletePrincipal'); + expect(auth.principals.size).toBe(1); + }); + + it('stores no renewed key whose end is not a date, revokes that key, and keeps the old one', async () => { + await create('helper'); + const before = readAgent('helper'); + auth.keyEnd = 'not-a-date'; + try { + await expect(renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' })).rejects.toMatchObject({ kind: 'server-error' }); + } finally { + auth.keyEnd = undefined; + } + expect(readAgent('helper')).toEqual(before); + expect(auth.keys.map((key) => key.revoked)).toEqual([false, true]); + }); + + it('revokes the old key on renewal even when the cached token cannot be removed', async () => { + await create('helper'); + await signedIn('helper'); + const cachedToken = path.join(home, '.constructive', 'cache', 'agents', auth.context(), 'helper.json'); + expect(fs.existsSync(cachedToken)).toBe(true); + const real = jest.requireActual('fs').rmSync; + const rm = jest.spyOn(require('fs') as typeof fs, 'rmSync').mockImplementation((file, options) => { + if (String(file) === cachedToken) throw Object.assign(new Error('denied'), { code: 'EACCES' }); + return real(file, options); + }); + try { + await renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' }); + } finally { + rm.mockRestore(); + } + expect(auth.keys[0].revoked).toBe(true); + }); + + it('treats a stored key end that is not a date as an unreadable record', async () => { + await create('helper'); + fs.writeFileSync(agentFile('helper'), JSON.stringify({ ...readAgent('helper'), keyExpiresAt: 'not-a-date' }), { mode: 0o600 }); + expect(await agentSession({ store, name: 'helper', env: {} })).toMatchObject({ kind: 'agent-unusable', reason: 'unreadable' }); + expect(listAgents({ store })).toEqual([expect.objectContaining({ name: 'helper', state: 'unreadable' })]); + }); + + it('quotes no part of a record that is not valid JSON in its problem, since the record holds the key', async () => { + await create('helper'); + fs.writeFileSync(agentFile('helper'), '{"name": "helper", "apiKey": cnc_SECRET_value_123}', { mode: 0o600 }); + const [info] = listAgents({ store }); + expect(info).toMatchObject({ state: 'unreadable', problem: expect.stringContaining('not valid JSON') }); + expect(JSON.stringify(info)).not.toContain('SECRET'); + }); + + 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, a valid key end date or the backend'] + ])('answers unreadable 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: 'unreadable' }); + 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: 'unreadable', 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('sets the scope back on the backend when the changed record cannot be stored, so nothing changed', async () => { + await create('helper'); + const principalId = readAgent('helper').principalId; + const sync = failNextSync(); + try { + await expect(grantSchemaChanges({ store, session: personSession(), name: 'helper' })).rejects.toThrow(/disk failed[\s\S]*set back on the backend/); + } finally { + sync.mockRestore(); + } + expect(auth.scopes.get(`${principalId}:2`)).toMatchObject({ allowedMask: SCHEMA_READ_ONLY_MASK }); + expect(readAgent('helper').schemaChanges).toBe(false); + }); + + it('says the entry is left when it cannot be removed after the principal is deleted, and removes it on the next try', async () => { + await create('helper'); + const rm = jest.spyOn(require('fs') as typeof fs, 'rmSync').mockImplementationOnce(diskFailure); + try { + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).resolves.toMatchObject({ + kind: 'entry-left', + name: 'helper', + problem: expect.stringContaining('could not be removed (disk failed)') + }); + } finally { + rm.mockRestore(); + } + expect(auth.principals.size).toBe(0); + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).resolves.toEqual({ kind: 'already-gone', name: 'helper' }); + expect(fs.existsSync(agentFile('helper'))).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('records no scope change the server did not confirm', async () => { + await create('helper'); + auth.answers.setPrincipalScope = { setPrincipalScope: { result: false } }; + await expect(grantSchemaChanges({ store, session: personSession(), name: 'helper' })).rejects.toThrow('did not confirm'); + expect(readAgent('helper').schemaChanges).toBe(false); + }); + + it('keeps the entry when the server does not confirm the delete of the principal', async () => { + await create('helper'); + auth.answers.deletePrincipal = { deletePrincipal: { result: false } }; + await expect(removeAgent({ store, session: personSession(), name: 'helper' })).rejects.toThrow('did not confirm'); + expect(fs.existsSync(agentFile('helper'))).toBe(true); + }); + + 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('refuses to remove a context while agents are stored under it, after the person signed out', async () => { + await create('helper'); + clearSession(store, auth.context()); + expect(() => removeBackend(store, auth.context())).toThrow(ContextInUseError); + expect(() => removeBackend(store, auth.context())).toThrow('helper'); + expect(store.loadContext(auth.context())).toBeTruthy(); + }); + + it('refuses to change the grant or the key of an agent another backend issued, and sends nothing', async () => { + await create('helper'); + const record = readAgent('helper'); + fs.writeFileSync(agentFile('helper'), JSON.stringify({ ...record, issuedFor: { ...record.issuedFor, apiEndpoint: 'https://api.other.example/graphql', authEndpoint: 'https://auth.other.example/graphql' } }), { mode: 0o600 }); + const before = auth.calls.length; + for (const change of [ + () => grantSchemaChanges({ store, session: personSession(), name: 'helper' }), + () => revokeSchemaChanges({ store, session: personSession(), name: 'helper' }), + () => renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' }) + ]) { + await expect(change()).rejects.toMatchObject({ kind: 'issuer-mismatch', message: expect.stringContaining('https://api.other.example/graphql') }); + } + expect(auth.calls.length).toBe(before); + }); + + it('removes only the record of an agent another backend issued, sends nothing, and names where its key still works', async () => { + await create('helper'); + const record = readAgent('helper'); + fs.writeFileSync(agentFile('helper'), JSON.stringify({ ...record, issuedFor: { ...record.issuedFor, apiEndpoint: 'https://api.other.example/graphql', authEndpoint: 'https://auth.other.example/graphql' } }), { mode: 0o600 }); + const before = auth.calls.length; + const removal = await removeAgent({ store, session: personSession(), name: 'helper' }); + expect(removal).toMatchObject({ kind: 'entry-removed', name: 'helper', problem: expect.stringContaining('https://api.other.example/graphql') }); + expect(removal).toMatchObject({ problem: expect.stringContaining(record.keyExpiresAt) }); + expect(auth.calls.length).toBe(before); + expect(fs.existsSync(agentFile('helper'))).toBe(false); + }); + + 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('a context with agents', () => { + it('asks to remove its agents before its session, since removing an agent needs the sign-in', async () => { + await create('helper'); + const { modulesEndpoint: modules, agentEndpoint: agent, computeEndpoint: compute } = auth.backend(); + const other = backendFromEndpoints({ api: 'https://api.other.example/graphql', auth: 'https://auth.other.example/graphql', modules, agent, compute }); + expect(store.getCredentials(auth.context())).toBeTruthy(); + expect(() => addBackend(store, other, auth.context())).toThrow(expect.objectContaining({ action: 'agents', agents: ['helper'] })); + expect(() => removeBackend(store, auth.context())).toThrow(expect.objectContaining({ action: 'remove', agents: ['helper'] })); + }); + + it('cannot move to other endpoints while agents of it are stored, by a sign-in or by addBackend once signed out', async () => { + await create('helper'); + const { modulesEndpoint: modules, agentEndpoint: agent, computeEndpoint: compute } = auth.backend(); + const other = backendFromEndpoints({ api: 'https://api.other.example/graphql', auth: 'https://auth.other.example/graphql', modules, agent, compute }); + const before = auth.calls.length; + await expect(signIn({ store, backend: other, context: auth.context(), email: 'owner@example.com', password: 'pw' })).rejects.toMatchObject({ action: 'agents' }); + clearSession(store, auth.context()); + expect(() => addBackend(store, other, auth.context())).toThrow(expect.objectContaining({ name: 'ContextInUseError', action: 'agents' })); + expect(auth.calls.length).toBe(before); + expect(store.loadContext(auth.context())?.targets.api.endpoint).toBe(auth.backend().apiEndpoint); + }); +}); + +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('says the old key was not revoked when the server does not confirm the revoke', async () => { + await create('helper'); + const old = readAgent('helper'); + auth.keys = auth.keys.filter((key) => key.id !== old.keyId); + const renewal = await renewAgentKey({ store, session: personSession(), password: 'pw', name: 'helper' }); + expect(renewal.previousKey).toMatchObject({ kind: 'failed', keyId: old.keyId }); + }); + + 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/session/__tests__/api-key.test.ts b/agentic/session/__tests__/api-key.test.ts new file mode 100644 index 0000000000..48013a797f --- /dev/null +++ b/agentic/session/__tests__/api-key.test.ts @@ -0,0 +1,45 @@ +import { API_KEY_NAME, buildCreateApiKeyInput, keyEndsSoon, parseMintedKey, 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({ days: 30 })).toEqual({ + keyName: API_KEY_NAME, + accessLevel: 'full_access', + mfaLevel: 'none', + expiresIn: { days: 30 } + }); + expect(API_KEY_NAME).toBe('agentic-cli'); + }); +}); + +describe('parseMintedKey', () => { + it('returns the minted key and maps expiresAt', () => { + expect(parseMintedKey({ apiKey: 'k', keyId: 'id', expiresAt: '2031-01-01' })).toEqual({ + apiKey: 'k', + keyId: 'id', + apiKeyExpiresAt: '2031-01-01' + }); + expect(parseMintedKey({ apiKey: 'k', keyId: 'id' })).toEqual({ apiKey: 'k', keyId: 'id' }); + }); + + it('throws when the backend returns no secret', () => { + expect(() => parseMintedKey(undefined)).toThrow('createApiKey returned no API key.'); + expect(() => parseMintedKey({ keyId: 'id' })).toThrow('createApiKey returned no API key.'); + }); +}); + +describe('keyEndsSoon', () => { + const now = Date.parse('2026-08-03T00:00:00Z'); + + it('is false without an expiry or with an unparsable one', () => { + expect(keyEndsSoon({ expiresAt: undefined, now })).toBe(false); + expect(keyEndsSoon({ expiresAt: 'garbage', now })).toBe(false); + }); + + it('is true at or inside the 7-day window, false outside', () => { + const at = (deltaMs: number) => new Date(now + deltaMs).toISOString(); + 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); + }); +}); diff --git a/agentic/session/__tests__/auth.test.ts b/agentic/session/__tests__/auth.test.ts new file mode 100644 index 0000000000..9fb43d89bf --- /dev/null +++ b/agentic/session/__tests__/auth.test.ts @@ -0,0 +1,454 @@ +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 } | { redirect: string } | '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 ('redirect' in reply) { + res.statusCode = 307; + res.setHeader('location', reply.redirect); + res.end(); + 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(), 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('fails at the key limit and changes nothing: it revokes no key and keeps the stored session', async () => { + await login(); + auth.replies.createApiKey = (_call, n) => (n === 2 ? failure('API_KEY_LIMIT_REACHED') : minted(n)); + const error = await signInError(login()); + expect(error).toMatchObject({ kind: 'refused', code: 'API_KEY_LIMIT_REACHED' }); + expect(error.message).toContain('sign out of this backend first'); + expect(auth.ops().slice(3)).toEqual(['signIn', 'createApiKey', 'signOut']); + expect(loadSession(store)).toMatchObject({ apiKey: 'key-1', keyId: 'kid-1' }); + }); + + it('fails and keeps the stored session as it was when the same account cannot make a new key', async () => { + await login(); + const before = loadSession(store); + auth.replies.createApiKey = () => failure('API_KEYS_DISABLED'); + const error = await signInError(login()); + expect(error).toMatchObject({ kind: 'refused', code: 'API_KEYS_DISABLED' }); + expect(loadSession(store)).toEqual(before); + expect(auth.ops().slice(3)).toEqual(['signIn', 'createApiKey', 'signOut']); + }); + + it('refuses a redirect, so the password never goes to the URL the server names', async () => { + const other = new FakeAuth(); + await other.start(); + try { + auth.replies.signIn = () => ({ redirect: other.endpoint }); + const error = await signInError(login()); + expect(error).toMatchObject({ kind: 'server-error', code: 'HTTP_307' }); + expect(error.message).toContain(`redirect (HTTP 307) to ${other.endpoint}`); + expect(other.calls).toEqual([]); + expect(store.listContexts()).toEqual([]); + } finally { + await other.stop(); + } + }); + + 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('signIn checks the store before it changes anything on a backend', () => { + it('refuses a context that holds credentials it did not write, and sends nothing', async () => { + store.createContext('custom', { endpoint: auth.endpoint, targets: {} }); + store.setCredentials('custom', { token: 'a-token-another-tool-stored' }); + await expect(signIn({ store, backend: auth.backend(), context: 'custom', email: 'dev@example.com', password: 'pw' })).rejects.toThrow(ContextInUseError); + expect(auth.calls).toEqual([]); + expect(store.getCredentials('custom')).toMatchObject({ token: 'a-token-another-tool-stored' }); + }); + + it.each([ + ['the same account', 'user-1'], + ['another account', 'user-2'] + ])('stores the new session before it revokes the key it replaces (%s)', async (_case, userId) => { + await login(); + auth.replies.signIn = (_call, n) => signedIn(userId, n); + let storedAtRevoke: unknown; + auth.replies.revokeApiKey = () => { + storedAtRevoke = loadSession(store)?.keyId; + return revoked; + }; + await login(); + expect(storedAtRevoke).toBe('kid-2'); + }); +}); + +describe('a context that holds a session of another backend', () => { + it('is refused by addBackend with the session kept, and is replaced by signIn, which stores the new session before it revokes that key', async () => { + const other = new FakeAuth(); + await other.start(); + let storedAtRevoke: unknown; + other.replies.revokeApiKey = () => { + storedAtRevoke = loadSession(store, 'custom'); + return revoked; + }; + 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(storedAtRevoke).toMatchObject({ apiKey: 'key-1', issuedFor: auth.backend() }); + 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('says the key was not revoked when the server does not confirm the revoke', async () => { + auth.replies.revokeApiKey = () => ({ data: { revokeApiKey: { result: false } } }); + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, session()); + expect(await out()).toMatchObject({ kind: 'cleared', key: { kind: 'failed', keyId: 'kid-1', reason: expect.stringContaining('did not confirm') } }); + }); + + 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('says nothing is signed in where only CONSTRUCTIVE_API_ENDPOINT names another backend, and keeps the stored session', async () => { + selectBackend(store, addBackend(store, auth.backend()).name); + saveSession(store, session()); + await expect(out({ CONSTRUCTIVE_API_ENDPOINT: 'https://api.example.com/graphql' })).resolves.toEqual({ kind: 'not-signed-in', context: null }); + expect(store.getCredentials(auth.context())).not.toBeNull(); + 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..af39453e7e --- /dev/null +++ b/agentic/session/__tests__/fake-principals.ts @@ -0,0 +1,252 @@ +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(); + /** When set, the end a new key is reported with, in place of its real end: a malformed answer. */ + keyEnd: string | undefined; + /** The end the fake gives a minted access token, in place of its real one. */ + tokenEnd: string | undefined; + scopes = new Map(); + keys: Key[] = []; + sessions: Session[] = []; + /** Answer an op with this data instead of its normal behavior, as a server that does not confirm the change. */ + answers: Record = {}; + /** 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: op in this.answers ? this.answers[op] : 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: this.keyEnd ?? 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: this.tokenEnd ?? 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..71a0b20cd8 --- /dev/null +++ b/agentic/session/__tests__/session.test.ts @@ -0,0 +1,532 @@ +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, sessionProblem } 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; +} + +describe('the store an injected environment names', () => { + it('is opened, and not the one CONSTRUCTIVE_STASH_DIR names in process.env', () => { + signInStored(); + const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'session-home-')); + const saved = { stash: process.env.CONSTRUCTIVE_STASH_DIR, home: process.env.HOME }; + // The signed-in store is the ambient one; HOME is an empty directory, so the real store is never read. + process.env.CONSTRUCTIVE_STASH_DIR = home; + process.env.HOME = empty; + try { + expect(resolveSession({ env: {} }).kind).toBe('no-backend'); + } finally { + if (saved.stash === undefined) delete process.env.CONSTRUCTIVE_STASH_DIR; + else process.env.CONSTRUCTIVE_STASH_DIR = saved.stash; + if (saved.home === undefined) delete process.env.HOME; + else process.env.HOME = saved.home; + fs.rmSync(empty, { recursive: true, force: true }); + } + }); +}); + +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'], + ['http://api.example.com/graphql', 'insecure'], + ['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' })); + expect(() => backendFromEndpoints({ api: ep, auth: 'http://auth.example.com/graphql', modules: ep, agent: ep, compute: ep })) + .toThrow(expect.objectContaining({ reason: 'insecure', plane: 'auth' })); + }); +}); + +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('is no-backend when the active context has a name this package does not take, such as one another tool stored', () => { + store.createContext('My Backend', { endpoint: 'https://api.example.com/graphql', targets: {} }); + store.setCurrentContext('My Backend'); + expect(resolve()).toEqual({ kind: 'no-backend', context: null }); + }); + + it('is invalid-backend for a stored context with an endpoint that fails the check, and sends it nothing', () => { + const https = (plane: string) => ({ endpoint: `https://${plane}.example.com/graphql` }); + store.createContext('lan', { endpoint: 'https://api.example.com/graphql', targets: { api: https('api'), auth: { endpoint: 'http://auth.example.com/graphql' }, modules: https('modules'), agent: https('agent'), compute: https('compute') } }); + store.setCurrentContext('lan'); + const session = resolve(); + expect(session).toMatchObject({ kind: 'invalid-backend', context: 'lan', plane: 'auth', problem: expect.stringContaining('plain http') }); + expect(sessionProblem(session)).toContain('nothing is sent to it'); + }); + + 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('tells a plain http endpoint variable to use https', () => { + expect(resolve({ CONSTRUCTIVE_API_ENDPOINT: REMOTE.apiEndpoint, CONSTRUCTIVE_AUTH_ENDPOINT: 'http://auth.example.com/graphql' })).toMatchObject({ + kind: 'invalid-override', + variable: 'CONSTRUCTIVE_AUTH_ENDPOINT', + fix: 'Set CONSTRUCTIVE_AUTH_ENDPOINT to its https URL, or unset it; plain http is accepted only for this machine.' + }); + }); + + 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', () => { + // Same context name as REMOTE, other endpoints: the auth plane is elsewhere. + const stored = backendFromEndpoints({ api: 'https://api.example.com/graphql', auth: 'https://identity.example.net/graphql' }); + signInStored(stored); + expect(addBackend(store, stored)).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, authEndpoint: backend.authEndpoint, 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, authEndpoint: REMOTE.authEndpoint, 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..7091dcc63b --- /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.9.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..989211cbc9 --- /dev/null +++ b/agentic/session/src/account-store.ts @@ -0,0 +1,177 @@ +import { appstash, ConfigStore, createConfigStore } from 'appstash'; + +import type { BackendEndpoints } from './backend-store'; +import { type ConstructiveEnv, getConstructiveEnv, STASH_DIR_ENV } from './env'; + +/** + * 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'; + +export { STASH_DIR_ENV } from './env'; + +/** An empty value is an error: treating it as unset would open the real store under the home directory. */ +export function stashBaseDir(env: ConstructiveEnv = getConstructiveEnv()): 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(); + +/** + * The store under `baseDir`, or under the home directory when `baseDir` is + * undefined. Called with no argument, it reads CONSTRUCTIVE_STASH_DIR from the + * process's environment; a caller that resolved an injected environment passes its + * result, undefined included, so the ambient variable never overrides it. + */ +export function openStore(...args: [baseDir?: string | undefined]): ConfigStore { + const baseDir = args.length ? args[0] : stashBaseDir(); + 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: ConstructiveEnv = getConstructiveEnv()): 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 const isContextName = (name: unknown): name is string => typeof name === 'string' && CONTEXT_NAME.test(name) && !name.includes('..'); + +export function checkContextName(name: string): string { + if (!isContextName(name)) 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, as recorded: text from the disk, used to compare and never sent to + * unchecked. Absent for a session stored before it was recorded, or by another app. + */ + issuedFor?: BackendEndpoints; + /** 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 the five recorded endpoints, or undefined when it lacks one. */ +export function issuedForOf(value: unknown): BackendEndpoints | 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 BackendEndpoints; +} + +type StoredCredentials = Parameters[1] & { authEndpoint?: string; issuedFor?: BackendEndpoints }; + +/** + * 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; + // A name this package never writes, such as one another tool stored, is no context of ours: nothing is chosen. + if (!isContextName(name)) return null; + return store.loadContext(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..9755b6b731 --- /dev/null +++ b/agentic/session/src/agent-store.ts @@ -0,0 +1,239 @@ +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 { BackendEndpoints } 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; + /** The five endpoints the key was issued for, as recorded: compared with the context's, never sent to. */ + issuedFor: BackendEndpoints; + 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); + // The temporary file holds the key too, so it goes on every path once it exists. + try { + try { + fs.writeFileSync(fd, content); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + if (mode === 'create') fs.linkSync(tmp, file); + else fs.renameSync(tmp, file); + } catch (err) { + fs.rmSync(tmp, { force: true }); + throw err; + } + // Published: a copy left behind holds the same record, with the same mode and in the same directory as the + // record, so a failed removal exposes nothing new and must not read as a failed write. + try { + fs.rmSync(tmp, { force: true }); + } catch { + // The record is written; see above. + } +} + +/** 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] !== '') && + !Number.isNaN(Date.parse(r.keyExpiresAt as string)) && + 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 { + // The parser's message can quote the text around the error, which may be the key. + throw new AgentRecordUnreadable(file, 'is not valid JSON'); + } + if (!isRecord(value)) throw new AgentRecordUnreadable(file, 'lacks the principal, the key, a valid key end date or the backend of an agent'); + // A record copied under another name would make an operation on this name act on that agent's principal. + if (value.name !== name || value.context !== context) throw new AgentRecordUnreadable(file, `is the record of the agent "${value.name}" under "${value.context}", not of this name and context`); + 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, best effort (see `readCachedToken`): a session takes a cached token only for the + * key that minted it, so a token left behind is never used again. + */ +export function dropCachedToken(store: ConfigStore, context: string, name: string): void { + try { + fs.rmSync(tokenFile(store, context, name), { force: true }); + } catch { + // See readCachedToken. + } +} + +/** Delete the agent's record, then its cached token. Throws when the record cannot be deleted. */ +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. */ +/** + * The cached token, or null when there is none that can be read. The cache only saves a mint, so reading, writing + * and deleting it never fail an operation: a token that cannot be cached is minted again next time. + */ +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 { + return null; + } + return typeof value?.keyId === 'string' && typeof value.accessToken === 'string' && typeof value.accessExpiresAt === 'string' ? (value as CachedToken) : null; +} + +/** + * Cache a minted token, best effort (see `readCachedToken`). 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 { + try { + writeAtomic(tokenFile(store, context, name), JSON.stringify(token), 'replace'); + } catch { + // See readCachedToken. + } +} diff --git a/agentic/session/src/agent.ts b/agentic/session/src/agent.ts new file mode 100644 index 0000000000..18c1986134 --- /dev/null +++ b/agentic/session/src/agent.ts @@ -0,0 +1,627 @@ +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 { errorText, type KeyRevocation, revokeKey } from './api-key'; +import { endSignIn, passwordSignIn } from './auth'; +import { describeAuthError, errorCodes, isNetworkError, RedirectRefusedError, trackedFetch, withAuthTimeout } from './auth-error'; +import { type BackendConfig, differingPlanes, type Endpoint, readBackend } from './backend-store'; +import { type ConstructiveEnv, getConstructiveEnv } from './env'; +import { Operation, type StepFailure, undoneText } from './operation'; +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' + /** Another backend than the person's session issued the agent's key, and only that backend can change it. */ + | 'issuer-mismatch' + | '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 (err instanceof RedirectRefusedError) return new AgentError('server-error', `${what} failed: ${err.message}`, `HTTP_${err.status}`); + 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: Endpoint, 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, in one of four states: `ready`, `set-up-again` (its key has ended), `issuer-mismatch` (the + * context now names other endpoints), or `unreadable` (its record cannot be read; `problem` says why). 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: 'unreadable'; 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; +} + +/** The record of an agent the person's backend issued: only that backend can change its principal or its key. */ +function issuedRecord(store: ConfigStore, owner: SignedInPerson, name: string): AgentRecord { + const record = ownedRecord(store, owner.context, name); + if (differingPlanes(record.issuedFor, owner.backend).length > 0) { + throw new AgentError( + 'issuer-mismatch', + `The agent "${name}" was set up with the backend ${record.issuedFor.apiEndpoint}, not the one this context names now, so it was not changed. Remove the agent and add it again under this backend.` + ); + } + 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; + } +} + +/** + * An agent operation (`Operation`): a failure before its commit throws the AgentError it was (or `map` makes of it), + * with what was undone after its message. + */ +function agentOperation(map: (failure: StepFailure) => Error | undefined = () => undefined): Operation { + return new Operation((failure) => { + const tail = undoneText(failure.undone); + const cause = map(failure) ?? failure.cause; + const message = (text: string): string => (tail ? `${text} ${tail}` : text); + if (cause instanceof AgentError) return new AgentError(cause.kind, message(cause.message), cause.code); + return new Error(message(errorText(cause)), { cause }); + }); +} + +async function createPrincipal(endpoint: Endpoint, bearer: string, name: string, organization: string | undefined): Promise { + const principalId = await call(endpoint, bearer, 'Creating the agent', (client) => + client.mutation.createPrincipal( + { input: { name, 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.'); + return principalId; +} + +async function deletePrincipal(endpoint: Endpoint, bearer: string, principalId: string, what: string): Promise { + return call(endpoint, bearer, what, (client) => client.mutation.deletePrincipal({ input: { principalId } }, { select: { result: true } })); +} + +async function revokeAgentKey(endpoint: Endpoint, bearer: string, keyId: string, what: string): Promise { + const data = await call(endpoint, bearer, what, (client) => client.mutation.revokeApiKey({ input: { keyId } }, { select: { result: true } })); + if ((data as { revokeApiKey?: { result?: unknown } })?.revokeApiKey?.result !== true) { + throw new AgentError('server-error', `${what} failed: the server did not confirm that the key was revoked.`); + } +} + +async function setScope(endpoint: Endpoint, bearer: string, principalId: string, schemaChanges: boolean): Promise { + const data = 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 } } + ) + ); + if ((data as { setPrincipalScope?: { result?: unknown } })?.setPrincipalScope?.result !== true) { + throw new AgentError('server-error', 'Setting what the agent may change failed: the server did not confirm the change.'); + } +} + +/** 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: Endpoint, 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: Endpoint, 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.'); + } + if (Number.isNaN(Date.parse(key.expiresAt))) { + // A record with this end could not be read back, so the key is not kept. + const keyId = key.keyId; + const revoked = await revokeKey(keyId, (id) => revokeAgentKey(endpoint, bearer, id, 'Revoking a key with no valid end')); + throw new AgentError( + 'server-error', + `Creating the key of the agent failed: the backend gave its end as "${key.expiresAt}", which is not a date. ${revoked.kind === 'revoked' ? 'That key was revoked.' : `Revoke the key ${keyId} in the app.`} 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)); +} + +/** + * create the principal [undo: delete it] -> set its scope -> cap its keys -> create its key -> COMMIT: store the agent + * + * The steps after the first need no undo of their own: deleting the principal ends its scope and its key. + */ +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; + // Another add of this name may have finished since the first check. + const op = agentOperation(({ cause }) => ((cause as NodeJS.ErrnoException)?.code === 'EEXIST' ? nameTaken(agentName, context) : undefined)); + const principalId = await op.step('create the principal', () => createPrincipal(endpoint, bearer, agentName, organization), { + run: (id) => deletePrincipal(endpoint, bearer, id, 'Deleting the half-made agent'), + undone: 'The principal it made was deleted again.', + notUndone: (id, reason) => `The principal ${id} it made could not be deleted (${reason}); delete it from the app.` + }); + await op.step('set its scope', () => setScope(endpoint, bearer, principalId, allowSchemaChanges)); + await op.step('cap its keys', () => capKeys(endpoint, bearer, principalId)); + const key = await op.step('create its key', () => 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 + }; + return op.commit('store the agent', () => { + const info = infoOf(store, record); + createAgentEntry(store, record); + return info; + }); +} + +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: 'unreadable', 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, at the checked auth endpoint of the context the key + * was bound to. The refresh token the backend makes is never asked for. + */ +async function mint(record: AgentRecord, authEndpoint: Endpoint): 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(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.'); + } + const ends = Date.parse(result.accessExpiresAt); + if (Number.isNaN(ends) || ends <= Date.now()) { + return unusable('mint-failed', `Issuing the agent "${record.name}" an access token failed: the backend gave it an end that is not a time in the future, so it was not used.`, '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 = getConstructiveEnv(), + rejectedToken +}: { + store: ConfigStore; + name: string; + context?: string; + env?: ConstructiveEnv; + 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, bound.backend.authEndpoint); + 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: + * + * change the scope [undo: change it back] -> COMMIT: store the record + */ +async function setSchemaChanges(store: ConfigStore, session: Session, name: string, schemaChanges: boolean): Promise { + const agentName = checkedName(name); + const owner = person(session); + const record = issuedRecord(store, owner, agentName); + const endpoint = owner.backend.authEndpoint; + const bearer = storedBearer(owner); + const op = agentOperation(); + await op.step('change the scope', () => setScope(endpoint, bearer, record.principalId, schemaChanges), { + run: () => setScope(endpoint, bearer, record.principalId, record.schemaChanges), + undone: 'The scope was set back on the backend, so nothing changed.', + notUndone: (_value, reason) => + `The backend kept the change, and setting it back failed too (${reason}), so the stored record does not show it. Run the same change again to store it.` + }); + const updated = { ...record, schemaChanges }; + return op.commit('store the record', () => { + const info = infoOf(store, updated); + writeAgent(store, updated); + return info; + }); +} + +/** 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 = issuedRecord(store, owner, agentName); + const endpoint = owner.backend.authEndpoint; + return withFreshSignIn(owner, password, async (bearer) => { + // create the new key [undo: revoke it] -> COMMIT: store it -> drop the cached token -> revoke the old key + const op = agentOperation(); + const key = await op.step('create the new key', () => createKey(endpoint, bearer, record.principalId, agentName), { + run: (made) => revokeAgentKey(endpoint, bearer, made.keyId, 'Revoking the new key that could not be stored'), + undone: 'The new key was revoked again; the old key still works.', + notUndone: (made, reason) => `The new key ${made.keyId} could not be revoked (${reason}); revoke it in the app. The old key still works.` + }); + const renewed: AgentRecord = { ...record, ...key }; + const agent = await op.commit('store the new key', () => { + const info = infoOf(store, renewed); + writeAgent(store, renewed); + return info; + }); + dropCachedToken(store, owner.context, agentName); + const previousKey = await revokeKey(record.keyId, (keyId) => revokeAgentKey(endpoint, bearer, keyId, 'Revoking the old key of the agent')); + return { agent, 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. An agent that another + * backend issued is `entry-removed`, with nothing sent: its problem names where + * its key still works. + */ +export type AgentRemoval = + | { kind: 'removed' | 'already-gone'; name: string } + /** The record could not be read, or another backend issued it: only the entry was removed, and `problem` says what is left. */ + | { kind: 'entry-removed'; name: string; problem: string } + /** The principal was deleted, so its key and tokens are ended, but its entry could not be removed: `problem` says how to finish. */ + | { kind: 'entry-left'; 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.` + }; + } + // Only the backend that issued the key can delete its principal, and this session belongs to another one: asking it + // would only hear that the principal is not there. + if (differingPlanes(record.issuedFor, owner.backend).length > 0) { + deleteAgent(store, owner.context, agentName); + return { + kind: 'entry-removed', + name: agentName, + problem: `The agent "${agentName}" was set up with the backend ${record.issuedFor.apiEndpoint}, not the one this context names now, so only its entry here was removed. Its key works on that backend until ${record.keyExpiresAt}: delete the principal "${agentName}" in the app of that backend to end it now.` + }; + } + // COMMIT: delete the principal (no undo: it ends the key and every token) -> remove the entry + const op = agentOperation(); + const kind = await op.commit('delete the principal', async (): Promise<'removed' | 'already-gone'> => { + try { + const data = await deletePrincipal(owner.backend.authEndpoint, storedBearer(owner), record.principalId, 'Removing the agent'); + const payload = (data as { deletePrincipal?: { result?: unknown } | null })?.deletePrincipal; + if (!payload) return 'already-gone'; + if (payload.result !== true) throw new AgentError('server-error', 'Removing the agent failed: the server did not confirm that its principal was deleted.'); + return 'removed'; + } catch (err) { + if (err instanceof AgentError && err.kind === 'not-found') return 'already-gone'; + 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; + } + }); + return op.settle( + 'remove the entry', + (): AgentRemoval => { + deleteAgent(store, owner.context, agentName); + return { kind, name: agentName }; + }, + (cause): AgentRemoval => ({ + kind: 'entry-left', + name: agentName, + problem: `The principal of the agent "${agentName}" was deleted, which ended its key and its tokens, but its entry here could not be removed (${errorText(cause)}). Remove the agent again to remove the entry.` + }) + ); +} diff --git a/agentic/session/src/api-key.ts b/agentic/session/src/api-key.ts new file mode 100644 index 0000000000..399d15ac30 --- /dev/null +++ b/agentic/session/src/api-key.ts @@ -0,0 +1,87 @@ +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 } : {}) + }; +} + +/** 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 }; + +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) }; + } +} diff --git a/agentic/session/src/auth-error.ts b/agentic/session/src/auth-error.ts new file mode 100644 index 0000000000..875fa84fde --- /dev/null +++ b/agentic/session/src/auth-error.ts @@ -0,0 +1,173 @@ +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'; + } +} + +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); + +/** The server answered with a redirect, which a request that carries a password or a key never follows. */ +export class RedirectRefusedError extends Error { + constructor( + endpoint: string, + readonly status: number, + location: string | null + ) { + const target = location === null ? undefined : shownLocation(location, endpoint); + super( + `The server at ${endpoint} answered with a redirect (HTTP ${status})${target ? ` to ${target}` : ''}. A request that carries a password or a key never follows a redirect, so nothing was sent there. If that is the right server, use its URL as the endpoint.` + ); + this.name = 'RedirectRefusedError'; + } +} + +function shownLocation(location: string, endpoint: string): string | undefined { + try { + const url = new URL(location, endpoint); + url.username = ''; + url.password = ''; + return url.toString(); + } catch { + return undefined; + } +} + +/** + * A fetch for one endpoint that tags a request with no answer, records the HTTP status of the last answer, and + * refuses a redirect, so a password or a key never goes to a URL that was not checked. + */ +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, redirect: 'manual' }); + } catch (err) { + throw new BackendUnreachableError(endpoint, err); + } + status = response.status; + if (REDIRECT_STATUSES.has(response.status)) throw new RedirectRefusedError(endpoint, response.status, response.headers.get('location')); + 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) || err instanceof RedirectRefusedError) 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 (err instanceof RedirectRefusedError) return new SignInError('server-error', err.message, `HTTP_${err.status}`); + 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..1b42ad28d9 --- /dev/null +++ b/agentic/session/src/auth.ts @@ -0,0 +1,391 @@ +import { auth } from '@constructive-io/sdk'; +import { ConfigStore } from 'appstash'; + +import { AccountSession, clearSession, loadSession, saveSession } from './account-store'; +import { API_KEY_DAYS, buildCreateApiKeyInput, errorText, KeyRevocation, MintedApiKey, parseMintedKey, revokeKey } from './api-key'; +import { describeAuthError, errorCodes, isNetworkError, RedirectRefusedError, SignInError, signInFailure, trackedFetch, withAuthTimeout } from './auth-error'; +import { + BackendConfig, + backendConflict, + backendFromEndpoints, + checkedEndpoint, + contextNameFor, + Endpoint, + EndpointError, + restoreBackend, + selectBackend, + writeBackend +} from './backend-store'; +import { type ConstructiveEnv } from './env'; +import { Operation, type StepFailure, undoneText } from './operation'; +import { type PersonSession, resolveSession, 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: Endpoint, 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 { + let data: { revokeApiKey?: { result?: unknown } } | undefined; + try { + data = (await withAuthTimeout(client.mutation.revokeApiKey({ input: { keyId } }, { select: REVOKE_KEY_SELECT }).unwrap(), endpoint)) as typeof data; + } catch (err) { + throw new Error(describeAuthError(err)); + } + if (data?.revokeApiKey?.result !== true) throw new Error('the server did not confirm that the key was revoked'); + } + }; +} + +/** + * Where a stored session's key is revoked: the auth endpoint that issued it, as recorded (`issuedFor`, else Desktop's + * `authEndpoint`), checked like any endpoint before a bearer goes there. A session that records only that endpoint + * still names its issuer, so its own token may go back there, though it is never used for anything else. + */ +function issuerOf(session: AccountSession): { kind: 'known'; endpoint: Endpoint } | { kind: 'unknown'; reason: string } { + const recorded = session.issuedFor?.authEndpoint ?? session.authEndpoint; + if (!recorded) return { kind: 'unknown', reason: NO_ISSUER }; + try { + return { kind: 'known', endpoint: checkedEndpoint('auth', recorded) }; + } catch (err) { + if (!(err instanceof EndpointError)) throw err; + return { kind: 'unknown', reason: `${err.message} So its key was not sent there to be revoked; it stays valid until it expires, unless you revoke it in the app.` }; + } +} + +/** Revoke a stored session's key at its issuer with the session's own bearer; never throws. */ +async function revokeStoredKey(session: AccountSession): Promise { + if (!session.keyId) return { kind: 'absent' }; + const issuer = issuerOf(session); + if (issuer.kind === 'unknown') return { kind: 'failed', keyId: session.keyId, reason: issuer.reason }; + return revokeKey(session.keyId, keyClient(issuer.endpoint, session.apiKey ?? session.accessToken).revoke); +} + +/** + * 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: Endpoint, 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: Endpoint, 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.`); + if (err instanceof RedirectRefusedError) return new SignInError('server-error', why, `HTTP_${err.status}`); + const code = errorCodes(err)[0]; + if (code === 'API_KEY_LIMIT_REACHED') { + return new SignInError( + 'refused', + `${why} The account holds as many live API keys as the backend allows: sign out of this backend first, which revokes the key this computer holds, or revoke a key you no longer use in the app, then sign in again.`, + code + ); + } + 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.`); +} + +/** A sign-in that failed before its commit, in the caller's terms: the store is as it was, and `undone` says what was given back. */ +function signInFailed({ step, cause, undone }: StepFailure, authEndpoint: string, context: string): Error { + const tail = undoneText(undone); + const withTail = (message: string): string => (tail ? `${message} ${tail}` : message); + switch (step) { + case 'sign in': + return cause instanceof Error ? cause : new Error(errorText(cause)); + case 'make an API key': { + const failure = noKeyFailure(cause, authEndpoint); + return new SignInError(failure.kind, withTail(failure.message), failure.code); + } + default: + return new Error(withTail(`Storing the sign-in under the context "${context}" failed (${errorText(cause)}), so nothing was stored. Check that the store can be written, then sign in again.`), { cause }); + } +} + +export interface SignInResult { + session: AccountSession; + context: string; + /** The key of the session this sign-in replaced, revoked once the new session is stored. */ + previousKey: KeyRevocation; +} + +/** + * Sign in to `backend` with email and password, and mint the person's 30-day API key inside the fresh step-up + * window, as one operation (`Operation`): + * + * check the store -> sign in [undo: end it] -> make a key [undo: revoke it] -> store the endpoints [undo: put + * the old ones back] -> choose the context [undo: choose the old one] -> COMMIT: store the session + * -> revoke the replaced key -> end the password sign-in + * + * So it stores a new session with a new key, or changes nothing, and a key is revoked only after its replacement is + * stored. A context the session cannot be filed under is refused before anything is sent (`ContextInUseError`). A + * failed sign-in, or one that makes no key, throws a `SignInError`. + */ +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 conflict = backendConflict(store, backend, context, { replacing: true }); + if (conflict) throw conflict; + const previous = loadSession(store, context); + const op = new Operation((failure) => signInFailed(failure, authEndpoint, context)); + + const signedIn = await op.step('sign in', () => passwordSignIn(authEndpoint, email, password), { + run: (fresh) => endSignIn(authEndpoint, fresh.accessToken), + undone: '', + notUndone: () => '' + }); + const issuer = keyClient(authEndpoint, signedIn.accessToken); + const minted = await op.step('make an API key', () => issuer.mint(), { + run: (key) => issuer.revoke(key.keyId), + undone: 'The new key was revoked again.', + notUndone: (key, reason) => `The new key ${key.keyId} could not be revoked (${reason}); revoke it in the app.` + }); + const storedContext = store.loadContext(context); + await op.step('store the endpoints', () => writeBackend(store, backend, context), { + run: () => restoreBackend(store, context, storedContext), + undone: '', + notUndone: (_value, reason) => `The old endpoints of "${context}" could not be put back (${reason}); store them again.` + }); + const settings = store.loadSettings(); + await op.step('choose the context', () => selectBackend(store, context), { + run: () => store.saveSettings(settings), + undone: '', + notUndone: (_value, reason) => `The context chosen before could not be chosen again (${reason}); choose it again.` + }); + const session = withKey({ ...signedIn, signedInAt: Date.now(), issuedFor: backend }, minted); + await op.commit('store the session', () => saveSession(store, session, context)); + + // The same account on the same auth plane revokes the replaced key with its new sign-in; anyone else with that key's own bearer. + let previousKey: KeyRevocation = { kind: 'absent' }; + if (previous?.keyId) { + const sameAccount = previous.userId === signedIn.userId && (previous.issuedFor?.authEndpoint ?? previous.authEndpoint) === authEndpoint; + previousKey = sameAccount ? await revokeKey(previous.keyId, issuer.revoke) : await revokeStoredKey(previous); + } + await op.settle('end the password sign-in', () => endSignIn(authEndpoint, signedIn.accessToken), (): void => undefined); + return { session, context, previousKey }; +} + +/** Where a sign-in goes: a backend and the context to file it under (null: its default name), or why there is none. */ +export type SignInTarget = + | { kind: 'target'; backend: BackendConfig; context: string | null; from: 'api-endpoint' | 'environment' | 'context' } + /** No backend is chosen and none was given: ask for an api endpoint, or say to pass one. */ + | { kind: 'no-backend' } + /** The session names a backend that cannot be used; `sessionProblem(session)` says why and what to do. */ + | { kind: 'unusable'; session: Extract }; + +interface TargetOptions { + /** An api endpoint the person gave. */ + api?: string; + /** The context to file the sign-in under: its backend is the target unless `api` names another. */ + context?: string; + env?: ConstructiveEnv; + store?: ConfigStore; +} + +/** + * The one choice of where a sign-in goes, for every binary. The backend the session resolves to (the environment's, + * else the context's) is the target with all its planes, also when `api` names its api endpoint. Another `api` is a + * new backend whose planes are derived (`backendFromEndpoints`, which throws `EndpointError`), filed under `context`. + */ +export function signInTarget(options: TargetOptions & { api: string }): Extract; +export function signInTarget(options: TargetOptions): SignInTarget; +export function signInTarget({ api, context, env, store }: TargetOptions): SignInTarget { + const state = resolveSession({ context, env, store }); + switch (state.kind) { + case 'signed-in': + case 'signed-out': + case 'issuer-mismatch': + if (api === undefined || api.trim() === state.backend.apiEndpoint) { + return { kind: 'target', backend: state.backend, context: state.context, from: state.source === 'env' ? 'environment' : 'context' }; + } + break; + case 'no-backend': + if (api === undefined) return { kind: 'no-backend' }; + break; + case 'incomplete-backend': + case 'invalid-backend': + case 'invalid-override': + case 'conflict': + if (api === undefined) return { kind: 'unusable', session: state }; + break; + default: { + const unknown: never = state; + throw new Error(`Unknown session state ${JSON.stringify(unknown)}.`); + } + } + return { kind: 'target', backend: backendFromEndpoints({ api }), context: context ?? null, from: 'api-endpoint' }; +} + +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 }; + +/** The name of the agent whose session this is, usable or not, or null for a person's session. */ +function agentOf(session: Session): string | null { + if (session.kind === 'agent-unusable') return session.agent; + return session.kind === 'signed-in' && session.source === 'agent' ? session.agent.name : null; +} + +/** + * Sign out of exactly the session `resolveSession` gave: clear what is stored under its context, then revoke its API + * key at the auth endpoint that issued it, with its own bearer. The session is cleared in every state, also when the + * context cannot be used, the issuer is not recorded or the revoke fails; `key` says what happened to the key, and a + * key that was not revoked stays valid until it ends. Throws the problem of an `invalid-override` or `conflict` + * session. Prints nothing. + */ +export async function signOut({ store, session }: { store: ConfigStore; session: PersonSession }): Promise { + if (session.kind === 'invalid-override' || session.kind === 'conflict') throw new Error(sessionProblem(session)); + // An agent's session, usable or not, carries the person's context, so going on would revoke the person's key and + // clear their sign-in. The type refuses one; this refuses it from a caller the compiler did not check. + const agent = agentOf(session); + if (agent) { + throw new Error( + `signOut ends the person's sign-in, and this is the session of the agent "${agent}", so nothing was signed out. ` + + "Pass the person's session to sign them out, or remove the agent with removeAgent to end its key." + ); + } + if (session.kind === 'signed-in' && session.source === 'env') return { kind: 'from-environment' }; + // Only CONSTRUCTIVE_API_ENDPOINT, naming another backend than the stored one: nothing is signed in there. + if (session.kind === 'signed-out' && session.source === 'env') return { kind: 'not-signed-in', context: null }; + const context = 'context' in session ? session.context : null; + if (!context || !store.getCredentials(context)) return { kind: 'not-signed-in', context }; + const stored = loadSession(store, context); + clearSession(store, context); + return { kind: 'cleared', context, key: stored ? await revokeStoredKey(stored) : { kind: 'absent' } }; +} + +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) || err instanceof RedirectRefusedError) 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..cdac1c9deb --- /dev/null +++ b/agentic/session/src/backend-store.ts @@ -0,0 +1,304 @@ +import { deriveSubdomainEndpoint } from '@agentic-kit/db-tools'; +import { ConfigStore } from 'appstash'; + +import { checkContextName, ContextNameError, currentContextName, loadSession } from './account-store'; +import { listAgentNames } from './agent-store'; + +/** Every Constructive plane a binary talks to, one GraphQL endpoint each, as text: what a record on disk holds. */ +export interface BackendEndpoints { + apiEndpoint: string; + authEndpoint: string; + modulesEndpoint: string; + agentEndpoint: string; + computeEndpoint: string; +} + +/** + * An endpoint that passed the endpoint check: an absolute https URL, or http on this machine, with no user name or + * password. The mark is a type only, so a value gets it from the check alone, through every copy of this package. + */ +export type Endpoint = string & { readonly __checkedEndpoint: true }; + +/** + * A backend whose five endpoints passed the endpoint check. Only `backendFromEndpoints` and the readers of the store + * make one, so no request can go to an endpoint that was never checked. + */ +export type BackendConfig = { readonly [K in keyof BackendEndpoints]: Endpoint }; + +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: BackendEndpoints, plane: Plane): string { + return config[KEY[plane]]; +} + +/** The planes whose endpoints differ, compared exactly (no case or slash folding). */ +export function differingPlanes(a: BackendEndpoints, b: BackendEndpoints): 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), holding an endpoint that fails the endpoint + * check (`plane`, `problem`), or stored under a name that is not a valid + * context name (`reason`). No function sends anything to a context that is not + * complete. + */ +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'; plane: Plane; problem: string } + | { name: string; current: boolean; status: 'invalid-name'; reason: string }; + +export type EndpointProblem = 'not-a-url' | 'scheme' | 'insecure' | 'userinfo' | 'not-derivable'; + +/** + * Whether `url` names this machine, where plain http never crosses a network: a host whose last label is localhost, + * an IPv4 address in 127/8, or ::1. + */ +export function isLoopback(url: URL): boolean { + const host = url.hostname; + return host.split('.').pop() === 'localhost' || /^127(\.\d{1,3}){3}$/.test(host) || host === '[::1]'; +} + +/** 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(/\/\/[^/@]*@/, '//'); + } +} + +/** `raw` as an endpoint of `plane`, or the `EndpointError` that says why it cannot be one. */ +export function checkedEndpoint(plane: Plane, raw: string): Endpoint { + 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.protocol === 'http:' && !isLoopback(url)) { + throw new EndpointError( + 'insecure', + plane, + `The ${plane} endpoint ${shown(endpoint)} uses plain http on a host that is not this machine, so the password and keys sent to it would cross the network unencrypted. Use its https URL; plain http is accepted only for localhost.` + ); + } + 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 as Endpoint; +} + +/** Five endpoints of a backend, each checked as given, none derived. Throws `EndpointError`. */ +export function checkedBackend(endpoints: BackendEndpoints): BackendConfig { + return Object.fromEntries(PLANES.map((plane) => [KEY[plane], checkedEndpoint(plane, endpoints[KEY[plane]] ?? '')])) as unknown as BackendConfig; +} + +/** + * 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: Endpoint, plane: Plane): Endpoint { + 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) as Endpoint; +} + +/** + * 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: Record = { apiEndpoint: api }; + 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 as unknown as BackendConfig; +} + +/** + * 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: BackendEndpoints): 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; + +/** A stored context read back: its endpoints pass the same check as new ones, or it is `incomplete` or `invalid`. */ +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 } : {}) }; + } + try { + const endpoints = Object.fromEntries(PLANES.map((plane) => [KEY[plane], targets[plane].endpoint])) as unknown as BackendEndpoints; + return { name, current, status: 'complete', backend: checkedBackend(endpoints) }; + } catch (err) { + if (!(err instanceof EndpointError)) throw err; + return { name, current, status: 'invalid', plane: err.plane, problem: err.message }; + } +} + +/** 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' | 'agents', + readonly agents: string[] = [] + ) { + super( + action === 'store' + ? `The context "${context}" holds a session that was not issued for these endpoints, or credentials another tool stored, so storing them would drop it while its key stays valid. Sign out of "${context}" first, which revokes that key, or store the backend under another name.` + : action === 'agents' + ? `The context "${context}" has agents set up with its endpoints (${agents.join(', ')}), and their keys work only there, so its endpoints cannot change. Remove those agents first (agent remove), or store the backend under another name.` + : agents.length + ? `The context "${context}" has agents (${agents.join(', ')}) whose keys stay valid after it is gone, with no entry left to remove them by, so it was not removed. Remove those agents first (agent remove), which ends their keys.` + : `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'; + } +} + +/** + * Why `config` cannot be stored under `name` now, or null. Credentials filed there must be a session this package + * wrote, issued for these endpoints; `replacing` takes any session of its own, which a sign-in revokes and replaces. + * A context whose agents were set up with its endpoints keeps them. The name is checked first, then the agents, then + * the session: removing an agent needs that sign-in, so the agents must go first. + */ +export function backendConflict(store: ConfigStore, config: BackendConfig, name: string, { replacing = false } = {}): ContextInUseError | null { + checkContextName(name); + const stored = readBackend(store, name); + const agents = stored ? listAgentNames(store, name) : []; + if (agents.length && (stored.status !== 'complete' || differingPlanes(stored.backend, config).length > 0)) return new ContextInUseError(name, 'agents', agents); + if (store.getCredentials(name)) { + const session = loadSession(store, name); + if (!session || (!replacing && (!session.issuedFor || differingPlanes(session.issuedFor, config).length > 0))) return new ContextInUseError(name, 'store'); + } + return null; +} + +/** + * 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), + * and when agents of the context were set up with other endpoints. + */ +export function addBackend(store: ConfigStore, config: BackendConfig, name: string = contextNameFor(config)): { name: string } { + const conflict = backendConflict(store, config, name); + if (conflict) throw conflict; + writeBackend(store, config, name); + return { name }; +} + +/** The context as stored, to put back with `restoreBackend`; null when there is none. */ +export type StoredContext = ReturnType; + +/** Write the endpoints under `name` with no check of what is filed there: for a caller that checked with `backendConflict`. */ +export function writeBackend(store: ConfigStore, config: BackendConfig, name: string): void { + const targets = Object.fromEntries(PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }])); + store.createContext(checkContextName(name), { endpoint: config.apiEndpoint, targets }); +} + +/** Put back a context `writeBackend` replaced: its old endpoints, or no context when there was none. */ +export function restoreBackend(store: ConfigStore, name: string, previous: StoredContext): void { + if (previous) store.createContext(checkContextName(name), { endpoint: previous.endpoint, targets: previous.targets }); + else store.deleteContext(checkContextName(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 agents are stored under it (`removeAgent` first, which needs the + * sign-in), then while a session is filed under it (`signOut` first, which revokes its key). + */ +export function removeBackend(store: ConfigStore, name: string): boolean { + const agents = listAgentNames(store, checkContextName(name)); + if (agents.length) throw new ContextInUseError(name, 'remove', agents); + if (store.getCredentials(name)) throw new ContextInUseError(name, 'remove'); + return store.deleteContext(name); +} diff --git a/agentic/session/src/env.ts b/agentic/session/src/env.ts new file mode 100644 index 0000000000..0f05b25989 --- /dev/null +++ b/agentic/session/src/env.ts @@ -0,0 +1,13 @@ +/** + * The CONSTRUCTIVE_* variables the agentic packages read, and the one place that reads them from the process. Every + * reader takes this view; a host or a test passes its own environment, and only the default comes from process.env. + */ +export type ConstructiveEnv = Readonly>; + +/** Base directory of the stash, for tests and isolated runs. Desktop reads the same variable. */ +export const STASH_DIR_ENV = 'CONSTRUCTIVE_STASH_DIR'; + +/** The CONSTRUCTIVE_* variables of `env` (default: the process's), as given: '' stays '', so a reader can refuse it. */ +export function getConstructiveEnv(env: NodeJS.ProcessEnv = process.env): ConstructiveEnv { + return Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith('CONSTRUCTIVE_'))); +} diff --git a/agentic/session/src/index.ts b/agentic/session/src/index.ts new file mode 100644 index 0000000000..5c252a9518 --- /dev/null +++ b/agentic/session/src/index.ts @@ -0,0 +1,66 @@ +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, SIGN_IN_AGAIN_WITHIN_MS } from './api-key'; +export { type CredentialCheck, signIn, type SignInResult, type SignInTarget, signInTarget, signOut, type SignOutResult, verifySession } from './auth'; +export { SignInError, type SignInErrorKind } from './auth-error'; +export { + addBackend, + type BackendConfig, + type BackendContext, + type BackendEndpoints, + backendFromEndpoints, + ContextInUseError, + contextNameFor, + type Endpoint, + EndpointError, + type EndpointProblem, + listBackends, + type Plane, + PLANES, + readBackend, + removeBackend, + selectBackend +} from './backend-store'; +export { type ConstructiveEnv, getConstructiveEnv } from './env'; +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/operation.ts b/agentic/session/src/operation.ts new file mode 100644 index 0000000000..7c6e058c45 --- /dev/null +++ b/agentic/session/src/operation.ts @@ -0,0 +1,112 @@ +import { errorText } from './api-key'; + +/** How to undo a step, and what the person reads when the undo worked or failed. */ +export interface Undo { + run(value: T): Promise | unknown; + /** Read when the undo worked; empty for an undo the person has nothing to do about. */ + undone: string; + notUndone(value: T, reason: string): string; +} + +/** One undo after a failure, as the person reads it. */ +export interface Undone { + step: string; + undone: boolean; + text: string; +} + +/** A step or the commit failed: `cause` is what it threw, `undone` what the steps before it gave back, last first. */ +export interface StepFailure { + step: string; + cause: unknown; + undone: Undone[]; +} + +/** The undo texts of a failure as one sentence run, for the end of its message. */ +export const undoneText = (undone: readonly Undone[]): string => + undone + .map(({ text }) => text) + .filter(Boolean) + .join(' '); + +type Phase = 'pending' | 'committed' | 'failed'; + +/** + * An operation that changes the backend and the store, as steps with one commit point: + * + * pending --step ok--> pending --commit ok--> committed --settle--> committed + * | | + * +--step fails--------+--commit fails--> failed (every done step undone, last first) + * + * Before the commit, a failed step or commit undoes the steps done so far and throws what `fail` makes of it. After + * the commit nothing is undone: what is left runs in `settle`, which cannot fail the operation. + */ +export class Operation { + private phase: Phase = 'pending'; + private undos: Array<{ step: string; run(): Promise }> = []; + + constructor(private readonly fail: (failure: StepFailure) => Error) {} + + /** Run a step before the commit. `undo` reverses it when a later step or the commit fails. */ + async step(name: string, run: () => Promise | T, undo?: Undo): Promise { + this.expect('pending', name); + let value: T; + try { + value = await run(); + } catch (cause) { + throw await this.rollBack(name, cause); + } + if (undo) { + this.undos.push({ + step: name, + run: async (): Promise => { + try { + await undo.run(value); + return { step: name, undone: true, text: undo.undone }; + } catch (err) { + return { step: name, undone: false, text: undo.notUndone(value, errorText(err)) }; + } + } + }); + } + return value; + } + + /** The point after which nothing is undone. A failed commit undoes every step, as a failed step does. */ + async commit(name: string, write: () => Promise | T): Promise { + this.expect('pending', name); + let value: T; + try { + value = await write(); + } catch (cause) { + throw await this.rollBack(name, cause); + } + this.phase = 'committed'; + this.undos = []; + return value; + } + + /** Work after the commit. It cannot fail the operation, so a throw becomes what `onError` makes of it. */ + async settle(name: string, run: () => Promise | T, onError: (cause: unknown) => T): Promise { + this.expect('committed', name); + try { + return await run(); + } catch (cause) { + return onError(cause); + } + } + + private async rollBack(step: string, cause: unknown): Promise { + this.phase = 'failed'; + const undone: Undone[] = []; + for (const undo of this.undos.reverse()) undone.push(await undo.run()); + this.undos = []; + return this.fail({ step, cause, undone }); + } + + private expect(phase: Phase, name: string): void { + if (this.phase !== phase) { + throw new Error(`"${name}" ran while the operation was ${this.phase}, but it may only run while it is ${phase}. This is a bug in @agentic-kit/session; report it.`); + } + } +} diff --git a/agentic/session/src/session.ts b/agentic/session/src/session.ts new file mode 100644 index 0000000000..4dcc15d4cb --- /dev/null +++ b/agentic/session/src/session.ts @@ -0,0 +1,404 @@ +import type { HostAccount, HostBackendConfig } from '@agentic-kit/db-tools'; +import { ConfigStore } from 'appstash'; + +import { checkContextName, currentContextName, loadSession, openStore, stashBaseDir } from './account-store'; +import { type AgentRecord, AgentRecordUnreadable, checkAgentName, readAgent } from './agent-store'; +import { BackendConfig, BackendEndpoints, backendFromEndpoints, differingPlanes, EndpointError, EndpointProblem, Plane, planeEndpoint, PLANES, readBackend } from './backend-store'; +import { type ConstructiveEnv, getConstructiveEnv, STASH_DIR_ENV } from './env'; + +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, a stored one that cannot be used, 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 } + /** A stored context holds an endpoint that fails the endpoint check (`plane`); `problem` says why. Nothing is sent to it. */ + | { kind: 'invalid-backend'; context: string; plane: Plane; problem: 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: BackendEndpoints | 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 or the backend refused it; the + * person renews the key. `unreadable`: its record cannot be read, so only + * removing the agent and adding it again helps. + * `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' | 'unreadable' | '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: ConstructiveEnv, name: string) => env[name] !== undefined; + +type EnvBackend = { kind: 'none' } | { kind: 'backend'; backend: BackendConfig } | Extract; + +function envBackend(env: ConstructiveEnv): 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 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 = err.reason === 'not-derivable' ? 'CONSTRUCTIVE_API_ENDPOINT' : endpointVar(err.plane); + return { kind: 'invalid-override', variable, problem: err.message, fix: ENDPOINT_FIX[err.reason](endpointVar(err.plane), env) }; + } +} + +/** What to set for each reason an endpoint variable is refused. */ +const ENDPOINT_FIX: Record string> = { + 'not-a-url': (variable) => `Set ${variable} to an absolute https URL, or unset it.`, + scheme: (variable) => `Set ${variable} to an https URL, or unset it.`, + insecure: (variable) => `Set ${variable} to its https URL, or unset it; plain http is accepted only for this machine.`, + userinfo: (variable) => `Set ${variable} to the URL with no user name or password in it, or unset it.`, + 'not-derivable': (_variable, env) => `Set every plane explicitly: ${ENDPOINT_VARS.filter((name) => !isSet(env, name)).join(', ')}.` +}; + +type EnvAccount = { kind: 'none' } | { kind: 'account'; account: SessionAccount } | Extract; + +function envAccount(env: ConstructiveEnv): 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: BackendEndpoints, b: BackendEndpoints) => 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 } : {}) }; + } + if (stored.status === 'invalid') return { kind: 'invalid-backend', context, plane: stored.plane, problem: stored.problem }; + 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; + /** The environment to read the CONSTRUCTIVE_* variables from. Default: the process's (getConstructiveEnv). */ + env?: ConstructiveEnv; + 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: ConstructiveEnv }): { 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 = getConstructiveEnv(), 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 = getConstructiveEnv(), 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 } : {}) }; + } + if (stored.status === 'invalid') return { kind: 'invalid-backend', context, plane: stored.plane, problem: stored.problem }; + 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('unreadable', 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, + authEndpoint: backend.authEndpoint, + 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-backend': + return `The backend context "${session.context}" cannot be used, and nothing is sent to it: ${session.problem} ${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.`; + } + case 'no-backend': + case 'signed-out': + case 'signed-in': + return null; + default: { + const unknown: never = session; + throw new Error(`Unknown session state ${JSON.stringify(unknown)}.`); + } + } +} diff --git a/agentic/session/src/tools-host.ts b/agentic/session/src/tools-host.ts new file mode 100644 index 0000000000..29e0c210df --- /dev/null +++ b/agentic/session/src/tools-host.ts @@ -0,0 +1,69 @@ +import type { ToolsHost } from '@agentic-kit/db-tools'; + +import { openStore, stashBaseDir } from './account-store'; +import { agentSession } from './agent'; +import { type ConstructiveEnv, getConstructiveEnv } from './env'; +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?: ConstructiveEnv; + 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 ?? getConstructiveEnv(); + 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/packages/node-type-registry/README.md b/packages/node-type-registry/README.md index 32631f6201..3cd9cadbf7 100644 --- a/packages/node-type-registry/README.md +++ b/packages/node-type-registry/README.md @@ -12,7 +12,7 @@

-Node type definitions for the Constructive blueprint system. Single source of truth for all Authz*, Data*, Relation*, View*, and Table* node types. +Node type definitions for the Constructive blueprint system: every Authz*, Data*, Relation*, View* and Table* node type, with the module presets and content presets. ## Usage @@ -23,7 +23,7 @@ import { allNodeTypes, AuthzDirectOwner, DataId } from 'node-type-registry'; console.log(AuthzDirectOwner.parameter_schema); // Get all node types as a flat array -console.log(allNodeTypes.length); // 52 +console.log(allNodeTypes.length); ``` ## Blueprint Types (generated) @@ -50,10 +50,10 @@ const definition: BlueprintDefinition = { { $type: 'DataDirectOwner', data: { include_id: false } }, ], fields: [ - { name: 'title', type: 'text', is_not_null: true }, - { name: 'description', type: 'text' }, + { name: 'title', type: { name: 'text' }, is_not_null: true }, + { name: 'description', type: { name: 'text' } }, ], - policies: [{ $type: 'AuthzDirectOwner' }], + policies: [{ $type: 'AuthzDirectOwner', data: { entity_field: 'owner_id' } }], }, ], relations: [ @@ -73,23 +73,22 @@ const definition: BlueprintDefinition = { }; ``` -### Regenerating types +### Where the source lives -When node type definitions are added or modified, regenerate with: +`src/` is a copy of the registry that the backend deploys, generated files included. Change a node type or a preset there, then copy it here from a checkout of the backend's repository: ```bash -cd graphql/node-type-registry && pnpm generate:types +pnpm sync:registry # copies src/ +pnpm sync:registry --check # lists the files that differ, and exits 1 if one does ``` -This produces `src/blueprint-types.generated.ts` from the TS node type source of truth. - ## Authz nodes: plain words and closed parameters Every `Authz*` node carries plain words, so a person or an agent can tell who a policy lets in without reading SQL: `summary` (one sentence), and `use_when`, `avoid_when` and `risks`. Each Authz node's `parameter_schema` is closed (`additionalProperties: false`), so a key the backend would store and ignore is refused instead of making a policy wider than meant. Keys the backend writes when it stores a policy (the member list it resolves, a capability mask, a compiled condition) are listed with `readOnly: true`: a stored policy may hold them, and a rule a caller writes leaves them out. A value that holds an Authz expression (`AuthzComposite`'s data, its `AND`/`OR`/`NOT` parts, `AuthzColumnSecurity.authz`) is marked `format: 'authz-expression'`: one key, which is `AND` or `OR` with a list, `NOT` with one expression, or the name of an Authz node with that node's data. A raw expression cannot be written. -`pnpm generate:reference --outdir ` writes the nodes as a Markdown reference page, `authz-node-reference.md`, with no date or version in it, so a copy that differs from a fresh render is stale. The page is made at dev time and is not part of the runtime exports. +`pnpm generate:reference --outdir ` writes two Markdown reference pages into the skills folder of the skills repository: the Authz nodes (`constructive-security/references/authz-node-reference.md`), and every other node with where a blueprint names it (`constructive-blueprints/references/node-reference.md`). They have no date or version in them, so a copy that differs from a fresh render is stale, and `--check` lists the stale pages and exits 1. The pages are made at dev time and are not part of the runtime exports. ## Blueprint JSON Schema diff --git a/packages/node-type-registry/__tests__/blueprint-schema.test.ts b/packages/node-type-registry/__tests__/blueprint-schema.test.ts index e9432c7cea..69193c220a 100644 --- a/packages/node-type-registry/__tests__/blueprint-schema.test.ts +++ b/packages/node-type-registry/__tests__/blueprint-schema.test.ts @@ -44,6 +44,61 @@ describe('the blueprint definition JSON Schema', () => { expect(errors(table({ policies: [{ ...TEAM, $type: 'AuthzNoSuchNode' }] }))).toContain('/tables/0/policies/0/$type must be equal to one of the allowed values'); }); + test('only policies with required caller inputs need data', () => { + expect(errors(table({ policies: [{ $type: 'AuthzEntityMembership' }] }))).toContain("/tables/0/policies/0 must have required property 'data'"); + expect(errors(table({ policies: [{ $type: 'AuthzAllowAll' }] }))).toEqual([]); + expect(errors(table({ policies: [{ $type: 'AuthzAllowAll', privileges: ['update'], with_check: { $type: 'AuthzEntityMembership' } }] }))).toContain( + "/tables/0/policies/0/with_check must have required property 'data'" + ); + }); + + test('each relation end names a table or a module table, not both', () => { + const module = { type: 'agent', scope: 'org', table: 'message' }; + const relates = (ends: Record) => ({ + ...table(), + relations: [{ $type: 'RelationBelongsTo', delete_action: 'r', ...ends }] + }); + expect(errors(relates({}))).not.toEqual([]); + expect(errors(relates({ source_table: 'projects' }))).not.toEqual([]); + expect(errors(relates({ source_table: 'projects', target_module: module }))).toEqual([]); + expect(errors(relates({ source_table: 'projects', target_module: module, delete_action: undefined }))).toContain( + "/relations/0 must have required property 'delete_action'" + ); + expect(errors(relates({ source_table: 'projects', target_schema: 'app_public', target_module: module }))).not.toEqual([]); + expect(errors(relates({ source_table: 'projects', target_table: 'messages', target_module: module }))).not.toEqual([]); + }); + + test('each table has one target and nodes that require data cannot use shorthand', () => { + const module = { type: 'agent', scope: 'org', table: 'message' }; + expect(errors({ tables: [{}] })).not.toEqual([]); + expect(errors({ tables: [{ module }] })).toEqual([]); + expect(errors(table({ module }))).not.toEqual([]); + const install = { type: 'agent', scope: 'org' }; + const provisions = { message: { policies: [TEAM] } }; + expect(errors({ tables: [{ module: install, provisions }] })).toEqual([]); + expect(errors({ tables: [{ module: install }] })).not.toEqual([]); + expect(errors({ tables: [{ module, provisions }] })).not.toEqual([]); + expect(errors({ tables: [{ module: install, provisions, policies: [TEAM] }] })).not.toEqual([]); + expect(errors(table({ nodes: ['DataId'] }))).toEqual([]); + expect(errors(table({ nodes: ['AuthzColumnSecurity'] }))).not.toEqual([]); + }); + + test.each(['AuthzValueExists', 'AuthzValueMatch'])('%s requires a nonempty join', ($type) => { + expect(errors(table({ policies: [{ $type, data: { ref_schema: 'app_public', ref_table: 'teams', join: [] } }] }))).toContain( + '/tables/0/policies/0/data/join must NOT have fewer than 1 items' + ); + }); + + test('junction policies use the same validation as table policies', () => { + const junction = (policy: Record) => ({ + ...table(), + relations: [{ $type: 'RelationManyToMany', source_table: 'projects', target_table: 'labels', policies: [policy] }] + }); + expect(errors(junction(TEAM))).toEqual([]); + expect(errors(junction({ $type: 'AuthzNoSuchNode' }))).not.toEqual([]); + expect(errors(junction({ $type: 'AuthzEntityMembership' }))).toContain("/relations/0/policies/0 must have required property 'data'"); + }); + test('a with_check override is for update only', () => { const check = { $type: 'AuthzValueAllowed', data: { column: 'role', allowed: ['member'], operator: 'in' } }; expect(errors(table({ policies: [{ ...TEAM, privileges: ['update'], with_check: check }] }))).toEqual([]); diff --git a/packages/node-type-registry/__tests__/module-types.test.ts b/packages/node-type-registry/__tests__/module-types.test.ts index e4460a8b5b..f228e1cc44 100644 --- a/packages/node-type-registry/__tests__/module-types.test.ts +++ b/packages/node-type-registry/__tests__/module-types.test.ts @@ -1,5 +1,6 @@ import { allModulePresets, + findMissingModuleDependencies, type ModuleEntry, type ModulePreset, publicModulePresets, @@ -11,26 +12,6 @@ import { publicModuleTypes } from '../src/module-types'; -function moduleEntries( - preset: (typeof allModulePresets)[number] -): Array<[string, Record]> { - return preset.modules.map((entry) => { - if (typeof entry === 'string') return [entry, {}]; - return entry; - }); -} - -function hasModule( - entries: Array<[string, Record]>, - name: string, - scope?: string -): boolean { - return entries.some( - ([entryName, options]) => - entryName === name && (scope === undefined || options.scope === scope) - ); -} - describe('module type registry', () => { test('matches the complete module registry', () => { expect(allModuleTypes.map(({ name }) => name)).toEqual([ @@ -48,6 +29,7 @@ describe('module type registry', () => { 'database_settings_module', 'db_preset_module', 'db_usage_module', + 'refusal_log_module', 'devices_module', 'domain_module', 'email_sender_module', @@ -83,6 +65,7 @@ describe('module type registry', () => { 'phone_numbers_module', 'plans_module', 'principal_auth_module', + 'principals_module', 'profiles_module', 'rate_limit_meters_module', 'rate_limits_module', @@ -122,6 +105,7 @@ describe('module type registry', () => { 'content_preset_module', 'database_settings_module', 'db_preset_module', + 'refusal_log_module', 'domain_module', 'infra_config_module', 'infra_module', @@ -166,7 +150,9 @@ describe('module type registry', () => { 'minimal', 'auth:hardened', 'b2b:storage', - 'full' + 'full', + 'b2b:saas', + 'auth:byo' ]); }); @@ -235,36 +221,9 @@ describe('module type registry', () => { expect(full?.modules).toContainEqual(['function_module', { scope: 'app' }]); }); - test('all presets satisfy the provisioning dependency checks', () => { + test('every preset installs the modules its modules depend on', () => { for (const preset of allModulePresets) { - const entries = moduleEntries(preset); - expect(hasModule(entries, 'users_module')).toBe(true); - expect(hasModule(entries, 'sessions_module')).toBe(true); - expect(hasModule(entries, 'rls_module')).toBe(true); - - if (hasModule(entries, 'session_secrets_module')) { - expect(hasModule(entries, 'sessions_module')).toBe(true); - } - if (hasModule(entries, 'user_auth_module')) { - expect(hasModule(entries, 'sessions_module')).toBe(true); - } - if (hasModule(entries, 'identity_providers_module')) { - expect(hasModule(entries, 'connected_accounts_module')).toBe(true); - expect(hasModule(entries, 'internal_secrets_module', 'app')).toBe(true); - } - if (hasModule(entries, 'webauthn_auth_module')) { - expect(hasModule(entries, 'user_auth_module')).toBe(true); - expect(hasModule(entries, 'session_secrets_module')).toBe(true); - expect(hasModule(entries, 'webauthn_credentials_module')).toBe(true); - } - if (hasModule(entries, 'hierarchy_module', 'org')) { - expect(hasModule(entries, 'memberships_module', 'org')).toBe(true); - } - for (const scope of ['app', 'org']) { - if (hasModule(entries, 'invites_module', scope)) { - expect(hasModule(entries, 'memberships_module', scope)).toBe(true); - } - } + expect({ preset: preset.name, missing: findMissingModuleDependencies(preset.modules) }).toEqual({ preset: preset.name, missing: [] }); } }); }); diff --git a/packages/node-type-registry/__tests__/reference-pages.test.ts b/packages/node-type-registry/__tests__/reference-pages.test.ts index 3216ee4b1e..25c521d89d 100644 --- a/packages/node-type-registry/__tests__/reference-pages.test.ts +++ b/packages/node-type-registry/__tests__/reference-pages.test.ts @@ -1,5 +1,10 @@ +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { dirname, join } from 'path'; + import * as authz from '../src/authz'; -import { renderAuthzReferencePage } from '../src/codegen/generate-reference'; +import { referencePages, renderAuthzReferencePage, renderBlueprintNodeReferencePage, stalePages } from '../src/codegen/generate-reference'; +import { allNodeTypes, blueprintDefinitionJsonSchema } from '../src/index'; import type { NodeTypeDefinition } from '../src/types'; const authzNodes: NodeTypeDefinition[] = Object.values(authz); @@ -51,3 +56,65 @@ describe('reference pages', () => { expect(renderAuthzReferencePage([node])).toContain('a \\| b'); }); }); + +describe('the blueprint node reference', () => { + const page = renderBlueprintNodeReferencePage(); + const section = (name: string) => page.slice(page.indexOf(`### ${name}\n`)).split('\n### ')[0].split('\n## ')[0]; + + test('has every node but the Authz nodes, with its words and the parameters a blueprint gives', () => { + for (const node of allNodeTypes) { + if (node.category === 'authz') { + expect(page).not.toContain(`### ${node.name}\n`); + continue; + } + expect(section(node.name)).toContain(node.description); + } + expect(section('DataDirectOwner')).toContain('| `owner_field_name` |'); + }); + + test('says where a blueprint names each node, and whether a table can name it as a string', () => { + expect(section('DataId')).toContain('**In a blueprint:** in `tables[].nodes[]`, as `"DataId"` or as `{ "$type": "DataId", "data": { … } }`.'); + expect(section('JobTrigger')).toContain('**In a blueprint:** in `tables[].nodes[]`, as `{ "$type": "JobTrigger", "data": { … } }`. `data` is required.'); + expect(section('ViewAggregated')).toContain('**In a blueprint:** no key of a blueprint takes it.'); + }); + + test('places every node a blueprint can name, wherever the blueprint schema takes it', () => { + const named = JSON.stringify(blueprintDefinitionJsonSchema); + for (const node of allNodeTypes) { + if (node.category === 'authz' || !named.includes(`"${node.name}"`)) continue; + expect(section(node.name)).not.toContain('no key of a blueprint takes it'); + } + expect(section('CheckOneOf')).toContain('- in `tables[].check_constraints[]`, as `{ "$type": "CheckOneOf", … }`. Required: `name` and `data`.'); + expect(section('CheckOneOf')).toContain('in `check_constraints[]`'); + }); + + test('gives a relation the keys its blueprint entry needs, and leaves out the ids the backend sets', () => { + const belongsTo = section('RelationBelongsTo'); + expect(belongsTo).toContain('Required: `delete_action`.'); + expect(belongsTo).toContain('The backend sets `source_table_id` and `target_table_id` from the two ends.'); + expect(belongsTo).toContain('Give exactly one of `source_table`, or `source_module`.'); + expect(belongsTo).not.toContain('| `source_table_id` |'); + expect(section('RelationSpatial')).toContain('Required: `name`, `operator`, `source_field` and `target_field`.'); + }); + + test('is the same every time, in name order whatever order the nodes come in', () => { + expect(renderBlueprintNodeReferencePage([...allNodeTypes].reverse())).toBe(page); + expect(page.split('\n')[2]).toBe('> Generated from `node-type-registry`. Do not edit this file by hand; regenerate it from the registry.'); + }); +}); + +describe('stalePages', () => { + test('lists each page that is missing or differs from a fresh render, and nothing once they match', () => { + const dir = mkdtempSync(join(tmpdir(), 'reference-pages-')); + expect(stalePages(dir)).toEqual(referencePages().map(({ path }) => path)); + for (const { path, text } of referencePages()) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), text); + } + expect(stalePages(dir)).toEqual([]); + const [first] = referencePages(); + writeFileSync(join(dir, first.path), readFileSync(join(dir, first.path), 'utf8').replace('Authz', 'Auth')); + expect(stalePages(dir)).toEqual([first.path]); + }); +}); + diff --git a/packages/node-type-registry/__tests__/sync-registry.test.ts b/packages/node-type-registry/__tests__/sync-registry.test.ts new file mode 100644 index 0000000000..55d88e6f2c --- /dev/null +++ b/packages/node-type-registry/__tests__/sync-registry.test.ts @@ -0,0 +1,61 @@ +import { execFileSync, spawnSync } from 'child_process'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { dirname, join } from 'path'; + +const SCRIPT = join(__dirname, '..', 'scripts', 'sync-registry.mjs'); + +/** A git repository at `root` with `files` committed. */ +function repo(root: string, files: Record): void { + for (const [file, text] of Object.entries(files)) { + mkdirSync(dirname(join(root, file)), { recursive: true }); + writeFileSync(join(root, file), text); + } + const git = (...args: string[]) => execFileSync('git', ['-c', 'user.email=test@example.com', '-c', 'user.name=test', ...args], { cwd: root, stdio: 'ignore' }); + git('init', '-q'); + git('add', '-A'); + git('commit', '-q', '-m', 'files'); +} + +describe('sync-registry', () => { + let dir: string; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'sync-registry-')); + }); + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it('removes nothing and stops when a file under src/ that git does not track would be removed', () => { + const upstream = join(dir, 'db'); + repo(upstream, { 'packages/node-type-registry/src/index.ts': 'export {};\n' }); + const here = join(dir, 'here'); + repo(here, { 'src/index.ts': 'export {};\n', 'src/gone.ts': 'export {};\n' }); + mkdirSync(join(here, 'scripts')); + copyFileSync(SCRIPT, join(here, 'scripts', 'sync-registry.mjs')); + writeFileSync(join(here, 'src', 'local.ts'), '// a file of the person, not committed\n'); + + const run = spawnSync('node', [join(here, 'scripts', 'sync-registry.mjs'), upstream], { encoding: 'utf8' }); + + expect(run.status).not.toBe(0); + expect(run.stderr).toContain('src/local.ts'); + expect(existsSync(join(here, 'src', 'local.ts'))).toBe(true); + expect(existsSync(join(here, 'src', 'gone.ts'))).toBe(true); + }); + + it('replaces nothing and stops when upstream has a file that is here but untracked, with other text', () => { + const upstream = join(dir, 'db'); + repo(upstream, { 'packages/node-type-registry/src/index.ts': 'export {};\n', 'packages/node-type-registry/src/new.ts': 'export const a = 1;\n' }); + const here = join(dir, 'here'); + repo(here, { 'src/index.ts': 'export {};\n' }); + mkdirSync(join(here, 'scripts')); + copyFileSync(SCRIPT, join(here, 'scripts', 'sync-registry.mjs')); + writeFileSync(join(here, 'src', 'new.ts'), '// the person\'s own work\n'); + + const run = spawnSync('node', [join(here, 'scripts', 'sync-registry.mjs'), upstream], { encoding: 'utf8' }); + + expect(run.status).not.toBe(0); + expect(run.stderr).toContain('src/new.ts'); + expect(readFileSync(join(here, 'src', 'new.ts'), 'utf8')).toBe("// the person's own work\n"); + }); +}); diff --git a/packages/node-type-registry/package.json b/packages/node-type-registry/package.json index f4a3405f3e..0749c167c0 100644 --- a/packages/node-type-registry/package.json +++ b/packages/node-type-registry/package.json @@ -1,7 +1,7 @@ { "name": "node-type-registry", "version": "1.24.1", - "description": "Node type definitions for the Constructive blueprint system. Single source of truth for all Authz*, Data*, Relation*, and View* node types.", + "description": "Node type definitions for the Constructive blueprint system: every Authz*, Data*, Relation* and View* node type, with the module presets and content presets.", "author": "Constructive ", "main": "index.js", "module": "esm/index.js", @@ -29,7 +29,11 @@ "test:watch": "jest --watch", "generate:types": "ts-node src/codegen/generate-types.ts", "generate:json": "ts-node src/codegen/generate-json.ts --outdir dist", - "generate:reference": "ts-node src/codegen/generate-reference.ts" + "generate:reference": "ts-node src/codegen/generate-reference.ts", + "sync:registry": "node scripts/sync-registry.mjs" + }, + "dependencies": { + "blocks-schema": "^0.5.4" }, "devDependencies": { "@babel/generator": "^7.29.0", diff --git a/packages/node-type-registry/scripts/sync-registry.mjs b/packages/node-type-registry/scripts/sync-registry.mjs new file mode 100644 index 0000000000..0a6d94105b --- /dev/null +++ b/packages/node-type-registry/scripts/sync-registry.mjs @@ -0,0 +1,97 @@ +#!/usr/bin/env node +// constructive-db owns the registry source; this package publishes a copy of it. This script copies src/ from a +// constructive-db checkout. With --check it changes nothing, lists each file that differs, and exits 1 if one does. +// +// node scripts/sync-registry.mjs [--check] + +import { execFileSync } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// The files under src/ that only one repository has: constructive-db's seed SQL generator and audit, and this +// package's generators of its JSON files and reference pages. Each repository keeps its own tests. +const OWN = { + 'constructive-db': ['src/audit/', 'src/generate.ts'], + constructive: ['src/codegen/generate-json.ts', 'src/codegen/generate-reference.ts'] +}; + +const args = process.argv.slice(2); +const check = args.includes('--check'); +const [checkout, ...extra] = args.filter((arg) => arg !== '--check'); +if (!checkout || extra.length) fail('Usage: node scripts/sync-registry.mjs [--check] '); + +const here = join(dirname(fileURLToPath(import.meta.url)), '..'); +const upstream = join(checkout, 'packages', 'node-type-registry'); +if (!existsSync(join(upstream, 'src', 'index.ts'))) { + fail(`${upstream} has no registry source (src/index.ts). Give the path of a constructive-db checkout.`); +} + +const owned = (repo, file) => OWN[repo].some((path) => (path.endsWith('/') ? file.startsWith(path) : file === path)); + +// The files under src/ as git lists them, so nothing git does not keep (an editor's or a system's file) is copied or +// compared: what constructive-db tracks, and here also the files a sync just copied and git does not ignore. +function files(root, { untracked }) { + try { + const listed = execFileSync('git', ['ls-files', '-z', ...(untracked ? ['--cached', '--others', '--exclude-standard'] : []), '--', 'src'], { cwd: root, encoding: 'utf8' }); + return [...new Set(listed.split('\0').filter(Boolean))].filter((file) => existsSync(join(root, file))).sort(); + } catch (err) { + fail(`git could not list the files of ${root} (${err.message.split('\n')[0]}). Give the path of a git checkout of constructive-db, and run this in a git checkout of constructive.`); + } +} + +const shared = files(upstream, { untracked: false }).filter((file) => !owned('constructive-db', file)); +const clash = shared.filter((file) => owned('constructive', file)); +if (clash.length) { + fail(`constructive-db now has ${clash.join(', ')}, which this package keeps as its own. Rename one of them, or take it out of OWN.`); +} +const kept = new Set(shared); +const changes = [ + ...shared.filter((file) => !existsSync(join(here, file))).map((file) => ({ kind: 'missing', file })), + ...shared + .filter((file) => existsSync(join(here, file)) && !readFileSync(join(here, file)).equals(readFileSync(join(upstream, file)))) + .map((file) => ({ kind: 'changed', file })), + ...files(here, { untracked: true }).filter((file) => !owned('constructive', file) && !kept.has(file)).map((file) => ({ kind: 'extra', file })) +]; + +if (check) { + if (!changes.length) { + console.log(`The registry source matches ${upstream}.`); + process.exit(0); + } + for (const { kind, file } of changes) console.log(`${kind.padEnd(7)} ${file}`); + console.error( + `\nThe registry source differs from ${upstream} in ${changes.length} file(s). ` + + 'Make the change in constructive-db, then run node scripts/sync-registry.mjs here.' + ); + process.exit(1); +} + +// git can restore a tracked file a sync removes or replaces, but not an untracked one, so the sync stops before it +// changes anything. A missing file is only added, so it is not one of them. +const tracked = new Set(files(here, { untracked: false })); +const untracked = changes.filter(({ kind, file }) => kind !== 'missing' && !tracked.has(file)).map(({ file }) => file); +if (untracked.length) { + fail( + `The sync would remove or replace ${untracked.join(', ')}, which git does not track, so nothing was changed. ` + + 'Move those files out of src/, commit them, or add them to OWN in this script, then run it again.' + ); +} + +for (const { kind, file } of changes) { + if (kind === 'extra') rmSync(join(here, file)); + else { + mkdirSync(dirname(join(here, file)), { recursive: true }); + copyFileSync(join(upstream, file), join(here, file)); + } + console.log(`${kind === 'extra' ? 'removed' : 'copied '} ${file}`); +} +console.log( + `\n${changes.length} file(s) synced. Build and test this package, then check the skills pages: ` + + 'ts-node src/codegen/generate-reference.ts --check --outdir /.agents/skills' +); + +function fail(message) { + console.error(message); + process.exit(2); +} diff --git a/packages/node-type-registry/src/authz/authz-database-claim.ts b/packages/node-type-registry/src/authz/authz-database-claim.ts index a28a6519c4..1a35aeb1ef 100644 --- a/packages/node-type-registry/src/authz/authz-database-claim.ts +++ b/packages/node-type-registry/src/authz/authz-database-claim.ts @@ -42,6 +42,6 @@ export const AuthzDatabaseClaim: NodeTypeDefinition = { 'Rows people reach through the API: use a membership policy.' ], risks: [ - 'Every session the platform binds to that database passes, including an API key used through the database connection proxy.' + 'By default, every session the platform binds to that database passes, including an API key used through the database connection proxy. You can require the platform to attest the connection instead.' ] }; diff --git a/packages/node-type-registry/src/authz/authz-entity-membership.ts b/packages/node-type-registry/src/authz/authz-entity-membership.ts index be1276997e..a6cab6deb4 100644 --- a/packages/node-type-registry/src/authz/authz-entity-membership.ts +++ b/packages/node-type-registry/src/authz/authz-entity-membership.ts @@ -44,7 +44,7 @@ export const AuthzEntityMembership: NodeTypeDefinition = { format: 'column-ref', 'x-column-scope': 'local', description: - 'Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capability/capabilities — both are ANDed.', + 'Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capabilities — both checks must pass.', }, is_admin: { type: 'boolean', diff --git a/packages/node-type-registry/src/authz/authz-related-entity-membership.ts b/packages/node-type-registry/src/authz/authz-related-entity-membership.ts index 2334578f38..1ca02a864b 100644 --- a/packages/node-type-registry/src/authz/authz-related-entity-membership.ts +++ b/packages/node-type-registry/src/authz/authz-related-entity-membership.ts @@ -99,7 +99,7 @@ export const AuthzRelatedEntityMembership: NodeTypeDefinition = { 'Rows that name their team directly: use AuthzEntityMembership.' ], risks: [ - 'The registry does not list sel_obj. The backend\'s own policies set sel_obj to true and sel_field to id; without them the row\'s column is compared with the team id itself, not with the related row.', + 'To compare the row\'s column with the related row\'s id rather than the team id, set sel_obj to true and sel_field to id.', ACTIVE_MEMBER_RISK, OTHER_TABLE_RISK ] diff --git a/packages/node-type-registry/src/authz/authz-related-member-owner.ts b/packages/node-type-registry/src/authz/authz-related-member-owner.ts index 936537cb86..fc909ef907 100644 --- a/packages/node-type-registry/src/authz/authz-related-member-owner.ts +++ b/packages/node-type-registry/src/authz/authz-related-member-owner.ts @@ -101,7 +101,7 @@ export const AuthzRelatedMemberOwner: NodeTypeDefinition = { 'Rows that name their team directly: use AuthzMemberOwner.' ], risks: [ - 'The registry does not list sel_obj. The backend\'s own policies set sel_obj to true and sel_field to id; without them the row\'s column is compared with the team id itself, not with the related row.', + 'To compare the row\'s column with the related row\'s id rather than the team id, set sel_obj to true and sel_field to id.', ACTIVE_MEMBER_RISK, AGENT_IDENTITY_RISK, OTHER_TABLE_RISK diff --git a/packages/node-type-registry/src/authz/authz-value-exists.ts b/packages/node-type-registry/src/authz/authz-value-exists.ts index acadd496e2..c6d2338a92 100644 --- a/packages/node-type-registry/src/authz/authz-value-exists.ts +++ b/packages/node-type-registry/src/authz/authz-value-exists.ts @@ -38,6 +38,7 @@ export const AuthzValueExists: NodeTypeDefinition = { }, join: { type: 'array', + minItems: 1, description: 'Join conditions between the protected row and the referenced table', items: { type: 'object', diff --git a/packages/node-type-registry/src/authz/authz-value-match.ts b/packages/node-type-registry/src/authz/authz-value-match.ts index 8cb6682a0a..5c38bb2069 100644 --- a/packages/node-type-registry/src/authz/authz-value-match.ts +++ b/packages/node-type-registry/src/authz/authz-value-match.ts @@ -38,6 +38,7 @@ export const AuthzValueMatch: NodeTypeDefinition = { }, join: { type: 'array', + minItems: 1, description: 'Join conditions between the protected row and the referenced table', items: { type: 'object', diff --git a/packages/node-type-registry/src/blueprint-schema.generated.ts b/packages/node-type-registry/src/blueprint-schema.generated.ts index 2d729771dc..95c8268ff4 100644 --- a/packages/node-type-registry/src/blueprint-schema.generated.ts +++ b/packages/node-type-registry/src/blueprint-schema.generated.ts @@ -3,7 +3,8 @@ // Regenerate with: // cd packages/node-type-registry && pnpm generate:types +/* eslint-disable */ import type { JSONSchema } from './types'; /** JSON Schema (draft-07) of a blueprint definition: the shapes construct_blueprint() reads, with each node's data checked against its parameter_schema in the form a caller writes it. */ -export const blueprintDefinitionJsonSchema: JSONSchema = {"$schema":"http://json-schema.org/draft-07/schema#","title":"BlueprintDefinition","description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint().","allOf":[{"$ref":"#/$defs/BlueprintDefinition"}],"$defs":{"AuthzAllowAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Allows all access. Generates TRUE expression."},"AuthzAppMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must hold an app membership (hardcoded membership_type=1). App-level analog of AuthzMemberOwner for global scopes with no entity key — authorship never survives losing app membership."},"AuthzAppMembershipParams":{"type":"object","properties":{"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":[],"additionalProperties":false,"description":"Checks whether the user is a member of the app. You can also require a specific permission."},"AuthzColumnSecurityParams":{"type":"object","properties":{"columns":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Guarded columns that share the same rule and authorization (e.g. [\"is_shared\"])."},"rule":{"type":"string","enum":["set_true","set_false","set_values","not_values","writable_when","transition","immutable"],"description":"Write pattern that arms the guard: set_true/set_false (column set to that boolean), set_values (column set to one of values), not_values (column set to a non-NULL value outside values), writable_when (column written/changed at all), transition (OLD->NEW pairs in allowed), immutable (delegates to DataImmutableFields).","default":"writable_when"},"authz":{"$ref":"#/$defs/AuthzExpression","description":"An Authz expression (one node such as {\"AuthzAppMembership\": {...}}, or AND, OR or NOT over nodes) that must be satisfied to perform the guarded write. Required for all rules except immutable."},"values":{"type":"array","items":{"type":"string"},"description":"For rule=set_values: the protected values that arm the guard. For rule=not_values: the allowed values; any non-NULL value outside them arms the guard."},"allowed":{"type":"array","items":{"type":"string"},"description":"For rule=transition: allowed guarded transitions expressed as \"from->to\" (e.g. [\"member->admin\"])."},"allow_system":{"type":"boolean","description":"When true, the system role (AuthzSystemOnly) bypasses the guard so provisioning/seed paths without a JWT principal can write freely.","default":false},"error_code":{"type":"string","description":"Machine-readable code prefixed onto the raised error message (e.g. MANAGED_DOMAIN_PUBLISH_FORBIDDEN)."},"error_message":{"type":"string","description":"Human-readable message raised when the guard denies the write."},"conditions":{"type":["object","array"],"items":{"type":"object"},"description":"Conditions on the row being written; the guard arms only when the write matches the rule and the row meets them."}},"required":["columns","rule"],"allOf":[{"if":{"properties":{"rule":{"not":{"const":"immutable"}}}},"then":{"required":["authz"]}},{"if":{"properties":{"rule":{"enum":["set_values","not_values"]}}},"then":{"required":["values"],"properties":{"values":{"minItems":1}}}},{"if":{"properties":{"rule":{"const":"transition"}}},"then":{"required":["allowed"],"properties":{"allowed":{"minItems":1}}}}],"additionalProperties":false,"description":"Column-level write authorization. Generates BEFORE INSERT/UPDATE triggers that enforce an authorization node whenever a guarded column is written to a protected value or transitions. The write-time counterpart to RLS SELECT/WITH CHECK policies: any table can declare \"only an actor satisfying may set column X\". The nested authz value is a normal Authz node compiled by the standard RLS pipeline; row-referencing nodes have their protected-table column references rebound to NEW. The immutable rule delegates to the native DataImmutableFields generator."},"AuthzCompositeParams":{"$ref":"#/$defs/AuthzExpression","description":"Composite authorization policy that combines multiple authorization nodes using boolean logic (AND/OR). The data field contains a JSONB AST with nested authorization nodes."},"AuthzDatabaseClaimParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column carrying the row's database id","default":"database_id"},"schema_id":{"type":"string","format":"uuid","description":"A schema whose database must be the claimed one, in place of a column; the rule then reads no column."},"lane_attested":{"type":"boolean","description":"Only connections the platform attests for the claimed database pass.","default":false}},"additionalProperties":false,"description":"Passes when the row's database column equals the session's pinned database claim (jwt.claims.database_id). Consults no principal, membership or entity, so it admits a connection whose identity the platform sets — such as a cloud function's database connection, whose claim comes from the connection and cannot widen it — to exactly the database that connection is bound to. A session with no claim fails loudly rather than reading nothing."},"AuthzDenyAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Denies all access. Generates FALSE expression."},"AuthzDirectOwnerAnyParams":{"type":"object","properties":{"entity_fields":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Array of column names to check for ownership"}},"required":["entity_fields"],"additionalProperties":false,"description":"OR logic for multiple ownership fields. Checks if current user matches any of the specified fields."},"AuthzDirectOwnerParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)"}},"required":["entity_field"],"additionalProperties":false,"description":"Direct equality comparison between a table column and the current user ID. Simplest authorization pattern with no subqueries."},"AuthzEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"mask_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capability/capabilities — both are ANDed."},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"},"check_function_name":{"type":"string","description":"A function that checks the membership instead of the member list; it is called with the row's team column."},"check_function_schema":{"type":"string","description":"The schema of that function."}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Checks whether the user belongs to the organization or group linked to this record."},"AuthzExpression":{"type":"object","description":"One Authz node as {\"AuthzEntityMembership\": {...}}, or AND or OR with a list of expressions, or NOT with one expression.","minProperties":1,"maxProperties":1,"properties":{"AND":{"$ref":"#/$defs/shared-040cc005ef"},"OR":{"$ref":"#/$defs/shared-040cc005ef"},"NOT":{"$ref":"#/$defs/AuthzExpression"},"AuthzAllowAll":{"$ref":"#/$defs/AuthzAllowAllParams"},"AuthzAppMemberOwner":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"},"AuthzAppMembership":{"$ref":"#/$defs/AuthzAppMembershipParams"},"AuthzDatabaseClaim":{"$ref":"#/$defs/AuthzDatabaseClaimParams"},"AuthzDenyAll":{"$ref":"#/$defs/AuthzDenyAllParams"},"AuthzDirectOwner":{"$ref":"#/$defs/AuthzDirectOwnerParams"},"AuthzDirectOwnerAny":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"},"AuthzEntityMembership":{"$ref":"#/$defs/AuthzEntityMembershipParams"},"AuthzFilePath":{"$ref":"#/$defs/AuthzFilePathParams"},"AuthzHumanOnly":{"$ref":"#/$defs/AuthzHumanOnlyParams"},"AuthzMemberList":{"$ref":"#/$defs/AuthzMemberListParams"},"AuthzMemberOwner":{"$ref":"#/$defs/AuthzMemberOwnerParams"},"AuthzOrgHierarchy":{"$ref":"#/$defs/AuthzOrgHierarchyParams"},"AuthzPeerOwnership":{"$ref":"#/$defs/AuthzPeerOwnershipParams"},"AuthzPublishable":{"$ref":"#/$defs/AuthzPublishableParams"},"AuthzRelatedEntityMembership":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"},"AuthzRelatedMemberList":{"$ref":"#/$defs/AuthzRelatedMemberListParams"},"AuthzRelatedMemberOwner":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"},"AuthzRelatedPeerOwnership":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"},"AuthzSystemOnly":{"$ref":"#/$defs/AuthzSystemOnlyParams"},"AuthzTemporal":{"$ref":"#/$defs/AuthzTemporalParams"},"AuthzValueAllowed":{"$ref":"#/$defs/AuthzValueAllowedParams"},"AuthzValueExists":{"$ref":"#/$defs/AuthzValueExistsParams"},"AuthzValueMatch":{"$ref":"#/$defs/AuthzValueMatchParams"}},"additionalProperties":false},"AuthzFilePathParams":{"type":"object","properties":{"shares_table_id":{"type":"string","format":"uuid","description":"UUID of the path_shares table (alternative to shares_schema/shares_table)"},"shares_schema":{"type":"string","description":"Schema of the path_shares table (or use shares_table_id)"},"shares_table":{"type":"string","description":"Name of the path_shares table (or use shares_table_id)"},"files_table_id":{"type":"string","format":"uuid","description":"UUID of the files table (alternative to files_schema/files_table)"},"files_schema":{"type":"string","description":"Schema of the files table (or use files_table_id)"},"files_table":{"type":"string","description":"Name of the files table (or use files_table_id)"},"capability_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Boolean column on the path_shares table that grants the required permission (e.g. can_read, can_write)"},"bucket_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the files table referencing the bucket","default":"bucket_id"},"path_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Ltree column on the files table representing the file path","default":"path"}},"required":["capability_field"],"allOf":[{"anyOf":[{"required":["shares_table_id"]},{"required":["shares_schema","shares_table"]}]},{"anyOf":[{"required":["files_table_id"]},{"required":["files_schema","files_table"]}]}],"additionalProperties":false,"description":"Path-scoped file sharing via ltree containment. Grants access when a path_shares row matches the current user, bucket, and an ancestor path with the required permission."},"AuthzHumanOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Passes only for human sessions: compares the session's principal claim to its user claim, so service principals (API keys, agents) are excluded. Typically applied as a restrictive policy alongside a permissive membership policy."},"AuthzMemberListParams":{"type":"object","properties":{"array_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the array of user IDs"}},"required":["array_field"],"additionalProperties":false,"description":"Check if current user is in an array column on the same row."},"AuthzMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id)","default":"entity_id"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must be a member of the entity referenced by entity_field. Combines direct ownership with entity membership — the actor can only access rows they own within entities they belong to."},"AuthzNotReadOnlyParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Blocks changes by users marked read-only in the member list. Pair it with AuthzEntityMembership to check that the user is a member in the first place."},"AuthzOrgHierarchyParams":{"type":"object","properties":{"direction":{"type":"string","enum":["up","down"],"description":"down=manager sees subordinates, up=subordinate sees managers"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the org entity","default":"entity_id"},"anchor_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the user (e.g., owner_id)"},"max_depth":{"type":"integer","description":"Optional max depth to limit visibility"}},"required":["direction","anchor_field"],"additionalProperties":false,"description":"Organizational hierarchy visibility using closure table. Managers can see subordinate data or subordinates can see manager data."},"AuthzPeerOwnershipParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the owning user (e.g., owner_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Peer visibility through shared entity membership. Authorizes access to user-owned rows when the owner and current user are both members of the same entity."},"AuthzPublishableParams":{"type":"object","properties":{"is_published_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Boolean field indicating published state","default":"is_published"},"published_at_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Timestamp field for publish time","default":"published_at"},"require_published_at":{"type":"boolean","description":"Require published_at to be non-null and <= now()","default":true}},"additionalProperties":false,"description":"Published state access control. Restricts access to records that are published."},"AuthzRelatedEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Choose the column on the linked table that identifies the organization, group, or other membership target."},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Checks membership through a linked table, such as whether the user belongs to the organization linked there."},"AuthzRelatedMemberListParams":{"type":"object","properties":{"owned_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to owned_schema/owned_table)"},"owned_schema":{"type":"string","description":"Schema of the related table (or use owned_table_id)"},"owned_table":{"type":"string","description":"Name of the related table (or use owned_table_id)"},"owned_table_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Array column in related table"},"owned_table_ref_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"FK column in related table"},"this_object_key":{"type":"string","format":"column-ref","x-column-scope":"local","description":"PK column in protected table"}},"required":["owned_table_key","owned_table_ref_key","this_object_key"],"anyOf":[{"required":["owned_table_id"]},{"required":["owned_schema","owned_table"]}],"additionalProperties":false,"description":"Array membership check in a related table."},"AuthzRelatedMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the related table to match to the entity ID in the member list"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access only when the current user owns the row and belongs to the entity referenced by a related row. If the user loses membership, owning the row no longer gives them access."},"AuthzRelatedPeerOwnershipParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the related table (e.g., message_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to obj_schema/obj_table)"},"obj_schema":{"type":"string","description":"Schema of the related table (or use obj_table_id)"},"obj_table":{"type":"string","description":"Name of the related table (or use obj_table_id)"},"obj_field_id":{"type":"string","format":"uuid","description":"UUID of field on related table containing the owner user ID (alternative to obj_field)"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field name on related table containing the owner user ID (e.g., sender_id)"},"obj_ref_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field on related table to select for matching entity_field","default":"id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access when the current user and the owner are members of the same entity. Unlike AuthzPeerOwnership, it looks up the owner on a related row."},"AuthzSystemOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Restricts access to system-initiated operations (triggers, background jobs). Checks jwt.claims.role_type = \"system\". Normal API requests default to \"user\" and are denied. Use for INSERT policies on append-only event/audit/usage tables."},"AuthzTemporalParams":{"type":"object","properties":{"valid_from_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for start time (at least one of valid_from_field or valid_until_field required)"},"valid_until_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for end time (at least one of valid_from_field or valid_until_field required)"},"valid_from_inclusive":{"type":"boolean","description":"Include start boundary","default":true},"valid_until_inclusive":{"type":"boolean","description":"Include end boundary","default":false}},"anyOf":[{"required":["valid_from_field"]},{"required":["valid_until_field"]}],"additionalProperties":false,"description":"Time-window based access control. Restricts access based on valid_from and/or valid_until timestamps. At least one of valid_from_field or valid_until_field must be provided."},"AuthzValueAllowedParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table to check"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the value check"}},"required":["column","allowed","operator"],"additionalProperties":false,"description":"Check the protected row's own column against an allowed set of values."},"AuthzValueExistsParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-1ca2c9bd61"},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with optional additional conditions."},"AuthzValueMatchParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-1ca2c9bd61"},"match":{"type":"object","description":"Value match on a referenced column","properties":{"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table to match"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the match"}},"required":["ref_column","allowed","operator"],"additionalProperties":false},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["match","join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with a value/array match on a referenced column and optional additional conditions."},"BlueprintAchievement":{"type":"object","properties":{"name":{"type":"string","description":"Unique name for the achievement level."},"description":{"type":"string","description":"Human-readable description of this achievement."},"priority":{"type":"number","description":"Display ordering priority; lower values appear first. Defaults to 100."},"requirements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementRequirement"},"description":"Requirements that must be met to earn this achievement."},"rewards":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementReward"},"description":"Rewards granted when the achievement is earned."},"entity_prefix":{"type":"string","description":"Entity prefix to scope this achievement to (e.g., \"org\", \"app\"). Used to resolve the correct events_module. Defaults to \"app\"."}},"required":["name","requirements"],"description":"An achievement entry for the blueprint achievements[] section. Creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"BlueprintAchievementRequirement":{"type":"object","properties":{"event_name":{"type":"string","description":"Name identifier matching an event_type or step name."},"count":{"type":"number","description":"Number of events needed to satisfy this requirement."},"description":{"type":"string","description":"Human-readable description of what this requirement entails."}},"required":["event_name","count"],"description":"A requirement entry within a blueprint achievement. Defines what events must occur to earn the achievement."},"BlueprintAchievementReward":{"type":"object","properties":{"reward_type":{"enum":["limit_credit","meter_credit"],"description":"Type of reward: limit_credit (grants limit credits) or meter_credit (grants meter credits)."},"target_name":{"type":"string","description":"Target limit name or meter slug for the credit grant."},"amount":{"type":"number","description":"Number of credits to grant."},"credit_type":{"type":"string","description":"Credit type: permanent, expiring, etc. Defaults to \"permanent\"."}},"required":["reward_type","target_name","amount"],"description":"A reward entry within a blueprint achievement. Defines credits granted when the achievement is earned."},"BlueprintAgentConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Agent scope. \"app\" (default) creates app-level agent tables (membership_type = NULL). \"org\" creates per-org agent tables. Only used at the top level of a blueprint definition — entity-scoped agents inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module agents. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_agent_thread."},"api_name":{"type":"string","description":"API name for the agent module. Used in GraphQL naming. Defaults to \"agent\"."},"has_plans":{"type":"boolean","description":"Whether to provision the agent_plan table for workflow plans with ordered tasks and approval gates. When true, tasks belong to plans (plan_id NOT NULL) instead of directly to threads. Defaults to false."},"has_resources":{"type":"boolean","description":"Whether to provision the unified agent_resource table (skills + knowledge with slug, kind, search, embedding). Standalone flag — also auto-enabled by has_agents. Defaults to false."},"has_agents":{"type":"boolean","description":"Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false."},"has_runs":{"type":"boolean","description":"Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false."},"resources":{"type":"array","items":{"type":"object","properties":{"dimensions":{"type":"number"},"chunk_size":{"type":"number"},"chunk_overlap":{"type":"number"},"chunk_strategy":{"enum":["paragraph","sentence","token"]},"embedding_model":{"type":"string"},"embedding_provider":{"type":"string"},"search_indexes":{"type":"array","items":{"type":"string"}}}},"description":"Resource configuration array. First element configures the agent_resource table: vector dimensions (default 768), chunk_size (default 1000), chunk_strategy (default \"paragraph\"), chunk_overlap (default 200), embedding_model, embedding_provider, search_indexes (default [\"bm25\"])."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the agent tables. NULL = apply defaults from apply_agent_security()."},"provisions":{"type":"object","properties":{"thread":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"message":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"task":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"prompt":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"plan":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"resource":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"agent":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"persona":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"run":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"event":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"workspace":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for agent tables. Each key targets a specific table (thread, message, task, prompt, plan, resource, agent, persona, run, event, workspace) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision. Overriding `event` replaces the append-only default, so a grant list there can make the transcript mutable; overriding `workspace` replaces its no-delete default."}},"description":"Agent module configuration. When used at the top level of a blueprint, the scope field controls whether agents are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions thread, message, task, prompt tables. has_resources adds unified agent_resource (skills + knowledge). has_agents adds agent registry + personas (implies has_resources)."},"BlueprintBucketSeed":{"type":"object","properties":{"name":{"type":"string","description":"Bucket key name (e.g., \"avatars\", \"documents\"). Becomes the key column value."},"description":{"type":"string","description":"Human-readable description of this bucket."},"is_public":{"type":"boolean","description":"Whether the bucket is publicly readable. Defaults to false."},"allowed_mime_types":{"type":"array","items":{"type":"string"},"description":"MIME type allowlist (e.g., [\"image/png\", \"image/jpeg\"]). NULL means all types allowed."},"max_file_size":{"type":"number","description":"Maximum file size in bytes for this bucket. NULL means no limit."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for this bucket."}},"required":["name"],"description":"A bucket seed entry for storage.buckets[]. Creates an initial bucket row in the {prefix}_buckets table during entity type provisioning. Only used for app-level storage (not entity-scoped)."},"BlueprintCheckConstraint":{"allOf":[{"$ref":"#/$defs/BlueprintTableCheckConstraint"},{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this CHECK constraint belongs to."}},"required":["table_name"]}],"description":"A CHECK constraint definition within a blueprint (top-level, requires table_name)."},"BlueprintDefinition":{"type":"object","properties":{"tables":{"type":"array","items":{"$ref":"#/$defs/BlueprintTable"},"description":"Tables to create."},"relations":{"type":"array","items":{"$ref":"#/$defs/BlueprintRelation"},"description":"Relations between tables."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintIndex"},"description":"Indexes on table columns."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintFullTextSearch"},"description":"Full-text search configurations."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintUniqueConstraint"},"description":"Unique constraints on table columns."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintCheckConstraint"},"description":"CHECK constraints on table columns."},"entity_types":{"type":"array","items":{"$ref":"#/$defs/BlueprintEntityType"},"description":"Entity types to provision in Phase 0 (before tables). Each entry creates an entity table with membership modules and security."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Top-level storage configuration array. Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates storage_module with membership_type = NULL. Org-scoped creates per-org/user storage with owner_id and AFTER INSERT bucket seeding. When infra is installed, a private \"functions\" bucket is auto-injected into org-scoped entries. For child entity type storage, use entity_types[].storage instead."},"achievements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievement"},"description":"Achievement definitions. Each entry creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Top-level namespace configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates namespace_module with membership_type = NULL. Org-scoped creates per-org namespaces. For entity-scoped namespaces, use entity_types[].namespaces instead."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Top-level function configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates function_module with membership_type = NULL. Org-scoped creates per-org functions. For entity-scoped functions, use entity_types[].functions instead."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Top-level agent configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates agent_module with membership_type = NULL. Org-scoped creates per-org agents. For entity-scoped agents, use entity_types[].agents instead."}},"required":["tables"],"description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint()."},"BlueprintEntityTableProvision":{"type":"object","properties":{"use_rls":{"type":"boolean","description":"Whether to enable RLS on the entity table. Forwarded to secure_table_provision. Defaults to true."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Node objects applied to the entity table for field creation (e.g., DataTimestamps, DataPeoplestamps). Forwarded to secure_table_provision as-is."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the entity table. Forwarded to secure_table_provision as-is."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects for the entity table. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples. Forwarded to secure_table_provision as-is. Defaults to []."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for the entity table. When present, these policies fully replace the five default entity-table policies (is_visible becomes a no-op)."}},"description":"Override object for the entity table created by a BlueprintEntityType. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, policies[] replaces the default entity-table policies entirely."},"BlueprintEntityType":{"type":"object","properties":{"name":{"type":"string","description":"Entity type name (e.g., \"data_room\", \"channel\", \"department\"). Required when creating a new entity type. Omit when extending an existing entity type (e.g., prefix: \"org\") — the entry will add storage/config to the existing type without creating a new one."},"prefix":{"type":"string","description":"Short prefix for generated objects (e.g., \"dr\", \"ch\", \"dept\"). Used in table/trigger naming."},"description":{"type":"string","description":"Human-readable description of this entity type."},"parent_entity":{"type":"string","description":"Parent entity type name. Defaults to \"org\"."},"table_name":{"type":"string","description":"Custom table name for the entity table. Defaults to name-derived convention."},"is_visible":{"type":"boolean","description":"Whether parent-entity members can see child entities via the default parent_member SELECT policy. Gates one of the five default policies. No-op when table_provision is supplied. Defaults to true."},"has_limits":{"type":"boolean","description":"Whether to provision a limits module for this entity type. Defaults to false."},"has_profiles":{"type":"boolean","description":"Whether to provision a profiles module for this entity type. Defaults to false. A membership may hold any number of profiles: the {prefix}_membership_profiles assignment table holds every profile it holds and the membership mask is granted | bit_or(held profile masks)."},"has_levels":{"type":"boolean","description":"Whether to provision a levels module for this entity type. Defaults to false."},"has_invites":{"type":"boolean","description":"Whether to provision entity-scoped invite tables ({prefix}_invites, {prefix}_claimed_invites) and a submit_{prefix}_invite_code() function. Defaults to false."},"has_invite_achievements":{"type":"boolean","description":"Whether to auto-attach an EventTracker to the claimed_invites table for invite-based achievements. Requires has_invites=true AND has_levels=true. When true, records 'invite_claimed' events credited to the sender (inviter) on each claimed invite. Defaults to false."},"skip_entity_policies":{"type":"boolean","description":"Escape hatch: when true AND table_provision is NULL, zero policies are provisioned on the entity table. Defaults to false."},"table_provision":{"$ref":"#/$defs/BlueprintEntityTableProvision","description":"Override for the entity table. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, its policies[] replaces the five default entity-table policies; is_visible becomes a no-op. When NULL (default), the five default policies are applied (gated by is_visible)."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Storage module configuration array. Presence triggers provisioning (same inference model as namespaces, functions, agents). Each entry provisions a separate storage module with its own tables, RLS, and settings. Each entry may specify a key for multi-module support (defaults to \"default\")."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Namespace module configuration array. Presence triggers provisioning. Each entry provisions a namespace_module with its own tables, computed-name proxy, and entity-scoped RLS. Registers manage_namespaces capability bit. \"[{}]\" = provision one default namespace module."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Function module configuration array. Presence triggers provisioning. Each entry provisions function_definitions, function_invocations (partitioned), and function_execution_logs tables. Registers manage_functions + invoke_functions capability bits. \"[{}]\" = provision one default function module."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Agent module configuration array. Presence triggers provisioning. Each entry provisions thread, message, task, prompt tables (and optionally knowledge with vector embeddings). \"[{}]\" = provision one default agent module."},"graphs":{"type":"array","items":{"$ref":"#/$defs/BlueprintGraphConfig"},"description":"Graph module configuration array. Presence triggers capability registration (manage_graphs, execute_graphs). Graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here. \"[{}]\" = register default graph capabilities."}},"required":["prefix"],"description":"An entity type entry for Phase 0 of construct_blueprint(). When name is provided, provisions a new entity type with its own entity table, membership modules, and security policies via entity_type_provision. When name is omitted and only prefix is given, extends an existing entity type (e.g., the built-in \"org\") with additional capabilities like storage — without creating a new entity type."},"BlueprintField":{"type":"object","properties":{"name":{"type":"string","description":"The column name."},"type":{"$ref":"#/$defs/FieldType","description":"The structured PostgreSQL type (e.g., { name: \"text\" })."},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint."},"default":{"$ref":"#/$defs/FieldDefault","description":"The structured default (e.g., { value: \"pending\" })."},"min":{"type":"number"},"max":{"type":"number"},"regexp":{"type":"string"},"index":{"enum":["btree","gin","gist","brin","hash"]},"description":{"type":"string","description":"Comment/description for this field."}},"required":["name","type"],"description":"A custom field (column) to add to a blueprint table."},"BlueprintFtsSource":{"type":"object","properties":{"field":{"type":"string","description":"Column name of the source field."},"weight":{"type":"string","description":"TSVector weight: \"A\", \"B\", \"C\", or \"D\"."},"lang":{"type":"string","description":"Language for text search. Defaults to \"english\"."}},"required":["field","weight"],"description":"A source field contributing to a full-text search tsvector column."},"BlueprintFullTextSearch":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this full-text search belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"}},"required":["table_name","field","sources"],"description":"A full-text search configuration for a blueprint table (top-level, requires table_name)."},"BlueprintFunctionConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Function scope. \"app\" (default) creates app-level functions (membership_type = NULL). \"org\" creates per-org functions. Only used at the top level of a blueprint definition — entity-scoped functions inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module functions. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_function_definitions."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the function tables. NULL = apply defaults from apply_function_security()."},"provisions":{"type":"object","properties":{"definitions":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"invocations":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"execution_logs":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for function tables. Each key targets a specific table (definitions, invocations, execution_logs) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Function module configuration. When used at the top level of a blueprint, the scope field controls whether functions are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions function_definitions, function_invocations (partitioned, 12-month retention), and function_execution_logs tables."},"BlueprintGraphConfig":{"type":"object","properties":{"key":{"type":"string","description":"Module discriminator for multi-module graphs. Defaults to \"default\"."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the graph tables. NULL = apply defaults from apply_graph_security()."}},"description":"Graph module configuration. Presence triggers capability registration (manage_graphs, execute_graphs). The graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here — the graph module itself must be provisioned separately."},"BlueprintIndex":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this index belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"}},"required":["table_name","access_method"],"description":"An index definition within a blueprint (top-level, requires table_name)."},"BlueprintModuleInstallRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type of the install, e.g. \"image\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type"],"description":"A reference to an installed module, naming no table of its own. Used by a table entry whose provisions map supplies the table keys."},"BlueprintModuleTableRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type owning the table. Currently \"agent\"."},"table":{"type":"string","description":"Logical table key within the module, not a table name. Agent: \"thread\", \"message\", \"task\", \"prompt\", \"plan\", \"agent\", \"persona\", \"resource\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type","table"],"description":"A reference from a blueprint table entry to a table generated by an installed module. Resolved through the module row's recorded table ids; a reference that matches no module instance or no provisioned table fails construction rather than creating a table."},"BlueprintNamespaceConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Namespace scope. \"app\" (default) creates app-level namespaces (membership_type = NULL). \"org\" creates per-org namespaces. Only used at the top level of a blueprint definition — entity-scoped namespaces inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module namespaces. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_namespaces."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the namespaces table. NULL = apply defaults from apply_namespace_security()."},"provisions":{"type":"object","properties":{"namespaces":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"namespace_events":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for namespace tables. Each key targets a specific table (namespaces, namespace_events) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Namespace module configuration. When used at the top level of a blueprint, the scope field controls whether namespaces are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions a namespaces table with computed-name proxy, rename trigger, and entity-scoped RLS."},"BlueprintNode":{"anyOf":[{"$ref":"#/$defs/BlueprintNodeShorthand"},{"$ref":"#/$defs/BlueprintNodeObject"}],"description":"A node entry in a blueprint table. Either a string shorthand or a typed object."},"BlueprintNodeObject":{"type":"object","properties":{"data":{"type":"object"},"$type":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzColumnSecurity","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch","CheckGreaterThan","CheckLessThan","CheckNotEqual","CheckOneOf","CheckOwnedRelation","DataArchivable","DataBulk","DataCapabilities","DataCompositeField","DataDenormalized","DataDirectOwner","DataEntityMembership","DataFileRef","DataForceCurrentUser","DataGenerated","DataHistory","DataI18n","DataId","DataIdentity","DataImmutableFields","DataInflection","DataInheritFromParent","DataJsonb","DataLock","DataMemberOwner","DataOwnedFields","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchBm25","SearchFullText","SearchSpatial","SearchSpatialAggregate","SearchTrgm","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","EventReferral","EventTracker","GuardStepUp","JobTrigger","LimitEnforceAggregate","LimitEnforceCounter","LimitEnforceFeature","LimitEnforceRate","LimitTrackUsage","LimitWarningAggregate","LimitWarningCounter","LimitWarningRate","ProcessChunks","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"]}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"if":{"$ref":"#/$defs/shared-49ec07b1f5"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-21a1ba9587"},{"if":{"properties":{"$type":{"const":"AuthzColumnSecurity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzColumnSecurityParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"if":{"$ref":"#/$defs/shared-47ab73adbe"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-34021cf1ff"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-15602a740a"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzEntityMembershipParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-5f5453df14"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzFilePathParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-aced6572ca"},{"if":{"$ref":"#/$defs/shared-eff5f86cd2"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberListParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-d91c021eee"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberOwnerParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-2c17992067"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzNotReadOnlyParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-97d5c3be03"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzOrgHierarchyParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-b1dc7b2e4f"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPeerOwnershipParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"if":{"$ref":"#/$defs/shared-f93f3b8ac9"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-584ca266e8"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberListParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-433a283165"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-5192cb016d"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"if":{"$ref":"#/$defs/shared-57b27779bd"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueAllowedParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-e23bde2ba6"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueExistsParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-3245b618eb"},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueMatchParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckGreaterThanParams"}}}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckLessThanParams"}}}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckNotEqualParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOneOfParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"CheckOwnedRelation"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOwnedRelationParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataArchivable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataArchivableParams"}}}},{"if":{"properties":{"$type":{"const":"DataBulk"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataBulkParams"}}}},{"if":{"properties":{"$type":{"const":"DataCapabilities"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCapabilitiesParams"}}}},{"if":{"properties":{"$type":{"const":"DataCompositeField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCompositeFieldParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDenormalized"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDenormalizedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDirectOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataEntityMembershipParams"}}}},{"if":{"properties":{"$type":{"const":"DataFileRef"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataFileRefParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataForceCurrentUser"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataForceCurrentUserParams"}}}},{"if":{"properties":{"$type":{"const":"DataGenerated"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataGeneratedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataHistory"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataHistoryParams"}}}},{"if":{"properties":{"$type":{"const":"DataI18n"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataI18nParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataId"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdParams"}}}},{"if":{"properties":{"$type":{"const":"DataIdentity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdentityParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataImmutableFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataImmutableFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInflection"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInflectionParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInheritFromParent"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInheritFromParentParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataJsonb"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataJsonbParams"}}}},{"if":{"properties":{"$type":{"const":"DataLock"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataLockParams"}}}},{"if":{"properties":{"$type":{"const":"DataMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataMemberOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataOwnedFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnedFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataOwnershipInEntity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnershipInEntityParams"}}}},{"if":{"properties":{"$type":{"const":"DataPeoplestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPeoplestampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPrincipalstamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPrincipalstampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPublishableParams"}}}},{"if":{"properties":{"$type":{"const":"DataRealtime"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataRealtimeParams"}}}},{"if":{"properties":{"$type":{"const":"DataSlug"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSlugParams"}}}},{"if":{"properties":{"$type":{"const":"DataSoftDelete"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSoftDeleteParams"}}}},{"if":{"properties":{"$type":{"const":"DataStatusField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataStatusFieldParams"}}}},{"if":{"properties":{"$type":{"const":"DataTags"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTagsParams"}}}},{"if":{"properties":{"$type":{"const":"DataTimestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTimestampsParams"}}}},{"if":{"properties":{"$type":{"const":"SearchBm25"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchBm25Params"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchFullText"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchFullTextParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchSpatial"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialParams"}}}},{"if":{"properties":{"$type":{"const":"SearchSpatialAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchTrgm"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchTrgmParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchUnified"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchUnifiedParams"}}}},{"if":{"properties":{"$type":{"const":"SearchVector"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchVectorParams"}}}},{"if":{"properties":{"$type":{"const":"TableOrganizationSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableOrganizationSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserProfiles"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserProfilesParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"EventReferral"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventReferralParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"EventTracker"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventTrackerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"GuardStepUp"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/GuardStepUpParams"}}}},{"if":{"properties":{"$type":{"const":"JobTrigger"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/JobTriggerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceFeature"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceFeatureParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitTrackUsage"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitTrackUsageParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"ProcessChunks"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessChunksParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessExtraction"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessExtractionParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessFileEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessFileEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageVersions"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageVersionsParams"}},"required":["data"]}}],"description":"Object form -- { $type, data } with typed parameters."},"BlueprintNodeShorthand":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzColumnSecurity","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch","CheckGreaterThan","CheckLessThan","CheckNotEqual","CheckOneOf","CheckOwnedRelation","DataArchivable","DataBulk","DataCapabilities","DataCompositeField","DataDenormalized","DataDirectOwner","DataEntityMembership","DataFileRef","DataForceCurrentUser","DataGenerated","DataHistory","DataI18n","DataId","DataIdentity","DataImmutableFields","DataInflection","DataInheritFromParent","DataJsonb","DataLock","DataMemberOwner","DataOwnedFields","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchBm25","SearchFullText","SearchSpatial","SearchSpatialAggregate","SearchTrgm","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","EventReferral","EventTracker","GuardStepUp","JobTrigger","LimitEnforceAggregate","LimitEnforceCounter","LimitEnforceFeature","LimitEnforceRate","LimitTrackUsage","LimitWarningAggregate","LimitWarningCounter","LimitWarningRate","ProcessChunks","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"],"description":"String shorthand -- just the node type name."},"BlueprintPolicy":{"type":"object","properties":{"privileges":{"type":"array","minItems":1,"items":{"type":"string","pattern":"^([Ss][Ee][Ll][Ee][Cc][Tt]|[Ii][Nn][Ss][Ee][Rr][Tt]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee])$"}},"permissive":{"type":"boolean"},"policy_role":{"type":"string"},"policy_name":{"type":"string"},"data":{"type":"object"},"with_check":{"$ref":"#/$defs/BlueprintPolicyWithCheck"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-c893ee8510"},{"$ref":"#/$defs/shared-a2c45e97d1"},{"$ref":"#/$defs/shared-85b2c2543e"},{"$ref":"#/$defs/shared-e3e4ac8f48"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-11809f0714"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-8e6e495eb6"},{"$ref":"#/$defs/shared-c2c61348f0"},{"$ref":"#/$defs/shared-4f25156f61"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-33013a269d"},{"$ref":"#/$defs/shared-0596961db6"},{"$ref":"#/$defs/shared-89ec3722aa"},{"$ref":"#/$defs/shared-1a97ddc6fb"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-c88c54a5c5"},{"$ref":"#/$defs/shared-3fc6945ad1"},{"$ref":"#/$defs/shared-c1527c6159"}],"description":"An RLS policy entry for a blueprint table. A with_check override applies to UPDATE only.","if":{"required":["with_check"]},"then":{"required":["privileges"],"properties":{"privileges":{"items":{"type":"string","pattern":"^[Uu][Pp][Dd][Aa][Tt][Ee]$"}}}}},"BlueprintPolicyWithCheck":{"type":"object","properties":{"data":{"type":"object"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-c893ee8510"},{"$ref":"#/$defs/shared-a2c45e97d1"},{"$ref":"#/$defs/shared-85b2c2543e"},{"$ref":"#/$defs/shared-e3e4ac8f48"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-11809f0714"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-8e6e495eb6"},{"$ref":"#/$defs/shared-c2c61348f0"},{"$ref":"#/$defs/shared-4f25156f61"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-33013a269d"},{"$ref":"#/$defs/shared-0596961db6"},{"$ref":"#/$defs/shared-89ec3722aa"},{"$ref":"#/$defs/shared-1a97ddc6fb"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-c88c54a5c5"},{"$ref":"#/$defs/shared-3fc6945ad1"},{"$ref":"#/$defs/shared-c1527c6159"}]},"BlueprintRelation":{"type":"object","description":"A relation entry in a blueprint definition.","properties":{"source_table":{"type":"string"},"target_table":{"type":"string"},"source_schema":{"type":"string"},"target_schema":{"type":"string"},"source_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"target_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"$type":{"enum":["RelationBelongsTo","RelationHasMany","RelationHasOne","RelationManyToMany","RelationSpatial"]}},"required":["$type"],"allOf":[{"if":{"properties":{"$type":{"const":"RelationBelongsTo"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field added"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., projects → project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}}}},{"if":{"properties":{"$type":{"const":"RelationHasMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Parent table being referenced by the FK (e.g., projects in projects has many tasks)"},"target_table_id":{"type":"string","format":"uuid","description":"Child table that receives the FK field (e.g., tasks in projects has many tasks)"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the target table. Auto-derived from source table name if omitted (e.g., projects derives project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}}}},{"if":{"properties":{"$type":{"const":"RelationHasOne"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field and unique constraint"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., users → user_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}}}},{"if":{"properties":{"$type":{"const":"RelationManyToMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"First table in the M:N relationship"},"target_table_id":{"type":"string","format":"uuid","description":"Second table in the M:N relationship"},"junction_table_id":{"type":"string","format":"uuid","description":"Existing junction table to use. If uuid_nil(), a new bare table is created"},"junction_table_name":{"type":"string","description":"Junction table name. Auto-derived from both table names if omitted (e.g., projects + tags derives project_tags)"},"source_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for source table. Auto-derived if omitted (e.g., projects derives project_id)"},"target_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for target table. Auto-derived if omitted (e.g., tags derives tag_id)"},"use_composite_key":{"type":"boolean","description":"When true, creates a composite PK from the two FK fields. When false, no PK is created by the trigger (use nodes with DataId for UUID PK). Mutually exclusive with nodes containing DataId.","default":false},"nodes":{"type":"array","items":{"type":"object"},"description":"Array of node objects for field creation on junction table. Each object has a $type key (e.g. DataId, DataEntityMembership) and optional data keys. Forwarded to secure_table_provision as-is. Empty array means no additional fields."},"grants":{"type":"array","items":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{"type":"array","items":{"type":"string"}}}},"required":["roles","privileges"]},"description":"Unified grant objects for the junction table. Each entry is { roles: string[], privileges: string[][] }. Forwarded to secure_table_provision as-is. Default: []"},"policies":{"type":"array","items":{"type":"object","properties":{"$type":{"type":"string"},"data":{"type":"object"},"privileges":{"type":"array","items":{"type":"string"}},"policy_role":{"type":"string"},"permissive":{"type":"boolean"},"policy_name":{"type":"string"}},"required":["$type"]},"description":"RLS policy objects for the junction table. Each entry has $type (Authz* generator), optional data, privileges, policy_role, permissive, policy_name. Forwarded to secure_table_provision as-is. Default: []"}}}},{"if":{"properties":{"$type":{"const":"RelationSpatial"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that owns the relation (the @spatialRelation tag is emitted on the owner column of this table)"},"source_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on source_table that carries the @spatialRelation smart tag"},"target_table_id":{"type":"string","format":"uuid","description":"Table being referenced by the spatial predicate"},"target_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on target_table that the predicate is evaluated against"},"name":{"type":"string","description":"Relation name (stable, snake_case). Becomes the generated filter field name in GraphQL (e.g. nearby_clinic). Unique per (source_table_id, name) — idempotency key."},"operator":{"type":"string","enum":["st_contains","st_within","st_intersects","st_covers","st_coveredby","st_overlaps","st_touches","st_dwithin"],"description":"PostGIS spatial predicate. One of the 8 whitelisted operators. st_dwithin requires param_name."},"param_name":{"type":"string","description":"Parameter name for parametric operators (currently only st_dwithin, which needs a distance argument). Must be NULL for all other operators. Enforced by table CHECK."},"source_field":{"type":"string"},"target_field":{"type":"string"}},"required":["source_field","target_field"]}}]},"BlueprintStorageConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Storage scope. \"app\" (default) creates app-level storage (no owner_id). \"org\" creates per-org/user storage (owner_id = org entity id, buckets seeded per-entity via AFTER INSERT trigger). Only \"app\" and \"org\" are allowed — child entity types get storage via entity_types[].storage."},"key":{"type":"string","description":"Module key discriminator. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case."},"storage_key":{"type":"string","description":"@deprecated Use `key` instead. Kept for backward compatibility."},"buckets":{"type":"array","items":{"$ref":"#/$defs/BlueprintBucketSeed"},"description":"Initial bucket seed entries. Each creates a row in {prefix}_buckets during provisioning."},"upload_url_expiry_seconds":{"type":"number","description":"Override for presigned upload URL expiry time in seconds."},"download_url_expiry_seconds":{"type":"number","description":"Override for presigned download URL expiry time in seconds."},"default_max_file_size":{"type":"number","description":"Default maximum file size in bytes for the storage module."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for the storage module."},"confirm_upload_delay":{"type":"string","description":"Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. \"30 seconds\"). Defaults to \"30 seconds\"."},"staging":{"type":"boolean","description":"Provision a temporary staging bucket (type temp, tagged default-temp) that stages for the private default bucket, so uploads land there and are promoted into their destination on confirmation. Setting staging_ttl implies this. Defaults to false."},"staging_ttl":{"type":"string","description":"How long an unpromoted staged file survives before it is eligible for expiry (PostgreSQL interval string, e.g. \"24 hours\"). Implies staging. Defaults to \"24 hours\"."},"provisions":{"type":"object","properties":{"files":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"buckets":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for storage tables. Each key targets a specific storage table (files, buckets) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision targeting the corresponding table. When a key includes policies[], those REPLACE the default storage policies for that table; tables without a key still get defaults."}},"description":"Storage configuration with optional scope. When used at the top level of a blueprint, the scope field controls whether storage is app-level (\"app\", default) or org-level (\"org\"). Seeds initial buckets, overrides module-level settings (expiry times, file size limits, CORS), and provides per-table provisioning overrides via provisions."},"BlueprintTable":{"type":"object","properties":{"table_name":{"type":"string","description":"The PostgreSQL table name to create. Required unless the entry carries a module reference instead."},"schema_name":{"type":"string","description":"Optional schema name (falls back to top-level default)."},"module":{"anyOf":[{"$ref":"#/$defs/BlueprintModuleTableRef"},{"$ref":"#/$defs/BlueprintModuleInstallRef"}],"description":"Attach this entry to a table an installed module generated instead of naming one, e.g. { type: \"agent\", scope: \"org\", table: \"message\" }. Mutually exclusive with table_name/schema_name. An entry carrying provisions names the install alone and leaves out table, since the provisions keys name the tables."},"provisions":{"type":"object","additionalProperties":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"description":"Provision security onto the tables the referenced module generated, keyed by the module's own table keys (e.g. { registries: { policies: [...] } } for an image module). Requires a module reference without \"table\", since the keys name the tables. Each entry takes ownership of the security it declares: the grants/policies given become that table's whole set, replacing what the module installed — unlike this entry's own policies[]/grants[], which layer onto one table."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Array of node type entries that define the table's behavior. Omitted by an entry that only carries provisions or only attaches policies to a module table."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the table."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for this table."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples (e.g. [[\"select\",\"*\"]]). Enables per-role targeting. Defaults to []."},"use_rls":{"type":"boolean","description":"Whether to enable RLS on this table. Defaults to true."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableIndex"},"description":"Table-level indexes (table_name inherited from parent)."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableFullTextSearch"},"description":"Table-level full-text search configurations (table_name inherited from parent)."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableUniqueConstraint"},"description":"Table-level unique constraints (table_name inherited from parent)."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableCheckConstraint"},"description":"Table-level CHECK constraints (table_name inherited from parent)."}},"description":"A table definition within a blueprint."},"BlueprintTableCheckConstraint":{"type":"object","properties":{"$type":{"enum":["CheckOneOf","CheckGreaterThan","CheckLessThan","CheckNotEqual"]}},"required":["$type"],"allOf":[{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"type":"object","properties":{"$type":{"const":"CheckOneOf"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckOneOfParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"type":"object","properties":{"$type":{"const":"CheckGreaterThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckGreaterThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"type":"object","properties":{"$type":{"const":"CheckLessThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckLessThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"type":"object","properties":{"$type":{"const":"CheckNotEqual"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckNotEqualParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}}],"description":"A CHECK constraint nested inside a table definition (table_name not required)."},"BlueprintTableFullTextSearch":{"type":"object","properties":{"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["field","sources"],"description":"A full-text search configuration nested inside a table definition (table_name not required)."},"BlueprintTableIndex":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["access_method"],"description":"An index definition nested inside a table definition (table_name not required)."},"BlueprintTableUniqueConstraint":{"type":"object","properties":{"columns":{"$ref":"#/$defs/shared-a0bfcadf85"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["columns"],"description":"A unique constraint nested inside a table definition (table_name not required)."},"BlueprintUniqueConstraint":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this unique constraint belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"columns":{"$ref":"#/$defs/shared-a0bfcadf85"}},"required":["table_name","columns"],"description":"A unique constraint definition within a blueprint (top-level, requires table_name)."},"CheckGreaterThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column > value)","default":0},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] > columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is greater than a threshold (single-column: column > value) or that one column is greater than another (cross-column: columns[0] > columns[1]). Compiled via AST helpers."},"CheckLessThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column < value)"},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] < columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is less than a threshold (single-column: column < value) or that one column is less than another (cross-column: columns[0] < columns[1]). Compiled via AST helpers."},"CheckNotEqualParams":{"type":"object","properties":{"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns that must not be equal","minItems":2,"maxItems":2}},"required":["columns"],"description":"Adds a CHECK constraint that validates two columns are not equal (columns[0] != columns[1]). Useful for preventing self-referencing rows. Compiled via AST helpers."},"CheckOneOfParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","description":"Column to validate against the allowed values"},"values":{"type":"array","items":{"type":"string"},"description":"Array of allowed values for the column"}},"required":["column","values"],"description":"Adds a CHECK constraint that validates a column value is one of an allowed set (e.g. tier IN ('free', 'paid', 'custom')). Compiled to column = ANY(ARRAY[...]) via AST helpers."},"CheckOwnedRelationParams":{"type":"object","properties":{"link_schema_name":{"type":"string","description":"Schema holding the link tables the ownership is proven through"},"owner_scope":{"type":"string","description":"Scope that owns the referencing rows; matched against the link row's owner_scope (e.g. database, platform)"},"owner_key_field_name":{"type":"string","format":"column-ref","description":"Column on the referencing table carrying its scope key, matched against the link row's owner_key. NULL for a global scope, whose owner key is NULL by construction"},"pointers":{"type":"array","description":"Typed pointer columns to guard, each resolved through its own link table","items":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Pointer column on the referencing table"},"link_table_name":{"type":"string","description":"Link table in link_schema_name whose ids this column points at"},"target_type_field_name":{"type":"string","description":"Optional link column additionally restricted regardless of ownership (e.g. a bucket type)"},"target_type_value":{"type":"string","description":"Value target_type_field_name must equal"},"allow_owner_tier":{"type":"boolean","description":"Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database","default":false}},"required":["field_name","link_table_name"]}},"arity":{"type":"string","enum":["exactly_one","all","any"],"description":"How many pointers a row must set: exactly_one for a polymorphic target (route → api OR site OR bucket), all for a junction/join row of a has-and-belongs-to-many relation (and for a mandatory belongs-to), any for optional pointers that are only checked when set","default":"exactly_one"},"required_error":{"type":"string","description":"Error code raised when the arity rule over the pointers is violated","default":"OWNED_RELATION_TARGET_REQUIRED"},"denied_error":{"type":"string","description":"Error code raised when the target is not owned by the referencing row owner","default":"OWNED_RELATION_TARGET_NOT_OWNED"},"trigger_function_schema":{"type":"string","description":"Schema the guard trigger function is created in; defaults to the table schema"},"trigger_function_name":{"type":"string","description":"Guard trigger function name; defaults to tg__owned_relation_guard"},"trigger_name":{"type":"string","description":"Guard trigger name; defaults to
_owned_relation_guard"}},"required":["link_schema_name","owner_scope","pointers"],"description":"Declares that typed pointer columns may only reference rows owned by the same scope owner as the referencing row, proven through a link table that carries the owner (owner_scope, owner_key) — typically a catalog projection that must never be referenced structurally. Creates one BEFORE INSERT OR UPDATE trigger enforcing the declared arity over the pointers and requiring every pointer that is set to resolve to a same-owner row, so it covers belongs-to / has-one / has-many (key on the row being written) and has-and-belongs-to-many (both keys on the junction row, arity all). Visibility/publication flags are never an authorization input."},"DataArchivableParams":{"type":"object","properties":{"is_archived_field":{"type":"string","format":"column-ref","description":"Column name for the archive boolean flag","default":"is_archived"},"archived_at_field":{"type":"string","format":"column-ref","description":"Column name for the archive timestamp","default":"archived_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds user-reversible archive support with is_archived boolean and archived_at timestamp, plus a partial index for efficient active-row queries."},"DataBulkParams":{"type":"object","properties":{"insert":{"type":"boolean","description":"Enable bulk insert (+bulkInsert)","default":true},"upsert":{"type":"boolean","description":"Enable bulk upsert (+bulkUpsert)","default":false},"update":{"type":"boolean","description":"Enable bulk update (+bulkUpdate)","default":false},"delete":{"type":"boolean","description":"Enable bulk delete (+bulkDelete)","default":false}},"description":"Enables bulk mutation smart tags on a table. When provisioned, adds @behavior tags for the selected bulk operations (insert, upsert, update, delete). Requires the graphile-bulk-mutations plugin."},"DataCapabilitiesParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the bit(n) mask column to create on this table.","default":"required_capabilities"},"capabilities":{"type":"string","description":"Selects the capabilities module whose bit numbering the mask is measured in, by scope (e.g. \"app\", \"org\") or by table prefix. Required only when the database has more than one; several with no selector raises naming the candidates."},"default":{"type":"array","items":{"type":"string"},"description":"Capability names every row requires unless told otherwise, resolved to a literal mask and baked into the column default. Omitted means a zero mask: requires nothing."},"mode":{"type":"string","enum":["direct","derived"],"description":"Who writes the mask: \"direct\" the writer, bounded by the subset guard; \"derived\" the mapping row named by from_column, stamped by generated triggers and hidden from mutations.","default":"direct"},"from_column":{"type":"string","format":"column-ref","description":"Derived mode only: the column on this table naming the mapping row to copy the mask from (e.g. classification_id)."},"mapping_table":{"type":"string","description":"Derived mode only: table holding one mask per class (e.g. document_classifications)."},"mapping_key":{"type":"string","format":"column-ref","description":"Derived mode only: column on the mapping table that from_column matches.","default":"id"},"mapping_column":{"type":"string","format":"column-ref","description":"Derived mode only: the mapping table's own bit(n) mask column. Created when absent, so a classification table needs no DataCapabilities declaration of its own. Defaults to the same name as field."},"subset_guard":{"type":"boolean","description":"Direct mode only: refuse a write requiring bits the writer does not hold, so nobody can lock a row away from everyone including themselves. Off is for trusted-writer tables only.","default":true},"entity_field":{"type":"string","format":"column-ref","description":"Direct mode only: the entity column the subset guard's membership check reads.","default":"entity_id"}},"description":"Per-row required permissions. A profile compiles a person to bits so no policy joins a profiles table; this compiles a row to bits so no policy joins a grant table either — the row stores which permissions are required, and an AuthzEntityMembership policy with mask_column checks that the user has all of them. The mask only narrows: it takes access away from someone membership already lets in, and never grants access to a non-member. Zero requires nothing, which is what an unclassified row defaults to. In direct mode the writer sets the mask and the subset guard bounds it to bits the writer holds; in derived mode it is copied from a mapping row (classification -> mask) by generated triggers, so authors edit one classification instead of every document."},"DataCompositeFieldParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the derived text field to create","default":"embedding_text"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names to concatenate into the target field"},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format: 'labeled' (field_name: value) or 'plain' (values only)","default":"labeled"}},"required":["source_fields"],"description":"Creates a derived text field that automatically concatenates multiple source fields via BEFORE INSERT/UPDATE triggers. Used to produce a unified text representation (e.g., embedding_text) from multiple columns on a table. The trigger fires with '_000' prefix to run before Search* triggers alphabetically."},"DataDenormalizedParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"FK field on this table that references the parent row (e.g. view_id)"},"set_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on this table to be populated from the parent (e.g. [\"database_id\"])"},"ref_field":{"type":"string","format":"column-ref","description":"Field on the parent table that is the FK target (e.g. id)"},"ref_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the parent table to copy from (e.g. [\"database_id\"])"},"use_updates":{"type":"boolean","description":"If true, also creates an UPDATE trigger so changes to the FK re-copy values","default":true},"update_defaults":{"type":"boolean","description":"If true, sets the default value of set_fields to uuid_nil() so they are populated by the trigger","default":true},"func_name":{"type":"string","description":"Custom function name suffix (defaults to the FK field name)"},"func_order":{"type":"integer","description":"Trigger ordering (0-padded). Lower numbers fire first","default":0}},"required":["field","set_fields","ref_field","ref_fields"],"description":"Creates INSERT and UPDATE triggers that copy field values from a referenced (parent) table into the current table whenever the FK changes. Used to denormalize frequently-read columns (e.g. database_id on junction tables) so that RLS and queries can filter locally without joining."},"DataDirectOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for owner ID","default":"owner_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from owner_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the owner column","default":true}},"description":"Adds ownership column for direct user ownership. Enables AuthzDirectOwner authorization."},"DataEntityMembershipParams":{"type":"object","properties":{"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for entity ID","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the entity column","default":true}},"description":"Adds entity reference for organization/group scoping. Enables AuthzEntityMembership, AuthzMembership, AuthzOrgHierarchy authorization."},"DataFileRefParams":{"type":"object","required":["field"],"properties":{"field":{"type":"string","format":"column-ref","pattern":"\\S","description":"The upload, image or attachment column to register"},"storage":{"type":"object","description":"The storage module the file lives in, selected by its scope and/or key; every key given must match exactly one module. When omitted, the table's scope column decides, and a table with no scope column uses the app's storage.","properties":{"scope":{"type":"string","pattern":"\\S","description":"Scope of the storage module, e.g. \"app\", \"org\" or an entity type's scope"},"key":{"type":"string","pattern":"\\S","description":"Key of the storage module, for a scope with more than one"}},"minProperties":1,"additionalProperties":false},"bucket":{"type":"string","pattern":"\\S","description":"Key of the bucket an upload resolves to. Set this or bucket_tags, not both."},"bucket_tags":{"type":"array","items":{"type":"string"},"description":"Tags of the bucket an upload resolves to. Set this or bucket, not both."},"is_public":{"type":"boolean","description":"With no bucket named, picks the default public (true) or private (false) bucket; with a bucket named, asserts that bucket is public or private. Omitted, the bucket alone decides."},"enforce_fk":{"type":"boolean","description":"Strict mode: a real foreign key beside the column. Not implemented yet, so the backend refuses true.","default":false}},"not":{"required":["bucket","bucket_tags"]},"description":"Registers an existing upload, image or attachment column as a managed reference to a files row: it records which storage module the file lives in and which bucket an upload resolves to, and the backend generates the sync trigger and the GC index from that. The column must be declared in fields[] first; the node creates no column."},"DataForceCurrentUserParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to force to current_user_id()","default":"actor_id"}},"description":"BEFORE INSERT trigger that forces a field to the value of jwt_public.current_user_id(). Prevents clients from spoofing the actor/uploader identity. The field value is always overwritten regardless of what the client provides."},"DataGeneratedParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the generated column to create"},"type":{"type":"object","description":"FieldType for the generated column (default: text)","default":{"name":"text"}},"kind":{"type":"string","enum":["expression","concat","slug","object_name","hash"],"description":"Preset for building the generation expression","default":"expression"},"generation_type":{"type":"string","enum":["stored","virtual"],"description":"Whether the column is STORED (persisted on write) or VIRTUAL (computed on read, PostgreSQL 18+)","default":"stored"},"source_field":{"type":"string","format":"column-ref","description":"Single source field for expression/slug/object_name presets"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names for concat/hash presets"},"expression":{"type":"object","description":"Raw FieldGeneration DSL or AST (used when kind is expression)"},"separator":{"type":"string","description":"Separator used by concat preset","default":" "},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format for concat preset: 'labeled' (field_name: value) or 'plain' (values only)","default":"plain"},"prefix":{"type":"string","description":"Optional prefix for object_name preset"},"suffix":{"type":"string","description":"Optional suffix for object_name preset"},"algorithm":{"type":"string","description":"Hash algorithm for hash preset (e.g. sha256, md5)","default":"sha256"},"is_required":{"type":"boolean","description":"Whether the generated column is NOT NULL","default":false}},"required":["target"],"description":"Creates a native PostgreSQL GENERATED ALWAYS AS (expr) column (STORED or VIRTUAL) from a source field expression, preset, or raw AST. The column is read-only for clients and computed automatically by PostgreSQL."},"DataHistoryParams":{"type":"object","properties":{"table_suffix":{"type":"string","description":"Suffix for the history table name","default":"_history"},"recorded_at_field":{"type":"string","format":"column-ref","description":"Column name for the version timestamp (also the partition key when partitioned)","default":"recorded_at"},"operation_field":{"type":"string","format":"column-ref","description":"Column name recording the operation ('INSERT' | 'UPDATE' | 'DELETE')","default":"history_op"},"exclude_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Source columns to omit from the history table (e.g. large jsonb or vector columns). Excluded columns are never created on the history table and never written by the trigger.","default":[]},"copy_mutation_policies":{"type":"boolean","description":"Whether to also clone INSERT/UPDATE/DELETE policies (not just SELECT). Default false — the history table is written only by the trigger and exposed read-only through GraphQL.","default":false},"partitioned":{"type":"boolean","description":"When true, range-partition the history table by recorded_at via pg_partman so old partitions can be dropped per the retention window.","default":false},"partition_interval":{"type":"string","description":"pg_partman partition interval (when partitioned)","default":"1 month"},"retention":{"type":"string","description":"pg_partman retention window; partitions older than this are dropped by run_maintenance (when partitioned). Empty keeps forever.","default":"12 months"},"premake":{"type":"integer","description":"Number of future partitions pg_partman pre-creates","default":2}},"description":"Creates a companion
_history table that records a new version row on every INSERT/UPDATE/DELETE via an AFTER trigger. The history table copies the source columns as plain nullable columns with NO keys or constraints, plus a recorded_at timestamp and a history_op column (NEW-append: INSERT/UPDATE store the new row, DELETE stores a tombstone). SELECT policies are cloned from the base table. Optionally range-partitions the history table by recorded_at (pg_partman) with a retention window so history is kept for a while but not forever. Adds an @history smart comment so the Graphile history plugin can expose version queries and restore mutations."},"DataI18nParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the base table to make translatable. Each field is duplicated on the translation table with the same type."},"table_suffix":{"type":"string","description":"Suffix for the translation table name","default":"_translations"},"lang_code_type":{"type":"string","enum":["citext","text"],"description":"Type for the lang_code column","default":"citext"},"copy_mutation_policies":{"type":"boolean","description":"Whether to also copy INSERT/UPDATE/DELETE policies (not just SELECT). Default true — translations should be editable by the same users who can edit the base row.","default":true},"search":{"type":"object","description":"SearchFullText configuration for the translations table. When provided, creates a tsvector column on the translations table with lang_column=lang_code for dynamic per-row language stemming.","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column on the translations table","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the translatable source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"}},"required":["field"]},"description":"Translatable columns that feed the tsvector. Language is determined dynamically from the lang_code column of each row."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"]}},"required":["fields"],"description":"Creates a companion _translations table with lang_code + translatable fields. Copies SELECT policies and column-ref fields from the base table. Adds @i18n smart comment so the Graphile i18n plugin discovers it. Requires i18n_module to be provisioned for the database."},"DataIdParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the primary key","default":"id"}},"description":"Adds a UUID primary key column with auto-generation default (uuidv7). This is the standard primary key pattern for all tables."},"DataIdentityParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the identity column to create"},"type":{"type":"object","description":"FieldType for the identity column (default: bigint)","default":{"name":"bigint"}},"generation":{"type":"string","enum":["always","by_default"],"description":"'always' for GENERATED ALWAYS AS IDENTITY, 'by_default' for GENERATED BY DEFAULT AS IDENTITY","default":"by_default"},"sequence":{"type":"object","description":"Optional sequence tuning for the backing identity sequence","properties":{"start":{"type":"integer","description":"START WITH value"},"increment":{"type":"integer","description":"INCREMENT BY value"},"min":{"type":["integer","null"],"description":"MINVALUE (null uses the default)"},"max":{"type":["integer","null"],"description":"MAXVALUE (null uses the default)"},"cache":{"type":"integer","description":"CACHE value"},"cycle":{"type":"boolean","description":"Whether the sequence cycles (CYCLE / NO CYCLE)"}}},"is_required":{"type":"boolean","description":"Whether the identity column is NOT NULL (identity columns are implicitly NOT NULL)","default":false}},"required":["target"],"description":"Creates a native PostgreSQL identity column (GENERATED ALWAYS / BY DEFAULT AS IDENTITY) backed by an implicit sequence. The database assigns values automatically; ALWAYS identity columns are not writable by clients."},"DataImmutableFieldsParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names that cannot be modified after INSERT (e.g. [\"key\", \"bucket_id\", \"owner_id\"])"}},"required":["fields"],"description":"BEFORE UPDATE trigger that prevents changes to a list of specified fields after INSERT. Raises an exception if any of the listed fields have changed. Unlike FieldImmutable (single-field), this handles multiple fields in a single trigger for efficiency."},"DataInflectionParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to transform"},"ops":{"type":"array","items":{"type":"string","enum":["plural","singular","camel","pascal","dashed","slugify","underscore","lower","upper"]},"description":"Inflection operations to apply in order"}},"required":["field_name","ops"],"description":"Transforms field values using inflection operations (snake_case, camelCase, slugify, plural, singular, etc). Attaches BEFORE INSERT and BEFORE UPDATE triggers. References fields by name in data jsonb."},"DataInheritFromParentParams":{"type":"object","properties":{"parent_fk_field":{"type":"string","format":"column-ref","description":"Name of the FK field on this table that references the parent (e.g. bucket_id)"},"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to copy from the parent row (e.g. [\"owner_id\", \"is_public\"])"},"parent_table":{"type":"string","description":"Parent table name (optional fallback if FK not yet registered in metaschema)"},"parent_schema":{"type":"string","description":"Parent table schema (optional, defaults to same schema as child table)"}},"required":["parent_fk_field","fields"],"description":"BEFORE INSERT trigger that copies specified fields from a parent table via a foreign key. The parent row is looked up through RLS (SECURITY INVOKER), so the insert fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files."},"DataJsonbParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the JSONB field","default":"metadata"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false},"create_index":{"type":"boolean","description":"Whether to create a GIN index","default":true}},"description":"Adds a JSONB column with optional GIN index for containment queries (@>, ?, ?|, ?&). Standard pattern for semi-structured metadata."},"DataLockParams":{"type":"object","properties":{"lock_field":{"type":"string","format":"column-ref","description":"Boolean column holding the lock state","default":"locked"},"events":{"type":"array","items":{"type":"string","enum":["UPDATE","DELETE"]},"description":"Which DML events are guarded while the row is locked. INSERT is not lockable — a row cannot be locked before it exists.","default":["DELETE"]},"enforcement":{"type":"string","enum":["step_up","block"],"description":"How a guarded verb is stopped while locked. step_up requires recent strong verification (needs a provisioned user_auth_module); block refuses the verb outright with ROW_LOCKED until unlocked.","default":"step_up"},"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Verification method satisfying the step-up requirement, for the guarded verbs in step_up mode and for clearing the lock","default":"fresh_auth"},"guard_unlock":{"type":"boolean","description":"Require step-up to change the lock column itself, so a locked row cannot be quietly unlocked and then deleted. Redundant (and therefore skipped) in step_up mode when UPDATE is already guarded.","default":true},"protect_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For a guarded UPDATE, restrict the guard to changes touching these columns. Empty guards the whole row.","default":[]},"default_locked":{"type":"boolean","description":"Initial value of the lock column for new rows","default":false},"min_age":{"type":"string","description":"Optional interval (e.g. \"24 hours\"); in step_up mode the guard only fires for rows older than this, so freshly created rows stay easy to clean up. Empty guards rows of any age.","default":""}},"description":"Adds a boolean lock column and guards mutations while a row is locked, so infrastructure rows other things depend on (a bucket a function needs, a route, a resource) are not deleted or edited by accident. Two enforcement modes: step_up requires recent strong verification (via GuardStepUp / require_step_up) for the guarded verbs, while block refuses them outright until the row is unlocked. Clearing the lock is itself step-up guarded, so unlocking is a deliberate, re-authenticated step rather than a silent prelude to deletion."},"DataMemberOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true},"entity_type":{"type":"string","description":"Membership scope (e.g. 'org', 'room'). Resolved to a membership type via the database's membership_types_module. This is the authoring form — use it instead of membership_type."},"membership_type":{"type":"integer","description":"Membership type resolved from the scope. Internal: prefer entity_type. Cannot be combined with entity_type.","default":null}},"description":"Adds owner_id and entity_id columns with a compound AuthzMemberOwner policy. The current user must own the row and be a member of the entity it belongs to. Use for private data within an entity scope — e.g., personal chat threads that belong to the company but only the author can see."},"DataOwnedFieldsParams":{"type":"object","properties":{"role_key_field_name":{"type":"string","format":"column-ref","description":"Name of the field identifying the owner (e.g. sender_id)"},"protected_field_names":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Names of fields only this owner can modify"}},"required":["role_key_field_name","protected_field_names"],"description":"Restricts which user can modify specific columns in shared objects. Creates an AFTER UPDATE trigger that throws OWNED_PROPS when a non-owner tries to change protected fields. References fields by name in data jsonb."},"DataOwnershipInEntityParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true}},"description":"Combines direct ownership with entity scoping. Adds both owner_id and entity_id columns. Enables AuthzDirectOwner, AuthzEntityMembership, and AuthzOrgHierarchy authorization. Particularly useful for OrgHierarchy where a user owns a row (owner_id) within an entity (entity_id), and managers above can see subordinate-owned records via the hierarchy closure table."},"DataPeoplestampsParams":{"type":"object","properties":{"created_by_field":{"type":"string","format":"column-ref","description":"Column name for the creating user reference","default":"created_by"},"updated_by_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating user reference","default":"updated_by"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from created_by and updated_by to the users table","default":false},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the peoplestamp columns","default":true}},"description":"Adds human actor tracking for creates/updates: created_by/updated_by record the human user (jwt_public.current_user_id())."},"DataPrincipalstampsParams":{"type":"object","properties":{"created_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the creating principal reference (agent, API key, or user)","default":"created_by_principal"},"updated_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating principal reference (agent, API key, or user)","default":"updated_by_principal"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the principalstamp columns","default":true}},"description":"Adds acting-principal tracking for creates/updates: created_by_principal/updated_by_principal record the acting principal — agent, API key, service identity, or the user itself (jwt_public.current_principal_id())."},"DataPublishableParams":{"type":"object","properties":{"is_published_field_name":{"type":"string","format":"column-ref","description":"Column name for the published boolean flag","default":"is_published"},"published_at_field_name":{"type":"string","format":"column-ref","description":"Column name for the publish timestamp","default":"published_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds publish state columns (is_published, published_at) for content visibility. Enables AuthzPublishable and AuthzTemporal authorization."},"DataRealtimeParams":{"type":"object","properties":{"operations":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML operations to track with emit_change triggers","default":["INSERT","UPDATE","DELETE"]},"subscriber_table_name":{"type":"string","description":"Custom name for the subscriber table (defaults to {source_table}_subscriber)"},"ephemeral":{"type":"boolean","description":"When true, events are delivered via pg_notify only without writing to change_log. Ideal for high-frequency ephemeral signals (e.g. cursor positions, live indicators) where persistence is unnecessary. Subscriber table and RLS policies are still created for access control.","default":false}},"description":"Creates per-table subscriber tables in subscriptions_public with RLS policies derived from source table SELECT policies. Attaches statement-level triggers to emit changes to subscribers."},"DataSlugParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to slugify","default":"slug"},"source_field_name":{"type":"string","format":"column-ref","description":"Optional source field name (defaults to field_name)"}},"required":[],"description":"Auto-generates URL-friendly slugs from field values on insert/update. Attaches BEFORE INSERT and BEFORE UPDATE triggers that call inflection.slugify() on the target field. References fields by name in data jsonb."},"DataSoftDeleteParams":{"type":"object","properties":{"deleted_at_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete timestamp","default":"deleted_at"},"is_deleted_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete boolean flag","default":"is_deleted"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds soft delete support with deleted_at and is_deleted columns."},"DataStatusFieldParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the status field","default":"status"},"type":{"$ref":"#/$defs/FieldType","description":"Column type as a FieldType object"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object (e.g., { value: \"active\" })"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":true},"allowed_values":{"type":"array","items":{"type":"string"},"description":"If provided, creates a CHECK constraint restricting the column to these values"}},"description":"Adds a status column with B-tree index for efficient equality filtering and sorting. Optionally constrains values via CHECK constraint when allowed_values is provided."},"DataTagsParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the tags array","default":"tags"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false}},"description":"Adds a citext[] tags column with GIN index for efficient array containment queries (@>, &&). Standard tagging pattern for categorization and filtering."},"DataTimestampsParams":{"type":"object","properties":{"created_at_field":{"type":"string","format":"column-ref","description":"Column name for the creation timestamp","default":"created_at"},"updated_at_field":{"type":"string","format":"column-ref","description":"Column name for the last-updated timestamp","default":"updated_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds automatic timestamp tracking with created_at and updated_at columns."},"EventReferralParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record for the referrer (e.g., \"invitee_uploaded_avatar\", \"invitee_completed_onboarding\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the invitee (actor) ID on the source table — used to look up the referrer via claimed_invites.receiver_id","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped referral events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"max_depth":{"type":"integer","description":"Maximum depth to walk up the invite chain. Default 1 (direct inviter only). Set 2–10 to enable multi-level referral rewards. App-level only — must not be combined with entity_field.","default":1,"minimum":1,"maximum":10},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events for the referrer (inviter) when their invitees perform actions on a watched table. Resolves the referrer automatically via the invites module's claimed_invites table using the membership_type context. Supports the same compound condition system as EventTracker. Use with achievements to unlock levels and grant credits based on invitee activity."},"EventTrackerParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record (e.g., \"avatar_uploaded\", \"order_completed\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"count":{"type":"integer","description":"Number of events to record per trigger fire","default":1},"toggle":{"type":"boolean","description":"Toggle mode: records event when condition is met, removes when condition is unmet","default":false},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the actor (user) ID to attribute the event to","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events via the events module when table rows change. Supports the same compound condition system as JobTrigger (condition_field, watch_fields, or full AND/OR/NOT conditions). Events are recorded to app_events and aggregated automatically. Use with achievements (blueprint-level) to unlock levels and grant credits based on event accumulation."},"FieldDefault":{"type":"object","description":"A structured default expression, e.g. { value: false }, { function: \"now\" } or { value: {}, cast: { name: \"jsonb\" } }.","properties":{"value":{"description":"Literal value."},"function":{"type":"string","description":"Function name."},"schema":{"type":"string","description":"Schema qualifier of the function."},"args":{"type":"array","items":{"anyOf":[{"type":["string","number","boolean","null"]},{"$ref":"#/$defs/FieldDefault"}]},"description":"Function arguments."},"cast":{"$ref":"#/$defs/FieldType"},"operator":{"type":"string","description":"Binary operator, e.g. \"+\"."},"left":{"$ref":"#/$defs/FieldDefault"},"right":{"$ref":"#/$defs/FieldDefault"},"sql_keyword":{"type":"string","description":"SQL keyword, e.g. \"CURRENT_TIMESTAMP\"."}}},"FieldType":{"type":"object","description":"A structured PostgreSQL type, e.g. { name: \"text\" } or { name: \"numeric\", args: [10, 2] }.","properties":{"name":{"type":"string","description":"Type name."},"schema":{"type":"string","description":"Schema qualifier."},"args":{"type":"array","items":{"type":["string","number","boolean"]},"description":"Type arguments."},"array_dimensions":{"type":"integer","description":"Number of array dimensions: 1 is text[]."},"range":{"type":"array","items":{"type":"string"},"maxItems":2,"description":"Interval field range, e.g. [\"day\", \"second\"]."}},"required":["name"]},"GuardStepUpParams":{"type":"object","properties":{"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Which recent proof satisfies the step-up requirement: password (password re-entry), mfa (second factor), password_or_mfa (either factor; an SSO sign-in alone does not count), or fresh_auth (any recent sign-in or re-verification, including SSO, magic link and OTP)","default":"fresh_auth"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML events require step-up verification","default":["UPDATE","DELETE"]},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":[],"description":"Attaches a BEFORE trigger that calls require_step_up() to enforce recent strong verification (password, MFA, or identity-provider assertion) before allowing mutations. Requires a provisioned sessions_module (with app_settings_auth) for the target database. The step_up_window is read from app_settings_auth at runtime (default 30 minutes). Supports compound conditions (AND/OR/NOT), watch_fields (fire only when specific fields change), and simple condition_field/condition_value leaf conditions."},"JobTriggerParams":{"type":"object","properties":{"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier passed to add_job (e.g., process_invoice, sync_to_stripe). Must match a registered function definition when function_module is installed."},"payload_strategy":{"type":"string","enum":["row","row_id","fields","custom"],"description":"How to build the job payload: row (full NEW/OLD), row_id (just id), fields (selected columns), custom (mapped columns)","default":"row_id"},"payload_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names to include in payload (only for fields strategy)"},"payload_custom":{"type":"object","additionalProperties":{"type":"string","format":"column-ref"},"description":"Key-to-column mapping for custom payload (e.g., {\"invoice_id\": \"id\", \"total\": \"amount\"})"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Trigger events to create","default":["INSERT","UPDATE"]},"include_old":{"type":"boolean","description":"Include OLD row in payload (for UPDATE triggers)","default":false},"include_meta":{"type":"boolean","description":"Include table/schema metadata in payload","default":false},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"$ref":"#/$defs/shared-6b829f5502"},"obj_schema":{"$ref":"#/$defs/shared-11a9ffe32a"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"job_key":{"type":"string","description":"Static job key for upsert semantics (prevents duplicate jobs)"},"queue_name":{"type":"string","description":"Job queue name for routing to specific workers"},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0},"run_at_delay":{"type":"string","description":"Delay before job runs as PostgreSQL interval (e.g., 30 seconds, 5 minutes)"},"max_attempts":{"type":"integer","description":"Maximum retry attempts for the job","default":25}},"required":["task_identifier"],"description":"Dynamically creates PostgreSQL triggers that enqueue jobs via app_jobs.add_job() when table rows are inserted, updated, or deleted. Supports configurable payload strategies (full row, row ID, selected fields, or custom mapping), conditional firing via WHEN clauses, watched field changes, and extended job options (queue, priority, delay, max attempts)."},"LimitEnforceAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to track (must match a default_limits entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches aggregate limit-tracking triggers to a table. On INSERT the named limit is incremented per entity; on DELETE it is decremented. Uses org_limit_aggregates_inc/dec for per-entity (org-level) aggregate limits rather than per-user limits. Requires a provisioned limits_module for the target database."},"LimitEnforceCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to track (must match a default_limits entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor or entity id used for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for entity context resolution. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches limit-tracking triggers to a table. On INSERT the named limit is incremented; on DELETE it is decremented. Requires a provisioned limits_module for the target scope."},"LimitEnforceFeatureParams":{"type":"object","properties":{"feature_name":{"type":"string","description":"Cap name representing this feature (must match a limit_caps_defaults entry with max=0 or max=1)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for per-entity cap lookups (only used for org scope). For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["feature_name"],"description":"Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE INSERT trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0)."},"LimitEnforceRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry, e.g. \"messaging\", \"inference\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limiting. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id (user) for rate limiting","default":"owner_id"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Which DML events to enforce rate limits on (DELETE is excluded since it reduces load)","default":["INSERT"]}},"required":["meter_slug"],"description":"Attaches a BEFORE trigger that calls check_rate_limit() to enforce sliding-window rate limits before allowing mutations. The function checks all three scopes (entity, actor-in-entity, actor) in a single call; which scopes are actually enforced is controlled by what rows exist in rate_window_limits (plan-based config). Requires a provisioned meter_rate_limits_module and billing_module for the target database."},"LimitTrackUsageParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to record usage against (must match a meters table entry, e.g. \"databases\", \"seats\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for billing. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"quantity":{"type":"integer","description":"Units to record per event (default 1)","default":1},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["meter_slug"],"description":"Declaratively attaches billing usage-recording triggers to a table. On INSERT the named meter is incremented via record_usage; on DELETE it is decremented (reversal). On UPDATE, if the entity_field changes, the old entity is decremented and the new entity is incremented. Requires a provisioned billing_module for the target database."},"LimitWarningAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to watch (must match a limit_warnings.name entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the entity's aggregate usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor/entity triple. Requires a provisioned limits_module with limit_warnings and aggregate limits enabled."},"LimitWarningCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to watch (must match a limit_warnings.name entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id. When provided, entity_id is included in the job payload and dedup state. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires a provisioned limits_module with limit_warnings enabled."},"LimitWarningRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use for warnings and warning_state tables. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for rate limit lookup","default":"owner_id"}},"required":["meter_slug"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current request count in the active sliding window has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires both a limits_module with limit_warnings enabled and a rate_limit_meters_module."},"ProcessChunksParams":{"type":"object","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"dimensions":{"type":"integer","description":"Vector dimensions for per-chunk embeddings","default":768},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric for the HNSW index on chunk embeddings","default":"cosine"},"embedding_model":{"type":"string","description":"Embedding model identifier for per-chunk embeddings. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"chunks_table_name":{"type":"string","description":"Override the chunks table name. Defaults to {parent_table}_chunks."},"metadata_fields":{"type":"array","items":{"type":"string"},"description":"Field names from the parent table to copy into chunk metadata"},"search_indexes":{"type":"array","items":{"$ref":"#/$defs/shared-5492e6a87c"},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override (e.g. [\"fulltext\", \"bm25\"])."},"entity_field":{"type":"string","format":"column-ref","description":"Column on the parent table that holds (or references) the entity_id for billing scope. Forwarded to the chunking job trigger."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the chunking job trigger.","properties":{"obj_table":{"$ref":"#/$defs/shared-462d3d2412"},"obj_schema":{"$ref":"#/$defs/shared-3d0fa23a34"},"obj_field":{"$ref":"#/$defs/shared-d4553f7be9"}},"required":["obj_table","obj_field"]},"enqueue_chunking_job":{"type":"boolean","description":"Whether to create a job trigger that auto-enqueues chunking on parent INSERT/UPDATE","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}},"description":"Creates a chunked-embedding child table for any parent table. Provisions the chunks table with content, chunk_index, embedding vector, metadata, HNSW index, inherited RLS, and optional job trigger for automatic text splitting. Composed internally by ProcessFileEmbedding (enabled by default in extract mode) but can also be used standalone."},"ProcessExtractionParams":{"type":"object","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"extraction_model":{"type":"string","description":"Extraction model identifier (e.g. a vision model for OCR, an LLM for structured extraction). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config."},"extraction_provider":{"type":"string","description":"Extraction provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%'].","default":["application/pdf","text/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the extraction worker","default":"document:extract_file_text"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for extraction tasks","default":"extraction"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates extraction output fields and a job trigger for file text extraction. Fires when a file is uploaded (status = 'uploaded') or on INSERT. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks."},"ProcessFileEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 512 for CLIP, 768 for nomic, 1536 for ada-002)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\", \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%'].","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the worker. In direct mode this is the embedding worker; in extract mode this is the extraction worker.","default":"embedding:process_file_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"source_bucket":{"type":"object","description":"Typed bucket reference ({\"$ref\":\"bucket\",\"tags\":[...],\"type\":...}) for the bucket the source files live in, when it is not the record's own bucket_id (which payload_custom already carries). Stamped into the trigger payload at attach time and resolved to coordinates at dispatch.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"variants_bucket":{"type":"object","description":"Typed bucket reference for where derived outputs (thumbnails, resized variants, extracted assets) are written. Stamped into the trigger payload at attach time and resolved to coordinates at dispatch, so the function never selects a bucket.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"type":"object","description":"Text extraction configuration. When present, the generator creates extraction output fields on the table and configures SearchVector with source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction).","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"}}},"include_chunks":{"type":"boolean","description":"Whether to create a chunks table via ProcessChunks. Defaults to true when extraction is provided, false in direct mode. Set explicitly to override."},"chunks":{"type":"object","description":"Chunking configuration passed through to ProcessChunks. When include_chunks is true (or defaults to true in extract mode), these params configure the chunks table, embedding dimensions, strategy, etc.","default":{},"properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"metadata_fields":{"type":"array","items":{"type":"string"},"description":"Field names from parent to copy into chunk metadata"},"search_indexes":{"type":"array","items":{"$ref":"#/$defs/shared-5492e6a87c"},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override."},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}},"description":"Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies."},"ProcessImageEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (default 512 for CLIP-style image embeddings)","default":512},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image embedding worker","default":"embedding:process_image_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"type":"object","description":"Text extraction configuration. Forwarded to ProcessFileEmbedding. When present, enables extract mode (e.g., OCR for images).","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata","default":"extracted_metadata"}}},"chunks":{"type":"object","description":"Chunking configuration. Forwarded to ProcessFileEmbedding. Only meaningful when extraction is also provided.","properties":{"content_field_name":{"type":"string","format":"column-ref","default":"content"},"chunk_size":{"type":"integer","default":1000},"chunk_overlap":{"type":"integer","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"default":"paragraph"},"metadata_fields":{"type":"object"},"enqueue_chunking_job":{"type":"boolean","default":true},"chunking_task_name":{"type":"string","format":"function-ref","default":"embedding:chunk_record"}}}},"description":"Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_image_embedding', direct mode (no extraction). Accepts all ProcessFileEmbedding parameters — any overrides are forwarded through."},"ProcessImageVersionsParams":{"type":"object","required":["versions"],"properties":{"versions":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Version identifier (e.g., \"thumb\", \"preview\", \"hero\")"},"width":{"type":"integer","description":"Target width in pixels"},"height":{"type":"integer","description":"Target height in pixels"},"fit":{"type":"string","enum":["cover","contain","fill","inside","outside"],"description":"Resize fitting strategy","default":"cover"},"format":{"type":"string","enum":["jpeg","png","webp","avif"],"description":"Output image format","default":"webp"},"quality":{"type":"integer","description":"Output quality (1-100)","default":80}},"required":["name"]},"description":"Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Required — the blueprint must explicitly define what variants to generate.","minItems":1},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Defaults to all image types.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image processing worker","default":"image:process_image_versions"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"$ref":"#/$defs/shared-9af2f9702a"},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for image processing tasks","default":"image_processing"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates a job trigger for image variant generation. Fires when an image file is uploaded (status = 'uploaded') or on INSERT. The external worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.) and stores them as new file records linked to the source image."},"SearchBm25Params":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of existing text column to index with BM25"},"text_config":{"type":"string","description":"PostgreSQL text search configuration for BM25","default":"english"},"k1":{"type":"number","description":"BM25 k1 parameter: term frequency saturation (typical: 1.2-2.0)","default":null},"b":{"type":"number","description":"BM25 b parameter: document length normalization (0=none, 1=full, typical: 0.75)","default":null},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["field_name"],"description":"Creates a BM25 index on an existing text column using pg_textsearch. Enables statistical relevance ranking with configurable k1 and b parameters. The BM25 index is auto-detected by graphile-search."},"SearchFullTextParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"},"lang":{"type":"string","description":"PostgreSQL text search configuration","default":"english"}},"required":["field"]},"description":"Source columns that feed the tsvector. Each has a field name, weight (A-D), and language config."},"lang_column":{"type":"string","format":"column-ref","description":"Column name whose value determines the text search configuration per row. When set, the tsvector trigger uses NEW.::regconfig instead of a static language, enabling dynamic per-row language stemming. The per-field lang values in source_fields are used as fallback defaults for the langs array but the trigger reads from this column at runtime."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"],"description":"Adds a tsvector column with GIN index and automatic trigger population from source fields. Enables PostgreSQL full-text search with configurable weights and language support. Leverages the existing metaschema full_text_search infrastructure."},"SearchSpatialAggregateParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the aggregate geometry column on the parent table","default":"geom_aggregate"},"source_table_id":{"type":"string","format":"uuid","description":"UUID of the source (child) table containing individual geometries"},"source_geom_field":{"type":"string","format":"column-ref","description":"Name of the geometry column on the source table","default":"geom"},"source_fk_field":{"type":"string","format":"column-ref","description":"Name of the foreign key column on the source table pointing to the parent"},"aggregate_function":{"type":"string","enum":["union","collect","convex_hull","concave_hull"],"description":"PostGIS aggregation function: union (ST_Union, merges overlapping), collect (ST_Collect, groups without merging), convex_hull (smallest convex polygon), concave_hull (tighter boundary)","default":"union"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"Output geometry type constraint for the aggregate field","default":"MultiPolygon"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method for the aggregate field","default":"gist"}},"required":["source_table_id","source_fk_field"],"description":"Creates a derived/materialized geometry field on the parent table that automatically aggregates geometries from a source (child) table via triggers. When child rows are inserted/updated/deleted, the parent aggregate field is recalculated using the specified PostGIS aggregation function (ST_Union, ST_Collect, ST_ConvexHull, ST_ConcaveHull). Useful for materializing spatial boundaries from collections of points or polygons."},"SearchSpatialParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the geometry/geography column","default":"geom"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"PostGIS geometry type constraint","default":"Point"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry (for geodetic calculations on the sphere)","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method","default":"gist"}},"description":"Adds a PostGIS geometry or geography column with a spatial index (GiST or SP-GiST). Supports configurable geometry types (Point, Polygon, etc.), SRID, and dimensionality. The graphile-postgis plugin auto-detects geometry/geography columns by codec type for spatial filtering (ST_Contains, ST_DWithin, bbox operators)."},"SearchTrgmParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to create trigram indexes on (fields must already exist on the table)"}},"required":["fields"],"description":"Creates GIN trigram indexes (gin_trgm_ops) on specified text/citext fields for fuzzy LIKE/ILIKE/similarity search. Adds @trgmSearch smart tag for PostGraphile integration. Fields must already exist on the table."},"SearchUnifiedParams":{"type":"object","properties":{"full_text_search":{"type":"object","description":"SearchFullText parameters. Omit to skip FTS setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"weight":{"type":"string","enum":["A","B","C","D"]},"lang":{"type":"string"}},"required":["field"]}},"search_score_weight":{"type":"number","default":1}}},"bm25":{"type":"object","description":"SearchBm25 parameters. Omit to skip BM25 setup.","properties":{"field_name":{"type":"string","format":"column-ref"},"text_config":{"type":"string","default":"english"},"k1":{"type":"number"},"b":{"type":"number"},"search_score_weight":{"type":"number","default":1}}},"embedding":{"type":"object","description":"SearchVector parameters. Omit to skip embedding setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"embedding"},"dimensions":{"type":"integer","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"]},"metric":{"type":"string","enum":["cosine","l2","ip"]},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"}},"embedding_model":{"type":"string","description":"Embedding model identifier. When null, the worker falls back to runtime config."},"embedding_provider":{"type":"string","description":"Embedding provider name. When null, the worker falls back to runtime config."},"search_score_weight":{"type":"number","default":1},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}}},"embedding_text_field":{"type":"string","format":"column-ref","description":"Name of the composite text field created for embedding input","default":"embedding_text"},"composite_format":{"type":"string","enum":["labeled","plain"],"description":"Output format for the composite text field","default":"labeled"},"trgm_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to tag with @trgmSearch for fuzzy/typo-tolerant matching"},"search_config":{"type":"object","description":"Unified search score configuration written to @searchConfig smart tag","properties":{"weights":{"type":"object","description":"Per-algorithm weights: {tsv: 1.5, bm25: 1.0, pgvector: 0.8, trgm: 0.3}"},"normalization":{"type":"string","enum":["linear","sigmoid"],"description":"Score normalization strategy","default":"linear"},"boost_recent":{"type":"boolean","description":"Enable recency boost for search results","default":false},"boost_recency_field":{"type":"string","format":"column-ref","description":"Timestamp field for recency boost (e.g. created_at, updated_at)"},"boost_recency_decay":{"type":"number","description":"Decay rate for recency boost (0-1, lower = faster decay)","default":0.5}}}},"description":"Composite node type that orchestrates multiple search modalities (full-text search, BM25, embeddings, trigram) on a single table. Configures per-table search score weights, normalization strategy, and recency boost via the @searchConfig smart tag."},"SearchVectorParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 384, 768, 1536, 3072)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric (cosine, l2, ip)","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names that feed the embedding. Used by stale trigger to detect content changes."},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"enqueue_job":{"type":"boolean","description":"Auto-create trigger that enqueues embedding generation jobs","default":true},"job_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the job queue. Must match a registered function definition when function_module is installed.","default":"embedding:embed_record"},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue. Must match a registered function definition when function_module is installed.","default":"embedding:chunk_record"}}}},"description":"Adds a vector embedding column with HNSW or IVFFlat index for similarity search. Supports configurable dimensions, distance metrics (cosine, l2, ip), per-field {field_name}_updated_at timestamp tracking (read-only in GraphQL), and automatic job enqueue triggers for embedding generation."},"TableOrganizationSettingsParams":{"type":"object","properties":{},"description":"Creates an organization settings table with standard business fields (legal_name, address fields). Uses AuthzEntityMembership for access control."},"TableUserProfilesParams":{"type":"object","properties":{},"description":"Creates a user profiles table with standard profile fields (profile_picture, bio, first_name, last_name, tags, desired). Uses AuthzDirectOwner for edit access and AuthzAllowAll for select."},"TableUserSettingsParams":{"type":"object","properties":{},"description":"Creates a user settings table for user-specific configuration. Uses AuthzDirectOwner for access control."},"TriggerCondition":{"type":"object","properties":{"field":{"type":"string","description":"Column name (validated against the table)."},"op":{"enum":["=","!=",">","<",">=","<=","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS DISTINCT FROM"],"description":"Comparison operator."},"value":{"description":"Comparison value. Type is resolved from the column definition."},"row":{"enum":["NEW","OLD"],"description":"Row reference (default: NEW)."},"ref":{"type":"object","properties":{"field":{"type":"string"},"row":{"enum":["NEW","OLD"]}},"description":"Column reference for field-to-field comparison (alternative to value)."},"AND":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with AND."},"OR":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with OR."},"NOT":{"$ref":"#/$defs/TriggerCondition","description":"Negated condition."}},"description":"Recursive condition type for compound trigger WHEN clauses. Leaf conditions specify {field, op, value?, row?, ref?}. Combinators nest via AND, OR, NOT."},"shared-001d8d7cd3":{"anyOf":[{"required":["obj_table_id"]},{"required":["obj_schema","obj_table"]}]},"shared-0165627a32":{"type":"array","items":{"type":"string"},"description":"Capability names of any kind (capability, level, ...) merged into the same mask"},"shared-040cc005ef":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/AuthzExpression"}},"shared-0596961db6":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberListParams"}}}},"shared-066977ff2f":{"anyOf":[{"required":["obj_field"]},{"required":["obj_field_id"]}]},"shared-078ee82414":{"properties":{"$type":{"const":"CheckOneOf"}},"required":["$type"]},"shared-0968d06284":{"type":"string","description":"Schema of the join table (or use obj_table_id)"},"shared-0a22d2c3f6":{"type":"string","description":"Single column name for the index."},"shared-11809f0714":{"if":{"properties":{"$type":{"const":"AuthzMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberListParams"}}}},"shared-11a9ffe32a":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"shared-13aff2afe8":{"type":"string","description":"The member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-152f619c56":{"if":{"properties":{"$type":{"const":"AuthzDenyAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDenyAllParams"}}}},"shared-15602a740a":{"properties":{"$type":{"const":"AuthzEntityMembership"}},"required":["$type"]},"shared-1a317ed066":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger."},"shared-1a97ddc6fb":{"if":{"properties":{"$type":{"const":"AuthzRelatedPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"}}}},"shared-1c8d46d43b":{"properties":{"$type":{"const":"CheckNotEqual"}},"required":["$type"]},"shared-1ca2c9bd61":{"type":"array","description":"Join conditions between the protected row and the referenced table","items":{"type":"object","properties":{"local_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table"},"ref_column":{"$ref":"#/$defs/shared-7539b204c0"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"shared-21a1ba9587":{"if":{"properties":{"$type":{"const":"AuthzAppMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMembershipParams"}}}},"shared-22f38cc906":{"type":"array","items":{"type":"string"},"description":"Operator classes for the index columns."},"shared-230094622e":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"obj_field":{"type":"string","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"shared-2997c2f821":{"if":{"properties":{"$type":{"const":"AuthzSystemOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzSystemOnlyParams"}}}},"shared-2a834ba4ff":{"type":"string","description":"Index access method (e.g., \"BTREE\", \"GIN\", \"GIST\", \"HNSW\", \"BM25\")."},"shared-2c17992067":{"properties":{"$type":{"const":"AuthzNotReadOnly"}},"required":["$type"]},"shared-2c20767ba3":{"properties":{"$type":{"const":"CheckGreaterThan"}},"required":["$type"]},"shared-3245b618eb":{"properties":{"$type":{"const":"AuthzValueMatch"}},"required":["$type"]},"shared-33013a269d":{"if":{"properties":{"$type":{"const":"AuthzRelatedEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"}}}},"shared-33af0ede37":{"type":"string","format":"column-ref","description":"Single column to compare against value (mutually exclusive with columns)"},"shared-34021cf1ff":{"properties":{"$type":{"const":"AuthzDirectOwnerAny"}},"required":["$type"]},"shared-36ea8e912e":{"if":{"properties":{"$type":{"const":"AuthzDatabaseClaim"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDatabaseClaimParams"}}}},"shared-39f66ad592":{"if":{"properties":{"$type":{"const":"AuthzAllowAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAllowAllParams"}}}},"shared-3a33134347":{"type":"object","description":"Metadata fields from parent to copy into chunks"},"shared-3d0fa23a34":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"shared-3fc6945ad1":{"if":{"properties":{"$type":{"const":"AuthzValueExists"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueExistsParams"}}}},"shared-411f8ee76d":{"type":"string","description":"Schema of the referenced table (or use ref_table_id)"},"shared-433a283165":{"properties":{"$type":{"const":"AuthzRelatedMemberOwner"}},"required":["$type"]},"shared-462d3d2412":{"type":"string","description":"Name of the related table to look up entity_id from"},"shared-47ab73adbe":{"properties":{"$type":{"const":"AuthzDirectOwner"}},"required":["$type"]},"shared-48649a3a43":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"}},"shared-49ec07b1f5":{"properties":{"$type":{"const":"AuthzAppMemberOwner"}},"required":["$type"]},"shared-4f25156f61":{"if":{"properties":{"$type":{"const":"AuthzPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPeerOwnershipParams"}}}},"shared-5192cb016d":{"properties":{"$type":{"const":"AuthzRelatedPeerOwnership"}},"required":["$type"]},"shared-51c1d9a5f0":{"type":"string","minLength":1,"not":{"const":"app"},"description":"Entity type prefix (e.g. 'org', 'channel', 'department'), resolved to its membership_type; use it instead of membership_type for readability."},"shared-5492e6a87c":{"type":"string","enum":["fulltext","bm25","trigram"]},"shared-55595a36d2":{"type":["array","object"],"items":{"type":"object"},"description":"Optional higher-level condition JSON applied to the referenced table (row alias d)"},"shared-57b27779bd":{"properties":{"$type":{"const":"AuthzValueAllowed"}},"required":["$type"]},"shared-584ca266e8":{"properties":{"$type":{"const":"AuthzRelatedMemberList"}},"required":["$type"]},"shared-5a2832df1c":{"type":"array","items":{"type":"string"},"description":"Array of column names for a multi-column index."},"shared-5e11bfeb01":{"type":"boolean","description":"If true, require is_owner flag on current user membership"},"shared-5f5453df14":{"properties":{"$type":{"const":"AuthzFilePath"}},"required":["$type"]},"shared-626b0c3c0b":{"type":"array","items":{"$ref":"#/$defs/BlueprintFtsSource"},"description":"Source fields that feed into this tsvector."},"shared-637ef72440":{"type":"string","pattern":"^[01]+$","description":"Capability bits a member must hold, as a bit string. Capabilities or levels, when given, replace it."},"shared-6639e33d04":{"if":{"properties":{"$type":{"const":"AuthzComposite"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzCompositeParams"}}}},"shared-698b2fd59a":{"type":"integer","minimum":2,"maximum":2147483647,"description":"The team kind: 2=org, 3+=dynamic entity types."},"shared-6adc1df48e":{"type":"string","description":"Optional schema name for disambiguation (falls back to top-level default)."},"shared-6b829f5502":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"shared-6dbc2f5a83":{"if":{"properties":{"$type":{"const":"AuthzPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPublishableParams"}}}},"shared-6eb30390ff":{"type":"string","enum":["INSERT","DELETE","UPDATE"]},"shared-7539b204c0":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table"},"shared-757c15800e":{"type":"string","description":"Name of the CHECK constraint."},"shared-787b8adf81":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Additional compound conditions beyond auto-generated filtering. Merged with the auto-generated conditions via AND."},"shared-7a53e1103e":{"type":"boolean","description":"Select sel_field from the related row instead of the team id; the platform's own related policies set it with sel_field \"id\"."},"shared-7edb884d72":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from"},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"}},"required":["obj_table","obj_field"]},"shared-7f50b0e5b7":{"type":"string","description":"Name of the referenced table (or use ref_table_id)"},"shared-8358853df2":{"properties":{"$type":{"const":"CheckLessThan"}},"required":["$type"]},"shared-85b2c2543e":{"if":{"properties":{"$type":{"const":"AuthzEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzEntityMembershipParams"}}}},"shared-8763e18b77":{"anyOf":[{"required":["membership_type"]},{"required":["entity_type"]},{"required":["sprt_schema","sprt_table"]}]},"shared-88656ecafa":{"type":"string","format":"column-ref","description":"Column name for conditional WHEN clause (fires only when field equals condition_value)"},"shared-8881b94a41":{"if":{"properties":{"$type":{"const":"AuthzTemporal"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzTemporalParams"}}}},"shared-89ec3722aa":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"}}}},"shared-8cc6b29877":{"type":"string","format":"uuid","description":"UUID of the referenced table (alternative to ref_schema/ref_table)"},"shared-8cef65cfda":{"type":"object","additionalProperties":{"oneOf":[{"type":"string","format":"column-ref"},{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"path":{"type":"array","items":{"type":"string"},"minItems":1}},"required":["field","path"]}]},"description":"Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({\"field\": \"upload\", \"path\": [\"key\"]}). Defaults to the four file columns, or to the file_field document when file_field is set."},"shared-8e6e495eb6":{"if":{"properties":{"$type":{"const":"AuthzNotReadOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzNotReadOnlyParams"}}}},"shared-9146e81ef6":{"type":"string","format":"uuid","description":"UUID of the join table (alternative to obj_schema/obj_table)"},"shared-927486214a":{"type":"boolean","description":"If true, require is_admin flag"},"shared-9572999fa8":{"type":"string","description":"The schema of the member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-97d5c3be03":{"properties":{"$type":{"const":"AuthzOrgHierarchy"}},"required":["$type"]},"shared-9af2f9702a":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'."},"shared-9d6147637c":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id, org_id)"},"shared-a0bfcadf85":{"type":"array","items":{"type":"string"},"description":"Column names that form the unique constraint."},"shared-a2c45e97d1":{"if":{"properties":{"$type":{"const":"AuthzDirectOwnerAny"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"}}}},"shared-a9d73b8ba7":{"if":{"properties":{"$type":{"const":"AuthzMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberOwnerParams"}}}},"shared-ab071ec2f8":{"type":"boolean","description":"If true, require is_owner flag"},"shared-ab15ceab40":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations."},"shared-ac9a0977fa":{"type":"string","description":"Embedding provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"shared-aced6572ca":{"if":{"properties":{"$type":{"const":"AuthzHumanOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzHumanOnlyParams"}}}},"shared-ad437cb66f":{"type":"string","format":"column-ref","x-column-scope":"local"},"shared-ad8f69741a":{"type":"string","description":"Optional schema name override."},"shared-af38a22089":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch"]},"shared-b0876b5627":{"type":"array","items":{"type":"string"},"description":"Achievement level names to require (kind=level catalog rows, merged into the same mask)"},"shared-b1944d8f7b":{"description":"Allowed values as a constant list, or a local column name containing the allowed values","anyOf":[{"type":"string","format":"column-ref","x-column-scope":"local","description":"Local column name containing allowed values"},{"type":"array","items":{"type":["string","boolean","number","null"]},"description":"Constant list of allowed values. Element JSON type is preserved: booleans/numbers emit typed constants (e.g. [true] -> TRUE, [5] -> 5), strings emit text literals."}]},"shared-b1dc7b2e4f":{"properties":{"$type":{"const":"AuthzPeerOwnership"}},"required":["$type"]},"shared-b68f53d1ed":{"type":"integer","description":"The width the mask is padded to; by default the length of the mask."},"shared-bb55f34041":{"type":"boolean","description":"Whether this is a unique index."},"shared-bc381c03de":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{}}},"required":["roles","privileges"]},"shared-c1527c6159":{"if":{"properties":{"$type":{"const":"AuthzValueMatch"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueMatchParams"}}}},"shared-c2c61348f0":{"if":{"properties":{"$type":{"const":"AuthzOrgHierarchy"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzOrgHierarchyParams"}}}},"shared-c5c620bfe3":{"type":"string","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. A zero mask requires nothing."},"shared-c88c54a5c5":{"if":{"properties":{"$type":{"const":"AuthzValueAllowed"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueAllowedParams"}}}},"shared-c893ee8510":{"if":{"properties":{"$type":{"const":"AuthzDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerParams"}}}},"shared-cc52e308f2":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Compound conditions for the trigger WHEN clause. Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema. Cannot be combined with condition_field or watch_fields."},"shared-cd4dc6cdf6":{"type":"string","description":"Name of the join table (or use obj_table_id)"},"shared-d3e6ac0b5d":{"type":"boolean","description":"If true, require is_admin flag on current user membership"},"shared-d4553f7be9":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"},"shared-d85a10e177":{"type":"object","description":"Reference to a table an installed module generated, resolved during blueprint construction (alternative to ref_table_id / ref_schema + ref_table)","properties":{"type":{"type":"string","description":"Module type owning the table, e.g. \"agent\""},"table":{"type":"string","description":"Logical table key within the module, e.g. \"thread\""},"scope":{"type":"string","description":"Scope of the module instance, e.g. \"app\" or \"org\""},"prefix":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations"}},"required":["type","table"]},"shared-d8e76848ea":{"type":"string","format":"uuid","description":"UUID of field on join table (alternative to obj_field)"},"shared-d91c021eee":{"properties":{"$type":{"const":"AuthzMemberOwner"}},"required":["$type"]},"shared-db0e2e6361":{"type":"string","format":"uuid","description":"Table being referenced by the FK"},"shared-dfbaf50fc6":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the join table"},"shared-e1125a4a5e":{"type":"string","description":"Scope of the module instance (e.g. \"app\", \"org\"). Required when the database installs the module at more than one scope."},"shared-e23bde2ba6":{"properties":{"$type":{"const":"AuthzValueExists"}},"required":["$type"]},"shared-e3e4ac8f48":{"if":{"properties":{"$type":{"const":"AuthzFilePath"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzFilePathParams"}}}},"shared-e6dbbbcd8d":{"type":"string","enum":["c","r","n","d","a"],"description":"FK delete action: c=CASCADE, r=RESTRICT, n=SET NULL, d=SET DEFAULT, a=NO ACTION. Required."},"shared-e772a2f2a5":{"type":"object","additionalProperties":{},"description":"Additional index-specific options."},"shared-eb6d498d14":{"if":{"properties":{"$type":{"const":"AuthzAppMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"}}}},"shared-eb860e1011":{"type":"string","enum":["INSERT","UPDATE","DELETE"]},"shared-ee69c55731":{"type":"string","description":"Name of the tsvector field on the table."},"shared-eff5f86cd2":{"properties":{"$type":{"const":"AuthzMemberList"}},"required":["$type"]},"shared-effacc6003":{"type":"object","description":"A further row that must exist in a third table, joined to the referenced row (alias b unless ref_alias says otherwise).","properties":{"ref_table_id":{"type":"string","format":"uuid","description":"UUID of the third table (alternative to ref_schema/ref_table)"},"ref_schema":{"type":"string","description":"Schema of the third table (or use ref_table_id)"},"ref_table":{"type":"string","description":"Name of the third table (or use ref_table_id)"},"ref_alias":{"type":"string","description":"Alias of the third table in the join","default":"b"},"join":{"type":"array","description":"Join conditions between the referenced row and the third table","items":{"type":"object","properties":{"local_column":{"$ref":"#/$defs/shared-7539b204c0"},"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the third table"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"conditions":{"type":["array","object"],"items":{"type":"object"},"description":"Optional condition JSON applied to the third table"}},"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]}],"additionalProperties":false},"shared-f35a015b21":{"type":"string","description":"Optional custom name for the index."},"shared-f4262069e5":{"type":"string","enum":["public","private","temp"]},"shared-f7ad90b1e2":{"type":"string","description":"Value to compare against condition_field in WHEN clause"},"shared-f93f3b8ac9":{"properties":{"$type":{"const":"AuthzRelatedEntityMembership"}},"required":["$type"]},"shared-fe3f452ee5":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For UPDATE triggers, only fire when these fields change (uses DISTINCT FROM)"}}}; +export const blueprintDefinitionJsonSchema: JSONSchema = {"$schema":"http://json-schema.org/draft-07/schema#","title":"BlueprintDefinition","description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint().","allOf":[{"$ref":"#/$defs/BlueprintDefinition"}],"$defs":{"AuthzAllowAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Allows all access. Generates TRUE expression."},"AuthzAppMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must hold an app membership (hardcoded membership_type=1). App-level analog of AuthzMemberOwner for global scopes with no entity key — authorship never survives losing app membership."},"AuthzAppMembershipParams":{"type":"object","properties":{"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":[],"additionalProperties":false,"description":"Checks whether the user is a member of the app. You can also require a specific permission."},"AuthzColumnSecurityParams":{"type":"object","properties":{"columns":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Guarded columns that share the same rule and authorization (e.g. [\"is_shared\"])."},"rule":{"type":"string","enum":["set_true","set_false","set_values","not_values","writable_when","transition","immutable"],"description":"Write pattern that arms the guard: set_true/set_false (column set to that boolean), set_values (column set to one of values), not_values (column set to a non-NULL value outside values), writable_when (column written/changed at all), transition (OLD->NEW pairs in allowed), immutable (delegates to DataImmutableFields).","default":"writable_when"},"authz":{"$ref":"#/$defs/AuthzExpression","description":"An Authz expression (one node such as {\"AuthzAppMembership\": {...}}, or AND, OR or NOT over nodes) that must be satisfied to perform the guarded write. Required for all rules except immutable."},"values":{"type":"array","items":{"type":"string"},"description":"For rule=set_values: the protected values that arm the guard. For rule=not_values: the allowed values; any non-NULL value outside them arms the guard."},"allowed":{"type":"array","items":{"type":"string"},"description":"For rule=transition: allowed guarded transitions expressed as \"from->to\" (e.g. [\"member->admin\"])."},"allow_system":{"type":"boolean","description":"When true, the system role (AuthzSystemOnly) bypasses the guard so provisioning/seed paths without a JWT principal can write freely.","default":false},"error_code":{"type":"string","description":"Machine-readable code prefixed onto the raised error message (e.g. MANAGED_DOMAIN_PUBLISH_FORBIDDEN)."},"error_message":{"type":"string","description":"Human-readable message raised when the guard denies the write."},"conditions":{"type":["object","array"],"items":{"type":"object"},"description":"Conditions on the row being written; the guard arms only when the write matches the rule and the row meets them."}},"required":["columns","rule"],"allOf":[{"if":{"properties":{"rule":{"not":{"const":"immutable"}}}},"then":{"required":["authz"]}},{"if":{"properties":{"rule":{"enum":["set_values","not_values"]}}},"then":{"required":["values"],"properties":{"values":{"minItems":1}}}},{"if":{"properties":{"rule":{"const":"transition"}}},"then":{"required":["allowed"],"properties":{"allowed":{"minItems":1}}}}],"additionalProperties":false,"description":"Column-level write authorization. Generates BEFORE INSERT/UPDATE triggers that enforce an authorization node whenever a guarded column is written to a protected value or transitions. The write-time counterpart to RLS SELECT/WITH CHECK policies: any table can declare \"only an actor satisfying may set column X\". The nested authz value is a normal Authz node compiled by the standard RLS pipeline; row-referencing nodes have their protected-table column references rebound to NEW. The immutable rule delegates to the native DataImmutableFields generator."},"AuthzCompositeParams":{"$ref":"#/$defs/AuthzExpression","description":"Composite authorization policy that combines multiple authorization nodes using boolean logic (AND/OR). The data field contains a JSONB AST with nested authorization nodes."},"AuthzDatabaseClaimParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column carrying the row's database id","default":"database_id"},"schema_id":{"type":"string","format":"uuid","description":"A schema whose database must be the claimed one, in place of a column; the rule then reads no column."},"lane_attested":{"type":"boolean","description":"Only connections the platform attests for the claimed database pass.","default":false}},"additionalProperties":false,"description":"Passes when the row's database column equals the session's pinned database claim (jwt.claims.database_id). Consults no principal, membership or entity, so it admits a connection whose identity the platform sets — such as a cloud function's database connection, whose claim comes from the connection and cannot widen it — to exactly the database that connection is bound to. A session with no claim fails loudly rather than reading nothing."},"AuthzDenyAllParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Denies all access. Generates FALSE expression."},"AuthzDirectOwnerAnyParams":{"type":"object","properties":{"entity_fields":{"type":"array","items":{"$ref":"#/$defs/shared-ad437cb66f"},"minItems":1,"description":"Array of column names to check for ownership"}},"required":["entity_fields"],"additionalProperties":false,"description":"OR logic for multiple ownership fields. Checks if current user matches any of the specified fields."},"AuthzDirectOwnerParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)"}},"required":["entity_field"],"additionalProperties":false,"description":"Direct equality comparison between a table column and the current user ID. Simplest authorization pattern with no subqueries."},"AuthzEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"mask_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capabilities — both checks must pass."},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"},"check_function_name":{"type":"string","description":"A function that checks the membership instead of the member list; it is called with the row's team column."},"check_function_schema":{"type":"string","description":"The schema of that function."}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Checks whether the user belongs to the organization or group linked to this record."},"AuthzExpression":{"type":"object","description":"One Authz node as {\"AuthzEntityMembership\": {...}}, or AND or OR with a list of expressions, or NOT with one expression.","minProperties":1,"maxProperties":1,"properties":{"AND":{"$ref":"#/$defs/shared-040cc005ef"},"OR":{"$ref":"#/$defs/shared-040cc005ef"},"NOT":{"$ref":"#/$defs/AuthzExpression"},"AuthzAllowAll":{"$ref":"#/$defs/AuthzAllowAllParams"},"AuthzAppMemberOwner":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"},"AuthzAppMembership":{"$ref":"#/$defs/AuthzAppMembershipParams"},"AuthzDatabaseClaim":{"$ref":"#/$defs/AuthzDatabaseClaimParams"},"AuthzDenyAll":{"$ref":"#/$defs/AuthzDenyAllParams"},"AuthzDirectOwner":{"$ref":"#/$defs/AuthzDirectOwnerParams"},"AuthzDirectOwnerAny":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"},"AuthzEntityMembership":{"$ref":"#/$defs/AuthzEntityMembershipParams"},"AuthzFilePath":{"$ref":"#/$defs/AuthzFilePathParams"},"AuthzHumanOnly":{"$ref":"#/$defs/AuthzHumanOnlyParams"},"AuthzMemberList":{"$ref":"#/$defs/AuthzMemberListParams"},"AuthzMemberOwner":{"$ref":"#/$defs/AuthzMemberOwnerParams"},"AuthzOrgHierarchy":{"$ref":"#/$defs/AuthzOrgHierarchyParams"},"AuthzPeerOwnership":{"$ref":"#/$defs/AuthzPeerOwnershipParams"},"AuthzPublishable":{"$ref":"#/$defs/AuthzPublishableParams"},"AuthzRelatedEntityMembership":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"},"AuthzRelatedMemberList":{"$ref":"#/$defs/AuthzRelatedMemberListParams"},"AuthzRelatedMemberOwner":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"},"AuthzRelatedPeerOwnership":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"},"AuthzSystemOnly":{"$ref":"#/$defs/AuthzSystemOnlyParams"},"AuthzTemporal":{"$ref":"#/$defs/AuthzTemporalParams"},"AuthzValueAllowed":{"$ref":"#/$defs/AuthzValueAllowedParams"},"AuthzValueExists":{"$ref":"#/$defs/AuthzValueExistsParams"},"AuthzValueMatch":{"$ref":"#/$defs/AuthzValueMatchParams"}},"additionalProperties":false},"AuthzFilePathParams":{"type":"object","properties":{"shares_table_id":{"type":"string","format":"uuid","description":"UUID of the path_shares table (alternative to shares_schema/shares_table)"},"shares_schema":{"type":"string","description":"Schema of the path_shares table (or use shares_table_id)"},"shares_table":{"type":"string","description":"Name of the path_shares table (or use shares_table_id)"},"files_table_id":{"type":"string","format":"uuid","description":"UUID of the files table (alternative to files_schema/files_table)"},"files_schema":{"type":"string","description":"Schema of the files table (or use files_table_id)"},"files_table":{"type":"string","description":"Name of the files table (or use files_table_id)"},"capability_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Boolean column on the path_shares table that grants the required permission (e.g. can_read, can_write)"},"bucket_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the files table referencing the bucket","default":"bucket_id"},"path_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Ltree column on the files table representing the file path","default":"path"}},"required":["capability_field"],"allOf":[{"anyOf":[{"required":["shares_table_id"]},{"required":["shares_schema","shares_table"]}]},{"anyOf":[{"required":["files_table_id"]},{"required":["files_schema","files_table"]}]}],"additionalProperties":false,"description":"Path-scoped file sharing via ltree containment. Grants access when a path_shares row matches the current user, bucket, and an ancestor path with the required permission."},"AuthzHumanOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Passes only for human sessions: compares the session's principal claim to its user claim, so service principals (API keys, agents) are excluded. Typically applied as a restrictive policy alongside a permissive membership policy."},"AuthzMemberListParams":{"type":"object","properties":{"array_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the array of user IDs"}},"required":["array_field"],"additionalProperties":false,"description":"Check if current user is in an array column on the same row."},"AuthzMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., owner_id)","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id)","default":"entity_id"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Compound policy: the row must be owned by the current user (owner_field = current_user_id) AND the current user must be a member of the entity referenced by entity_field. Combines direct ownership with entity membership — the actor can only access rows they own within entities they belong to."},"AuthzNotReadOnlyParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-9d6147637c"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Blocks changes by users marked read-only in the member list. Pair it with AuthzEntityMembership to check that the user is a member in the first place."},"AuthzOrgHierarchyParams":{"type":"object","properties":{"direction":{"type":"string","enum":["up","down"],"description":"down=manager sees subordinates, up=subordinate sees managers"},"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the org entity","default":"entity_id"},"anchor_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Field referencing the user (e.g., owner_id)"},"max_depth":{"type":"integer","description":"Optional max depth to limit visibility"}},"required":["direction","anchor_field"],"additionalProperties":false,"description":"Organizational hierarchy visibility using closure table. Managers can see subordinate data or subordinates can see manager data."},"AuthzPeerOwnershipParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the owning user (e.g., owner_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"}],"additionalProperties":false,"description":"Peer visibility through shared entity membership. Authorizes access to user-owned rows when the owner and current user are both members of the same entity."},"AuthzPublishableParams":{"type":"object","properties":{"is_published_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Boolean field indicating published state","default":"is_published"},"published_at_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Timestamp field for publish time","default":"published_at"},"require_published_at":{"type":"boolean","description":"Require published_at to be non-null and <= now()","default":true}},"additionalProperties":false,"description":"Published state access control. Restricts access to records that are published."},"AuthzRelatedEntityMembershipParams":{"type":"object","properties":{"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Choose the column on the linked table that identifies the organization, group, or other membership target."},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Checks membership through a linked table, such as whether the user belongs to the organization linked there."},"AuthzRelatedMemberListParams":{"type":"object","properties":{"owned_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to owned_schema/owned_table)"},"owned_schema":{"type":"string","description":"Schema of the related table (or use owned_table_id)"},"owned_table":{"type":"string","description":"Name of the related table (or use owned_table_id)"},"owned_table_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Array column in related table"},"owned_table_ref_key":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"FK column in related table"},"this_object_key":{"type":"string","format":"column-ref","x-column-scope":"local","description":"PK column in protected table"}},"required":["owned_table_key","owned_table_ref_key","this_object_key"],"anyOf":[{"required":["owned_table_id"]},{"required":["owned_schema","owned_table"]}],"additionalProperties":false,"description":"Array membership check in a related table."},"AuthzRelatedMemberOwnerParams":{"type":"object","properties":{"owner_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name containing the owner user ID (e.g., actor_id)","default":"owner_id"},"entity_field":{"$ref":"#/$defs/shared-dfbaf50fc6"},"sel_field":{"type":"string","description":"Member list column to use for the entity match","default":"entity_id"},"sprt_join_field":{"type":"string","description":"Member list column to match to the related table","default":"entity_id"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"$ref":"#/$defs/shared-9146e81ef6"},"obj_schema":{"$ref":"#/$defs/shared-0968d06284"},"obj_table":{"$ref":"#/$defs/shared-cd4dc6cdf6"},"obj_field_id":{"$ref":"#/$defs/shared-d8e76848ea"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the related table to match to the entity ID in the member list"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-927486214a"},"is_owner":{"$ref":"#/$defs/shared-ab071ec2f8"},"sel_obj":{"$ref":"#/$defs/shared-7a53e1103e"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["owner_field","entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access only when the current user owns the row and belongs to the entity referenced by a related row. If the user loses membership, owning the row no longer gives them access."},"AuthzRelatedPeerOwnershipParams":{"type":"object","properties":{"entity_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the related table (e.g., message_id)"},"membership_type":{"$ref":"#/$defs/shared-698b2fd59a"},"entity_type":{"$ref":"#/$defs/shared-51c1d9a5f0"},"obj_table_id":{"type":"string","format":"uuid","description":"UUID of the related table (alternative to obj_schema/obj_table)"},"obj_schema":{"type":"string","description":"Schema of the related table (or use obj_table_id)"},"obj_table":{"type":"string","description":"Name of the related table (or use obj_table_id)"},"obj_field_id":{"type":"string","format":"uuid","description":"UUID of field on related table containing the owner user ID (alternative to obj_field)"},"obj_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field name on related table containing the owner user ID (e.g., sender_id)"},"obj_ref_field":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Field on related table to select for matching entity_field","default":"id"},"levels":{"$ref":"#/$defs/shared-b0876b5627"},"capabilities":{"$ref":"#/$defs/shared-0165627a32"},"is_admin":{"$ref":"#/$defs/shared-d3e6ac0b5d"},"is_owner":{"$ref":"#/$defs/shared-5e11bfeb01"},"mask_column":{"$ref":"#/$defs/shared-c5c620bfe3"},"sprt_schema":{"$ref":"#/$defs/shared-9572999fa8"},"sprt_table":{"$ref":"#/$defs/shared-13aff2afe8"},"mask":{"$ref":"#/$defs/shared-637ef72440"},"bitlen":{"$ref":"#/$defs/shared-b68f53d1ed"}},"required":["entity_field"],"allOf":[{"$ref":"#/$defs/shared-8763e18b77"},{"$ref":"#/$defs/shared-066977ff2f"},{"$ref":"#/$defs/shared-001d8d7cd3"}],"additionalProperties":false,"description":"Allows access when the current user and the owner are members of the same entity. Unlike AuthzPeerOwnership, it looks up the owner on a related row."},"AuthzSystemOnlyParams":{"type":"object","properties":{},"additionalProperties":false,"description":"Restricts access to system-initiated operations (triggers, background jobs). Checks jwt.claims.role_type = \"system\". Normal API requests default to \"user\" and are denied. Use for INSERT policies on append-only event/audit/usage tables."},"AuthzTemporalParams":{"type":"object","properties":{"valid_from_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for start time (at least one of valid_from_field or valid_until_field required)"},"valid_until_field":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column for end time (at least one of valid_from_field or valid_until_field required)"},"valid_from_inclusive":{"type":"boolean","description":"Include start boundary","default":true},"valid_until_inclusive":{"type":"boolean","description":"Include end boundary","default":false}},"anyOf":[{"required":["valid_from_field"]},{"required":["valid_until_field"]}],"additionalProperties":false,"description":"Time-window based access control. Restricts access based on valid_from and/or valid_until timestamps. At least one of valid_from_field or valid_until_field must be provided."},"AuthzValueAllowedParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table to check"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the value check"}},"required":["column","allowed","operator"],"additionalProperties":false,"description":"Check the protected row's own column against an allowed set of values."},"AuthzValueExistsParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-6ea79cf84b"},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with optional additional conditions."},"AuthzValueMatchParams":{"type":"object","properties":{"ref_table_id":{"$ref":"#/$defs/shared-8cc6b29877"},"ref_schema":{"$ref":"#/$defs/shared-411f8ee76d"},"ref_table":{"$ref":"#/$defs/shared-7f50b0e5b7"},"ref_module":{"$ref":"#/$defs/shared-d85a10e177"},"join":{"$ref":"#/$defs/shared-6ea79cf84b"},"match":{"type":"object","description":"Value match on a referenced column","properties":{"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table to match"},"allowed":{"$ref":"#/$defs/shared-b1944d8f7b"},"operator":{"type":"string","enum":["in","any","overlap","contains","contained"],"description":"Operator to use for the match"}},"required":["ref_column","allowed","operator"],"additionalProperties":false},"conditions":{"$ref":"#/$defs/shared-55595a36d2"},"exists":{"$ref":"#/$defs/shared-effacc6003"}},"required":["match","join"],"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]},{"required":["ref_module"]}],"additionalProperties":false,"description":"EXISTS check in a referenced table joined by a local column, with a value/array match on a referenced column and optional additional conditions."},"BlueprintAchievement":{"type":"object","properties":{"name":{"type":"string","description":"Unique name for the achievement level."},"description":{"type":"string","description":"Human-readable description of this achievement."},"priority":{"type":"number","description":"Display ordering priority; lower values appear first. Defaults to 100."},"requirements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementRequirement"},"description":"Requirements that must be met to earn this achievement."},"rewards":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievementReward"},"description":"Rewards granted when the achievement is earned."},"entity_prefix":{"type":"string","description":"Entity prefix to scope this achievement to (e.g., \"org\", \"app\"). Used to resolve the correct events_module. Defaults to \"app\"."}},"required":["name","requirements"],"description":"An achievement entry for the blueprint achievements[] section. Creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"BlueprintAchievementRequirement":{"type":"object","properties":{"event_name":{"type":"string","description":"Name identifier matching an event_type or step name."},"count":{"type":"number","description":"Number of events needed to satisfy this requirement."},"description":{"type":"string","description":"Human-readable description of what this requirement entails."}},"required":["event_name","count"],"description":"A requirement entry within a blueprint achievement. Defines what events must occur to earn the achievement."},"BlueprintAchievementReward":{"type":"object","properties":{"reward_type":{"enum":["limit_credit","meter_credit"],"description":"Type of reward: limit_credit (grants limit credits) or meter_credit (grants meter credits)."},"target_name":{"type":"string","description":"Target limit name or meter slug for the credit grant."},"amount":{"type":"number","description":"Number of credits to grant."},"credit_type":{"type":"string","description":"Credit type: permanent, expiring, etc. Defaults to \"permanent\"."}},"required":["reward_type","target_name","amount"],"description":"A reward entry within a blueprint achievement. Defines credits granted when the achievement is earned."},"BlueprintAgentConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Agent scope. \"app\" (default) creates app-level agent tables (membership_type = NULL). \"org\" creates per-org agent tables. Only used at the top level of a blueprint definition — entity-scoped agents inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module agents. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_agent_thread."},"api_name":{"type":"string","description":"API name for the agent module. Used in GraphQL naming. Defaults to \"agent\"."},"has_plans":{"type":"boolean","description":"Whether to provision the agent_plan table for workflow plans with ordered tasks and approval gates. When true, tasks belong to plans (plan_id NOT NULL) instead of directly to threads. Defaults to false."},"has_resources":{"type":"boolean","description":"Whether to provision the unified agent_resource table (skills + knowledge with slug, kind, search, embedding). Standalone flag — also auto-enabled by has_agents. Defaults to false."},"has_agents":{"type":"boolean","description":"Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false."},"has_repository_resources":{"type":"boolean","description":"Whether to attach resources to the repositories they apply to, through an agent_resource_repository junction (resource_id, repository_id, priority). Requires resources and a repository module at this same scope — with no repository catalog to point at, the junction is not created. Defaults to false."},"has_runs":{"type":"boolean","description":"Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false."},"resources":{"type":"array","items":{"type":"object","properties":{"dimensions":{"type":"number"},"chunk_size":{"type":"number"},"chunk_overlap":{"type":"number"},"chunk_strategy":{"enum":["paragraph","sentence","token"]},"embedding_model":{"type":"string"},"embedding_provider":{"type":"string"},"search_indexes":{"type":"array","items":{"type":"string"}}}},"description":"Resource configuration array. First element configures the agent_resource table: vector dimensions (default 768), chunk_size (default 1000), chunk_strategy (default \"paragraph\"), chunk_overlap (default 200), embedding_model, embedding_provider, search_indexes (default [\"bm25\"])."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the agent tables. NULL = apply defaults from apply_agent_security()."},"provisions":{"type":"object","properties":{"thread":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"message":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"task":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"prompt":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"plan":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"resource":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"agent":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"persona":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"run":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"event":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"workspace":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for agent tables. Each key targets a specific table (thread, message, task, prompt, plan, resource, agent, persona, run, event, workspace) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision. Overriding `event` replaces the append-only default, so a grant list there can make the transcript mutable; overriding `workspace` replaces its no-delete default."}},"description":"Agent module configuration. When used at the top level of a blueprint, the scope field controls whether agents are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions thread, message, task, prompt tables. has_resources adds unified agent_resource (skills + knowledge). has_agents adds agent registry + personas (implies has_resources)."},"BlueprintBucketSeed":{"type":"object","properties":{"name":{"type":"string","description":"Bucket key name (e.g., \"avatars\", \"documents\"). Becomes the key column value."},"description":{"type":"string","description":"Human-readable description of this bucket."},"type":{"enum":["public","private","temp"],"description":"Bucket access type. Defaults to public when is_public is true and private otherwise."},"is_public":{"type":"boolean","description":"Whether the bucket is publicly readable. Must agree with type when both are supplied."},"destination":{"type":"string","description":"Destination bucket key for a temporary bucket."},"staging_ttl":{"type":"string","description":"Maximum staging time for a temporary bucket as a PostgreSQL interval."},"allowed_mime_types":{"type":"array","items":{"type":"string"},"description":"MIME type allowlist (e.g., [\"image/png\", \"image/jpeg\"]). NULL means all types allowed."},"max_file_size":{"type":"number","description":"Maximum file size in bytes for this bucket. NULL means no limit."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for this bucket."}},"required":["name"],"description":"A bucket seed entry for storage.buckets[]. Creates an initial bucket row in the {prefix}_buckets table during entity type provisioning. Only used for app-level storage (not entity-scoped)."},"BlueprintCheckConstraint":{"allOf":[{"$ref":"#/$defs/BlueprintTableCheckConstraint"},{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this CHECK constraint belongs to."}},"required":["table_name"]}],"description":"A CHECK constraint definition within a blueprint (top-level, requires table_name)."},"BlueprintDefinition":{"type":"object","properties":{"tables":{"type":"array","items":{"$ref":"#/$defs/BlueprintTable"},"description":"Tables to create."},"relations":{"type":"array","items":{"$ref":"#/$defs/BlueprintRelation"},"description":"Relations between tables."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintIndex"},"description":"Indexes on table columns."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintFullTextSearch"},"description":"Full-text search configurations."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintUniqueConstraint"},"description":"Unique constraints on table columns."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintCheckConstraint"},"description":"CHECK constraints on table columns."},"entity_types":{"type":"array","items":{"$ref":"#/$defs/BlueprintEntityType"},"description":"Entity types to provision in Phase 0 (before tables). Each entry creates an entity table with membership modules and security."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Top-level storage configuration array. Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates storage_module with membership_type = NULL. Org-scoped creates per-org/user storage with owner_id and AFTER INSERT bucket seeding. When infra is installed, a private \"functions\" bucket is auto-injected into org-scoped entries. For child entity type storage, use entity_types[].storage instead."},"achievements":{"type":"array","items":{"$ref":"#/$defs/BlueprintAchievement"},"description":"Achievement definitions. Each entry creates a level with requirements and optional rewards in the events_module. Requires events_module to be provisioned (e.g., via entity_types[].has_levels = true or modules includes events_module)."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Top-level namespace configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates namespace_module with membership_type = NULL. Org-scoped creates per-org namespaces. For entity-scoped namespaces, use entity_types[].namespaces instead."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Top-level function configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates function_module with membership_type = NULL. Org-scoped creates per-org functions. For entity-scoped functions, use entity_types[].functions instead."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Top-level agent configuration array (Phase 0.6). Each entry has an optional scope (\"app\" or \"org\"). App-scoped (default) creates agent_module with membership_type = NULL. Org-scoped creates per-org agents. For entity-scoped agents, use entity_types[].agents instead."}},"required":["tables"],"description":"The complete blueprint definition -- the JSONB shape accepted by construct_blueprint()."},"BlueprintEntityTableProvision":{"type":"object","properties":{"use_rls":{"type":"boolean","description":"Whether to enable RLS on the entity table. Forwarded to secure_table_provision. Defaults to true."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Node objects applied to the entity table for field creation (e.g., DataTimestamps, DataPeoplestamps). Forwarded to secure_table_provision as-is."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the entity table. Forwarded to secure_table_provision as-is."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects for the entity table. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples. Forwarded to secure_table_provision as-is. Defaults to []."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for the entity table. When present, these policies fully replace the five default entity-table policies (is_visible becomes a no-op)."}},"description":"Override object for the entity table created by a BlueprintEntityType. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, policies[] replaces the default entity-table policies entirely."},"BlueprintEntityType":{"type":"object","properties":{"name":{"type":"string","description":"Entity type name (e.g., \"data_room\", \"channel\", \"department\"). Required when creating a new entity type. Omit when extending an existing entity type (e.g., prefix: \"org\") — the entry will add storage/config to the existing type without creating a new one."},"prefix":{"type":"string","description":"Short prefix for generated objects (e.g., \"dr\", \"ch\", \"dept\"). Used in table/trigger naming."},"description":{"type":"string","description":"Human-readable description of this entity type."},"parent_entity":{"type":"string","description":"Parent entity type name. Defaults to \"org\"."},"table_name":{"type":"string","description":"Custom table name for the entity table. Defaults to name-derived convention."},"is_visible":{"type":"boolean","description":"Whether parent-entity members can see child entities via the default parent_member SELECT policy. Gates one of the five default policies. No-op when table_provision is supplied. Defaults to true."},"has_limits":{"type":"boolean","description":"Whether to provision a limits module for this entity type. Defaults to false."},"has_profiles":{"type":"boolean","description":"Whether to provision a profiles module for this entity type. Defaults to false. A membership may hold any number of profiles: the {prefix}_membership_profiles assignment table holds every profile it holds and the membership mask is granted | bit_or(held profile masks)."},"has_levels":{"type":"boolean","description":"Whether to provision a levels module for this entity type. Defaults to false."},"has_invites":{"type":"boolean","description":"Whether to provision entity-scoped invite tables ({prefix}_invites, {prefix}_claimed_invites) and a submit_{prefix}_invite_code() function. Defaults to false."},"has_invite_achievements":{"type":"boolean","description":"Whether to auto-attach an EventTracker to the claimed_invites table for invite-based achievements. Requires has_invites=true AND has_levels=true. When true, records 'invite_claimed' events credited to the sender (inviter) on each claimed invite. Defaults to false."},"skip_entity_policies":{"type":"boolean","description":"Escape hatch: when true AND table_provision is NULL, zero policies are provisioned on the entity table. Defaults to false."},"table_provision":{"$ref":"#/$defs/BlueprintEntityTableProvision","description":"Override for the entity table. Shape mirrors BlueprintTable / secure_table_provision vocabulary. When supplied, its policies[] replaces the five default entity-table policies; is_visible becomes a no-op. When NULL (default), the five default policies are applied (gated by is_visible)."},"storage":{"type":"array","items":{"$ref":"#/$defs/BlueprintStorageConfig"},"description":"Storage module configuration array. Presence triggers provisioning (same inference model as namespaces, functions, agents). Each entry provisions a separate storage module with its own tables, RLS, and settings. Each entry may specify a key for multi-module support (defaults to \"default\")."},"namespaces":{"type":"array","items":{"$ref":"#/$defs/BlueprintNamespaceConfig"},"description":"Namespace module configuration array. Presence triggers provisioning. Each entry provisions a namespace_module with its own tables, computed-name proxy, and entity-scoped RLS. Registers manage_namespaces capability bit. \"[{}]\" = provision one default namespace module."},"functions":{"type":"array","items":{"$ref":"#/$defs/BlueprintFunctionConfig"},"description":"Function module configuration array. Presence triggers provisioning. Each entry provisions function_definitions, function_invocations (partitioned), and function_execution_logs tables. Registers manage_functions + invoke_functions capability bits. \"[{}]\" = provision one default function module."},"agents":{"type":"array","items":{"$ref":"#/$defs/BlueprintAgentConfig"},"description":"Agent module configuration array. Presence triggers provisioning. Each entry provisions thread, message, task, prompt tables (and optionally knowledge with vector embeddings). \"[{}]\" = provision one default agent module."},"graphs":{"type":"array","items":{"$ref":"#/$defs/BlueprintGraphConfig"},"description":"Graph module configuration array. Presence triggers capability registration (manage_graphs, execute_graphs). Graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here. \"[{}]\" = register default graph capabilities."}},"required":["prefix"],"description":"An entity type entry for Phase 0 of construct_blueprint(). When name is provided, provisions a new entity type with its own entity table, membership modules, and security policies via entity_type_provision. When name is omitted and only prefix is given, extends an existing entity type (e.g., the built-in \"org\") with additional capabilities like storage — without creating a new entity type."},"BlueprintField":{"type":"object","properties":{"name":{"type":"string","description":"The column name."},"type":{"$ref":"#/$defs/FieldType","description":"The structured PostgreSQL type (e.g., { name: \"text\" })."},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint."},"default":{"$ref":"#/$defs/FieldDefault","description":"The structured default (e.g., { value: \"pending\" })."},"min":{"type":"number"},"max":{"type":"number"},"regexp":{"type":"string"},"index":{"enum":["btree","gin","gist","brin","hash"]},"description":{"type":"string","description":"Comment/description for this field."},"processing":{"anyOf":[{"const":false},{"$ref":"#/$defs/BlueprintFieldProcessing"}],"description":"Upload and image fields only. The processing lanes that run on the field's files. Omitted, an image field newly added by the blueprint renders the default versions and nothing else runs; false runs nothing."}},"required":["name","type"],"description":"A custom field (column) to add to a blueprint table."},"BlueprintFieldProcessing":{"type":"object","properties":{"versions":{"anyOf":[{"type":"boolean"},{"$ref":"#/$defs/shared-1232a5e8ca"},{"type":"object","properties":{"versions":{"$ref":"#/$defs/shared-1232a5e8ca"},"versions_field":{"type":"string","format":"column-ref","description":"Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document.","default":"image_versions"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image processing worker","default":"image:process_image_versions"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for image processing tasks","default":"image_processing"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}}}],"description":"Image fields. Resized versions of the image, written into the image document as `versions`. On by default with the default set of sizes; a list states the versions instead, an object any ProcessImageVersions parameter, false turns it off."},"embedding":{"anyOf":[{"type":"boolean"},{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (default 512 for CLIP-style image embeddings)","default":512},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-0d918e14b9"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image embedding worker. The payload is the file row (file_id, key, mime_type, bucket_id), so the task must be a record worker that reads the object itself — not embedding:process_image_embedding, which embeds an image_url it is handed.","default":"embedding:process_file_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"}}},{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 512 for CLIP, 768 for nomic, 1536 for ada-002)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-c9b32dbf00"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"$ref":"#/$defs/shared-cf7316ac6e"},"task_identifier":{"$ref":"#/$defs/shared-f90494132b"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"source_bucket":{"$ref":"#/$defs/shared-41591dfcf8"},"variants_bucket":{"$ref":"#/$defs/shared-8aa6c03738"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"$ref":"#/$defs/shared-a0d2b7ccf1"},"include_chunks":{"$ref":"#/$defs/shared-347ff05f99"},"chunks":{"type":"object","description":"Chunking configuration passed through to ProcessChunks. When include_chunks is true (or defaults to true in extract mode), these params configure the chunks table, embedding dimensions, strategy, etc.","default":{},"properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"metadata_fields":{"$ref":"#/$defs/shared-6119be8d95"},"search_indexes":{"$ref":"#/$defs/shared-0ed784651d"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}}}],"description":"Image and upload fields. A vector embedding of the file. Off by default; true takes the node defaults, an object any ProcessImageEmbedding (image) or ProcessFileEmbedding (upload) parameter. The vector column is `_embedding` unless `field_name` names it."},"extraction":{"anyOf":[{"type":"boolean"},{"type":"object","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"extraction_model":{"$ref":"#/$defs/shared-f862b57bdc"},"extraction_provider":{"$ref":"#/$defs/shared-82428b2411"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%'].","default":["application/pdf","text/%"]},"routes":{"$ref":"#/$defs/shared-9649b5119d"},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the extraction worker","default":"document:extract_file_text"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for extraction tasks","default":"extraction"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}}}],"description":"Upload fields. Text and metadata extracted from the file. Off by default; true takes the node defaults, an object any ProcessExtraction parameter. The columns are `_text` and `_metadata` unless `text_field` / `metadata_field` name them."}},"description":"What runs on the files of an upload or image field. Each key is a lane and provisions the same node an entry in nodes[] would, with file_field filled in; naming the field in such a node instead leaves that lane to the node."},"BlueprintFtsSource":{"type":"object","properties":{"field":{"type":"string","description":"Column name of the source field."},"weight":{"type":"string","description":"TSVector weight: \"A\", \"B\", \"C\", or \"D\"."},"lang":{"type":"string","description":"Language for text search. Defaults to \"english\"."}},"required":["field","weight"],"description":"A source field contributing to a full-text search tsvector column."},"BlueprintFullTextSearch":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this full-text search belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"}},"required":["table_name","field","sources"],"description":"A full-text search configuration for a blueprint table (top-level, requires table_name)."},"BlueprintFunctionConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Function scope. \"app\" (default) creates app-level functions (membership_type = NULL). \"org\" creates per-org functions. Only used at the top level of a blueprint definition — entity-scoped functions inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module functions. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_function_definitions."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the function tables. NULL = apply defaults from apply_function_security()."},"provisions":{"type":"object","properties":{"definitions":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"invocations":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"execution_logs":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for function tables. Each key targets a specific table (definitions, invocations, execution_logs) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Function module configuration. When used at the top level of a blueprint, the scope field controls whether functions are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions function_definitions, function_invocations (partitioned, 12-month retention), and function_execution_logs tables."},"BlueprintGraphConfig":{"type":"object","properties":{"key":{"type":"string","description":"Module discriminator for multi-module graphs. Defaults to \"default\"."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the graph tables. NULL = apply defaults from apply_graph_security()."}},"description":"Graph module configuration. Presence triggers capability registration (manage_graphs, execute_graphs). The graph module requires a merkle_store_module_id dependency, so entity_type_provision only registers capabilities here — the graph module itself must be provisioned separately."},"BlueprintIndex":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this index belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"}},"required":["table_name","access_method"],"description":"An index definition within a blueprint (top-level, requires table_name)."},"BlueprintModuleInstallRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type of the install, e.g. \"image\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type"],"description":"A reference to an installed module, naming no table of its own. Used by a table entry whose provisions map supplies the table keys."},"BlueprintModuleTableRef":{"type":"object","properties":{"type":{"type":"string","description":"Module type owning the table. Currently \"agent\"."},"table":{"type":"string","description":"Logical table key within the module, not a table name. Agent: \"thread\", \"message\", \"task\", \"prompt\", \"plan\", \"agent\", \"persona\", \"resource\"."},"scope":{"$ref":"#/$defs/shared-e1125a4a5e"},"prefix":{"$ref":"#/$defs/shared-ab15ceab40"}},"required":["type","table"],"description":"A reference from a blueprint table entry to a table generated by an installed module. Resolved through the module row's recorded table ids; a reference that matches no module instance or no provisioned table fails construction rather than creating a table."},"BlueprintNamespaceConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Namespace scope. \"app\" (default) creates app-level namespaces (membership_type = NULL). \"org\" creates per-org namespaces. Only used at the top level of a blueprint definition — entity-scoped namespaces inherit scope from the entity type."},"key":{"type":"string","description":"Module discriminator for multi-module namespaces. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_namespaces."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policy overrides for the namespaces table. NULL = apply defaults from apply_namespace_security()."},"provisions":{"type":"object","properties":{"namespaces":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"namespace_events":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for namespace tables. Each key targets a specific table (namespaces, namespace_events) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision."}},"description":"Namespace module configuration. When used at the top level of a blueprint, the scope field controls whether namespaces are app-level (\"app\", default) or org-level (\"org\"). When used inside entity_types[], scope is inherited from the entity type. Provisions a namespaces table with computed-name proxy, rename trigger, and entity-scoped RLS."},"BlueprintNode":{"anyOf":[{"$ref":"#/$defs/BlueprintNodeShorthand"},{"$ref":"#/$defs/BlueprintNodeObject"}],"description":"A node entry in a blueprint table. Either a string shorthand or a typed object."},"BlueprintNodeObject":{"type":"object","properties":{"data":{"type":"object"},"$type":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzColumnSecurity","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch","CheckGreaterThan","CheckLessThan","CheckNotEqual","CheckOneOf","CheckOwnedRelation","DataArchivable","DataBulk","DataCapabilities","DataCompositeField","DataDenormalized","DataDirectOwner","DataEntityMembership","DataFileRef","DataForceCurrentUser","DataGenerated","DataHistory","DataI18n","DataId","DataIdentity","DataImmutableFields","DataInflection","DataInheritFromParent","DataJsonb","DataLock","DataMemberOwner","DataOwnedFields","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchBm25","SearchFullText","SearchSpatial","SearchSpatialAggregate","SearchTrgm","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","EventReferral","EventTracker","GuardStepUp","JobTrigger","LimitEnforceAggregate","LimitEnforceCounter","LimitEnforceFeature","LimitEnforceRate","LimitTrackUsage","LimitWarningAggregate","LimitWarningCounter","LimitWarningRate","ProcessChunks","ProcessCustom","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"]}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"if":{"properties":{"$type":{"const":"AuthzColumnSecurity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzColumnSecurityParams"}},"required":["data"]}},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-6ac44ac2ba"},{"$ref":"#/$defs/shared-0379afb669"},{"$ref":"#/$defs/shared-ca5d04c28d"},{"$ref":"#/$defs/shared-ff315e2ff3"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-5a2b860e32"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-1afc3ee393"},{"$ref":"#/$defs/shared-968a890679"},{"$ref":"#/$defs/shared-35954fc61d"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-7756a0ed5a"},{"$ref":"#/$defs/shared-a5a04dd84a"},{"$ref":"#/$defs/shared-f5f12fa8f6"},{"$ref":"#/$defs/shared-b297346d46"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-0022037ad5"},{"$ref":"#/$defs/shared-1d336e787f"},{"$ref":"#/$defs/shared-693097b0e5"},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckGreaterThanParams"}}}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckLessThanParams"}}}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckNotEqualParams"}},"required":["data"]}},{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOneOfParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"CheckOwnedRelation"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/CheckOwnedRelationParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataArchivable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataArchivableParams"}}}},{"if":{"properties":{"$type":{"const":"DataBulk"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataBulkParams"}}}},{"if":{"properties":{"$type":{"const":"DataCapabilities"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCapabilitiesParams"}}}},{"if":{"properties":{"$type":{"const":"DataCompositeField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataCompositeFieldParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDenormalized"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDenormalizedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataDirectOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataEntityMembershipParams"}}}},{"if":{"properties":{"$type":{"const":"DataFileRef"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataFileRefParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataForceCurrentUser"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataForceCurrentUserParams"}}}},{"if":{"properties":{"$type":{"const":"DataGenerated"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataGeneratedParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataHistory"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataHistoryParams"}}}},{"if":{"properties":{"$type":{"const":"DataI18n"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataI18nParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataId"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdParams"}}}},{"if":{"properties":{"$type":{"const":"DataIdentity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataIdentityParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataImmutableFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataImmutableFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInflection"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInflectionParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataInheritFromParent"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataInheritFromParentParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataJsonb"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataJsonbParams"}}}},{"if":{"properties":{"$type":{"const":"DataLock"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataLockParams"}}}},{"if":{"properties":{"$type":{"const":"DataMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataMemberOwnerParams"}}}},{"if":{"properties":{"$type":{"const":"DataOwnedFields"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnedFieldsParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"DataOwnershipInEntity"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataOwnershipInEntityParams"}}}},{"if":{"properties":{"$type":{"const":"DataPeoplestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPeoplestampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPrincipalstamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPrincipalstampsParams"}}}},{"if":{"properties":{"$type":{"const":"DataPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataPublishableParams"}}}},{"if":{"properties":{"$type":{"const":"DataRealtime"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataRealtimeParams"}}}},{"if":{"properties":{"$type":{"const":"DataSlug"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSlugParams"}}}},{"if":{"properties":{"$type":{"const":"DataSoftDelete"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataSoftDeleteParams"}}}},{"if":{"properties":{"$type":{"const":"DataStatusField"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataStatusFieldParams"}}}},{"if":{"properties":{"$type":{"const":"DataTags"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTagsParams"}}}},{"if":{"properties":{"$type":{"const":"DataTimestamps"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/DataTimestampsParams"}}}},{"if":{"properties":{"$type":{"const":"SearchBm25"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchBm25Params"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchFullText"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchFullTextParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchSpatial"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialParams"}}}},{"if":{"properties":{"$type":{"const":"SearchSpatialAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchSpatialAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchTrgm"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchTrgmParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"SearchUnified"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchUnifiedParams"}}}},{"if":{"properties":{"$type":{"const":"SearchVector"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/SearchVectorParams"}}}},{"if":{"properties":{"$type":{"const":"TableOrganizationSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableOrganizationSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserProfiles"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserProfilesParams"}}}},{"if":{"properties":{"$type":{"const":"TableUserSettings"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/TableUserSettingsParams"}}}},{"if":{"properties":{"$type":{"const":"EventReferral"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventReferralParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"EventTracker"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/EventTrackerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"GuardStepUp"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/GuardStepUpParams"}}}},{"if":{"properties":{"$type":{"const":"JobTrigger"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/JobTriggerParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceFeature"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceFeatureParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitEnforceRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitEnforceRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitTrackUsage"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitTrackUsageParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningAggregate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningAggregateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningCounter"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningCounterParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"LimitWarningRate"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/LimitWarningRateParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"ProcessChunks"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessChunksParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessCustom"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessCustomParams"}},"required":["data"]}},{"if":{"properties":{"$type":{"const":"ProcessExtraction"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessExtractionParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessFileEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessFileEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageEmbedding"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageEmbeddingParams"}}}},{"if":{"properties":{"$type":{"const":"ProcessImageVersions"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/ProcessImageVersionsParams"}}}}],"description":"Object form -- { $type, data } with typed parameters."},"BlueprintNodeShorthand":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzHumanOnly","AuthzMemberOwner","AuthzPublishable","AuthzSystemOnly","AuthzTemporal","CheckGreaterThan","CheckLessThan","DataArchivable","DataBulk","DataCapabilities","DataDirectOwner","DataEntityMembership","DataForceCurrentUser","DataHistory","DataId","DataJsonb","DataLock","DataMemberOwner","DataOwnershipInEntity","DataPeoplestamps","DataPrincipalstamps","DataPublishable","DataRealtime","DataSlug","DataSoftDelete","DataStatusField","DataTags","DataTimestamps","SearchSpatial","SearchUnified","SearchVector","TableOrganizationSettings","TableUserProfiles","TableUserSettings","GuardStepUp","ProcessChunks","ProcessExtraction","ProcessFileEmbedding","ProcessImageEmbedding","ProcessImageVersions"],"description":"String shorthand -- just the node type name."},"BlueprintPolicy":{"type":"object","properties":{"privileges":{"type":"array","minItems":1,"items":{"type":"string","pattern":"^([Ss][Ee][Ll][Ee][Cc][Tt]|[Ii][Nn][Ss][Ee][Rr][Tt]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee])$"}},"permissive":{"type":"boolean"},"policy_role":{"type":"string"},"policy_name":{"type":"string"},"data":{"type":"object"},"with_check":{"$ref":"#/$defs/BlueprintPolicyWithCheck"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-6ac44ac2ba"},{"$ref":"#/$defs/shared-0379afb669"},{"$ref":"#/$defs/shared-ca5d04c28d"},{"$ref":"#/$defs/shared-ff315e2ff3"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-5a2b860e32"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-1afc3ee393"},{"$ref":"#/$defs/shared-968a890679"},{"$ref":"#/$defs/shared-35954fc61d"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-7756a0ed5a"},{"$ref":"#/$defs/shared-a5a04dd84a"},{"$ref":"#/$defs/shared-f5f12fa8f6"},{"$ref":"#/$defs/shared-b297346d46"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-0022037ad5"},{"$ref":"#/$defs/shared-1d336e787f"},{"$ref":"#/$defs/shared-693097b0e5"}],"description":"An RLS policy entry for a blueprint table. A with_check override applies to UPDATE only.","if":{"required":["with_check"]},"then":{"required":["privileges"],"properties":{"privileges":{"items":{"type":"string","pattern":"^[Uu][Pp][Dd][Aa][Tt][Ee]$"}}}}},"BlueprintPolicyWithCheck":{"type":"object","properties":{"data":{"type":"object"},"$type":{"$ref":"#/$defs/shared-af38a22089"}},"additionalProperties":false,"required":["$type"],"allOf":[{"$ref":"#/$defs/shared-39f66ad592"},{"$ref":"#/$defs/shared-eb6d498d14"},{"$ref":"#/$defs/shared-21a1ba9587"},{"$ref":"#/$defs/shared-6639e33d04"},{"$ref":"#/$defs/shared-36ea8e912e"},{"$ref":"#/$defs/shared-152f619c56"},{"$ref":"#/$defs/shared-6ac44ac2ba"},{"$ref":"#/$defs/shared-0379afb669"},{"$ref":"#/$defs/shared-ca5d04c28d"},{"$ref":"#/$defs/shared-ff315e2ff3"},{"$ref":"#/$defs/shared-aced6572ca"},{"$ref":"#/$defs/shared-5a2b860e32"},{"$ref":"#/$defs/shared-a9d73b8ba7"},{"$ref":"#/$defs/shared-1afc3ee393"},{"$ref":"#/$defs/shared-968a890679"},{"$ref":"#/$defs/shared-35954fc61d"},{"$ref":"#/$defs/shared-6dbc2f5a83"},{"$ref":"#/$defs/shared-7756a0ed5a"},{"$ref":"#/$defs/shared-a5a04dd84a"},{"$ref":"#/$defs/shared-f5f12fa8f6"},{"$ref":"#/$defs/shared-b297346d46"},{"$ref":"#/$defs/shared-2997c2f821"},{"$ref":"#/$defs/shared-8881b94a41"},{"$ref":"#/$defs/shared-0022037ad5"},{"$ref":"#/$defs/shared-1d336e787f"},{"$ref":"#/$defs/shared-693097b0e5"}]},"BlueprintRelation":{"type":"object","description":"A relation entry in a blueprint definition.","properties":{"source_table":{"type":"string"},"target_table":{"type":"string"},"source_schema":{"type":"string"},"target_schema":{"type":"string"},"source_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"target_module":{"$ref":"#/$defs/BlueprintModuleTableRef"},"$type":{"enum":["RelationBelongsTo","RelationHasMany","RelationHasOne","RelationManyToMany","RelationSpatial"]}},"allOf":[{"oneOf":[{"required":["source_table"],"not":{"required":["source_module"]}},{"required":["source_module"],"not":{"anyOf":[{"required":["source_table"]},{"required":["source_schema"]}]}}]},{"oneOf":[{"required":["target_table"],"not":{"required":["target_module"]}},{"required":["target_module"],"not":{"anyOf":[{"required":["target_table"]},{"required":["target_schema"]}]}}]},{"if":{"properties":{"$type":{"const":"RelationBelongsTo"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field added"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., projects → project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true},"scope_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Columns both tables carry that the referenced row must share with the referencing row (e.g. [\"entity_id\"], or [\"project_id\"] for a stage of the same project). Adds a hidden composite FK (field_name, ...scope_fields) -> target (id, ...scope_fields) plus the target unique key it needs, so a row cannot point at another scope's row even when it knows the id."}},"required":["delete_action"]}},{"if":{"properties":{"$type":{"const":"RelationHasMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Parent table being referenced by the FK (e.g., projects in projects has many tasks)"},"target_table_id":{"type":"string","format":"uuid","description":"Child table that receives the FK field (e.g., tasks in projects has many tasks)"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the target table. Auto-derived from source table name if omitted (e.g., projects derives project_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}},"required":["delete_action"]}},{"if":{"properties":{"$type":{"const":"RelationHasOne"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that will have the FK field and unique constraint"},"target_table_id":{"$ref":"#/$defs/shared-db0e2e6361"},"field_name":{"type":"string","format":"column-ref","description":"FK field name on the source table. Auto-derived from target table name if omitted (e.g., users → user_id)"},"delete_action":{"$ref":"#/$defs/shared-e6dbbbcd8d"},"is_required":{"type":"boolean","description":"Whether the FK field is NOT NULL","default":true}},"required":["delete_action"]}},{"if":{"properties":{"$type":{"const":"RelationManyToMany"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"First table in the M:N relationship"},"target_table_id":{"type":"string","format":"uuid","description":"Second table in the M:N relationship"},"junction_table_id":{"type":"string","format":"uuid","description":"Existing junction table to use. If uuid_nil(), a new bare table is created"},"junction_table_name":{"type":"string","description":"Junction table name. Auto-derived from both table names if omitted (e.g., projects + tags derives project_tags)"},"source_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for source table. Auto-derived if omitted (e.g., projects derives project_id)"},"target_field_name":{"type":"string","format":"column-ref","description":"FK field name on junction for target table. Auto-derived if omitted (e.g., tags derives tag_id)"},"use_composite_key":{"type":"boolean","description":"When true, creates a composite PK from the two FK fields. When false, no PK is created by the trigger (use nodes with DataId for UUID PK). Mutually exclusive with nodes containing DataId.","default":false},"nodes":{"type":"array","items":{"type":"object"},"description":"Array of node objects for field creation on junction table. Each object has a $type key (e.g. DataId, DataEntityMembership) and optional data keys. Forwarded to secure_table_provision as-is. Empty array means no additional fields."},"grants":{"type":"array","items":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{"type":"array","items":{"type":"string"}}}},"required":["roles","privileges"]},"description":"Unified grant objects for the junction table. Each entry is { roles: string[], privileges: string[][] }. Forwarded to secure_table_provision as-is. Default: []"},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"}}}}},{"if":{"properties":{"$type":{"const":"RelationSpatial"}},"required":["$type"]},"then":{"properties":{"source_table_id":{"type":"string","format":"uuid","description":"Table that owns the relation (the @spatialRelation tag is emitted on the owner column of this table)"},"source_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on source_table that carries the @spatialRelation smart tag"},"target_table_id":{"type":"string","format":"uuid","description":"Table being referenced by the spatial predicate"},"target_field_id":{"type":"string","format":"uuid","description":"Geometry/geography column on target_table that the predicate is evaluated against"},"name":{"type":"string","description":"Relation name (stable, snake_case). Becomes the generated filter field name in GraphQL (e.g. nearby_clinic). Unique per (source_table_id, name) — idempotency key."},"operator":{"type":"string","enum":["st_contains","st_within","st_intersects","st_covers","st_coveredby","st_overlaps","st_touches","st_dwithin"],"description":"PostGIS spatial predicate. One of the 8 whitelisted operators. st_dwithin requires param_name."},"param_name":{"type":"string","description":"Parameter name for parametric operators (currently only st_dwithin, which needs a distance argument). Must be NULL for all other operators. Enforced by table CHECK."},"source_field":{"type":"string"},"target_field":{"type":"string"}},"required":["name","operator","source_field","target_field"]}}],"required":["$type"]},"BlueprintStorageConfig":{"type":"object","properties":{"scope":{"enum":["app","org"],"description":"Storage scope. \"app\" (default) creates app-level storage (no owner_id). \"org\" creates per-org/user storage (owner_id = org entity id, buckets seeded per-entity via AFTER INSERT trigger). Only \"app\" and \"org\" are allowed — child entity types get storage via entity_types[].storage."},"key":{"type":"string","description":"Module key discriminator. Defaults to \"default\" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case."},"buckets":{"type":"array","items":{"$ref":"#/$defs/BlueprintBucketSeed"},"description":"Initial bucket seed entries. Each creates a row in {prefix}_buckets during provisioning."},"upload_url_expiry_seconds":{"type":"number","description":"Override for presigned upload URL expiry time in seconds."},"download_url_expiry_seconds":{"type":"number","description":"Override for presigned download URL expiry time in seconds."},"default_max_file_size":{"type":"number","description":"Default maximum file size in bytes for the storage module."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"CORS allowed origins for the storage module."},"confirm_upload_delay":{"type":"string","description":"Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. \"30 seconds\"). Every files table runs the confirm loop: the AFTER INSERT trigger enqueues a storage:confirm_upload job that verifies the object exists in S3 before moving status from requested to uploaded, and expires a requested row whose bytes never arrived within upload_url_expiry_seconds. Defaults to \"30 seconds\"."},"staging":{"type":"boolean","description":"Provision a temporary staging bucket (type temp, tagged default-temp) that stages for the private default bucket, so uploads land there and are promoted into their destination on confirmation. Setting staging_ttl implies this. Defaults to false."},"staging_ttl":{"type":"string","description":"How long an unpromoted staged file survives before it is eligible for expiry (PostgreSQL interval string, e.g. \"24 hours\"). Implies staging. Defaults to \"24 hours\"."},"provisions":{"type":"object","properties":{"files":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"buckets":{"$ref":"#/$defs/BlueprintEntityTableProvision"}},"description":"Per-table overrides for storage tables. Each key targets a specific storage table (files, buckets) and uses the same shape as table_provision: { nodes, fields, grants, use_rls, policies }. Fanned out to secure_table_provision targeting the corresponding table. When a key includes policies[], those REPLACE the default storage policies for that table; tables without a key still get defaults."}},"description":"Storage configuration with optional scope. When used at the top level of a blueprint, the scope field controls whether storage is app-level (\"app\", default) or org-level (\"org\"). Seeds initial buckets, overrides module-level settings (expiry times, file size limits, CORS), and provides per-table provisioning overrides via provisions."},"BlueprintTable":{"type":"object","properties":{"table_name":{"type":"string","description":"The PostgreSQL table name to create. Required unless the entry carries a module reference instead."},"schema_name":{"type":"string","description":"Optional schema name (falls back to top-level default)."},"module":{"anyOf":[{"$ref":"#/$defs/BlueprintModuleTableRef"},{"$ref":"#/$defs/BlueprintModuleInstallRef"}],"description":"Attach this entry to a table an installed module generated instead of naming one, e.g. { type: \"agent\", scope: \"org\", table: \"message\" }. Mutually exclusive with table_name/schema_name. An entry carrying provisions names the install alone and leaves out table, since the provisions keys name the tables."},"provisions":{"type":"object","additionalProperties":{"$ref":"#/$defs/BlueprintEntityTableProvision"},"description":"Provision security onto the tables the referenced module generated, keyed by the module's own table keys (e.g. { registries: { policies: [...] } } for an image module). Requires a module reference without \"table\", since the keys name the tables. Each entry takes ownership of the security it declares: the grants/policies given become that table's whole set, replacing what the module installed — unlike this entry's own policies[]/grants[], which layer onto one table."},"nodes":{"type":"array","items":{"$ref":"#/$defs/BlueprintNode"},"description":"Array of node type entries that define the table's behavior. Omitted by an entry that only carries provisions or only attaches policies to a module table."},"fields":{"type":"array","items":{"$ref":"#/$defs/BlueprintField"},"description":"Custom fields (columns) to add to the table."},"policies":{"type":"array","items":{"$ref":"#/$defs/BlueprintPolicy"},"description":"RLS policies for this table."},"grants":{"type":"array","items":{"$ref":"#/$defs/shared-bc381c03de"},"description":"Unified grant objects. Each entry is { roles: string[], privileges: unknown[] } where privileges are [verb, columns] tuples (e.g. [[\"select\",\"*\"]]). Enables per-role targeting. Defaults to []."},"use_rls":{"type":"boolean","description":"Whether to enable RLS on this table. Defaults to true."},"indexes":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableIndex"},"description":"Table-level indexes (table_name inherited from parent)."},"full_text_searches":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableFullTextSearch"},"description":"Table-level full-text search configurations (table_name inherited from parent)."},"unique_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableUniqueConstraint"},"description":"Table-level unique constraints (table_name inherited from parent)."},"check_constraints":{"type":"array","items":{"$ref":"#/$defs/BlueprintTableCheckConstraint"},"description":"Table-level CHECK constraints (table_name inherited from parent)."}},"description":"A table definition within a blueprint.","oneOf":[{"required":["table_name"],"not":{"required":["module"]}},{"required":["module"],"not":{"anyOf":[{"required":["table_name"]},{"required":["schema_name"]}]}}],"if":{"required":["provisions"]},"then":{"required":["module"],"not":{"anyOf":[{"required":["policies"]},{"required":["grants"]},{"required":["nodes"]},{"required":["fields"]}]},"properties":{"module":{"not":{"required":["table"]}},"provisions":{"minProperties":1}}},"else":{"properties":{"module":{"$ref":"#/$defs/BlueprintModuleTableRef"}}}},"BlueprintTableCheckConstraint":{"type":"object","properties":{"$type":{"enum":["CheckOneOf","CheckGreaterThan","CheckLessThan","CheckNotEqual"]}},"required":["$type"],"allOf":[{"if":{"$ref":"#/$defs/shared-078ee82414"},"then":{"type":"object","properties":{"$type":{"const":"CheckOneOf"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckOneOfParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-2c20767ba3"},"then":{"type":"object","properties":{"$type":{"const":"CheckGreaterThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckGreaterThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-8358853df2"},"then":{"type":"object","properties":{"$type":{"const":"CheckLessThan"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckLessThanParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}},{"if":{"$ref":"#/$defs/shared-1c8d46d43b"},"then":{"type":"object","properties":{"$type":{"const":"CheckNotEqual"},"name":{"$ref":"#/$defs/shared-757c15800e"},"data":{"$ref":"#/$defs/CheckNotEqualParams","description":"The check node's parameters."},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["$type","name","data"]}}],"description":"A CHECK constraint nested inside a table definition (table_name not required)."},"BlueprintTableFullTextSearch":{"type":"object","properties":{"field":{"$ref":"#/$defs/shared-ee69c55731"},"sources":{"$ref":"#/$defs/shared-626b0c3c0b"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["field","sources"],"description":"A full-text search configuration nested inside a table definition (table_name not required)."},"BlueprintTableIndex":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-0a22d2c3f6"},"columns":{"$ref":"#/$defs/shared-5a2832df1c"},"access_method":{"$ref":"#/$defs/shared-2a834ba4ff"},"is_unique":{"$ref":"#/$defs/shared-bb55f34041"},"name":{"$ref":"#/$defs/shared-f35a015b21"},"op_classes":{"$ref":"#/$defs/shared-22f38cc906"},"options":{"$ref":"#/$defs/shared-e772a2f2a5"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["access_method"],"description":"An index definition nested inside a table definition (table_name not required)."},"BlueprintTableUniqueConstraint":{"type":"object","properties":{"columns":{"$ref":"#/$defs/shared-a0bfcadf85"},"schema_name":{"$ref":"#/$defs/shared-ad8f69741a"}},"required":["columns"],"description":"A unique constraint nested inside a table definition (table_name not required)."},"BlueprintUniqueConstraint":{"type":"object","properties":{"table_name":{"type":"string","description":"Table name this unique constraint belongs to."},"schema_name":{"$ref":"#/$defs/shared-6adc1df48e"},"columns":{"$ref":"#/$defs/shared-a0bfcadf85"}},"required":["table_name","columns"],"description":"A unique constraint definition within a blueprint (top-level, requires table_name)."},"CheckGreaterThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column > value)","default":0},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] > columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is greater than a threshold (single-column: column > value) or that one column is greater than another (cross-column: columns[0] > columns[1]). Compiled via AST helpers."},"CheckLessThanParams":{"type":"object","properties":{"column":{"$ref":"#/$defs/shared-33af0ede37"},"value":{"type":"number","description":"Threshold value for single-column comparison (column < value)"},"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns for cross-column comparison (columns[0] < columns[1])","minItems":2,"maxItems":2}},"description":"Adds a CHECK constraint that validates a column value is less than a threshold (single-column: column < value) or that one column is less than another (cross-column: columns[0] < columns[1]). Compiled via AST helpers."},"CheckNotEqualParams":{"type":"object","properties":{"columns":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Two columns that must not be equal","minItems":2,"maxItems":2}},"required":["columns"],"description":"Adds a CHECK constraint that validates two columns are not equal (columns[0] != columns[1]). Useful for preventing self-referencing rows. Compiled via AST helpers."},"CheckOneOfParams":{"type":"object","properties":{"column":{"type":"string","format":"column-ref","description":"Column to validate against the allowed values"},"values":{"type":"array","items":{"type":"string"},"description":"Array of allowed values for the column"}},"required":["column","values"],"description":"Adds a CHECK constraint that validates a column value is one of an allowed set (e.g. tier IN ('free', 'paid', 'custom')). Compiled to column = ANY(ARRAY[...]) via AST helpers."},"CheckOwnedRelationParams":{"type":"object","properties":{"link_schema_name":{"type":"string","description":"Schema holding the link tables the ownership is proven through"},"owner_scope":{"type":"string","description":"Scope that owns the referencing rows; matched against the link row's owner_scope (e.g. database, platform)"},"owner_key_field_name":{"type":"string","format":"column-ref","description":"Column on the referencing table carrying its scope key, matched against the link row's owner_key. NULL for a global scope, whose owner key is NULL by construction"},"pointers":{"type":"array","description":"Typed pointer columns to guard, each resolved through its own link table","items":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Pointer column on the referencing table"},"link_table_name":{"type":"string","description":"Link table in link_schema_name whose ids this column points at"},"target_type_field_name":{"type":"string","description":"Optional link column additionally restricted regardless of ownership (e.g. a bucket type)"},"target_type_value":{"type":"string","description":"Value target_type_field_name must equal"},"allow_owner_tier":{"type":"boolean","description":"Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database","default":false},"allow_frame_chain":{"type":"boolean","description":"Admit rows owned by any frame on the referencing row's own scope-frame chain (its own scopes, then the platform database's chain) for this column, for pointers naming a definition published UP the hierarchy — the shared platform function image a tenant route targets. Ancestry only: a peer or another keyed owner is on no chain. Requires owner_key_field_name","default":false}},"required":["field_name","link_table_name"]}},"arity":{"type":"string","enum":["exactly_one","all","any"],"description":"How many pointers a row must set: exactly_one for a polymorphic target (route → api OR site OR bucket), all for a junction/join row of a has-and-belongs-to-many relation (and for a mandatory belongs-to), any for optional pointers that are only checked when set","default":"exactly_one"},"required_error":{"type":"string","description":"Error code raised when the arity rule over the pointers is violated","default":"OWNED_RELATION_TARGET_REQUIRED"},"denied_error":{"type":"string","description":"Error code raised when the target is not owned by the referencing row owner","default":"OWNED_RELATION_TARGET_NOT_OWNED"},"trigger_function_schema":{"type":"string","description":"Schema the guard trigger function is created in; defaults to the table schema"},"trigger_function_name":{"type":"string","description":"Guard trigger function name; defaults to tg_
_owned_relation_guard"},"trigger_name":{"type":"string","description":"Guard trigger name; defaults to
_owned_relation_guard"}},"required":["link_schema_name","owner_scope","pointers"],"description":"Declares that typed pointer columns may only reference rows owned by the same scope owner as the referencing row, proven through a link table that carries the owner (owner_scope, owner_key) — typically a catalog projection that must never be referenced structurally. Creates one BEFORE INSERT OR UPDATE trigger enforcing the declared arity over the pointers and requiring every pointer that is set to resolve to a same-owner row, so it covers belongs-to / has-one / has-many (key on the row being written) and has-and-belongs-to-many (both keys on the junction row, arity all). Visibility/publication flags are never an authorization input."},"DataArchivableParams":{"type":"object","properties":{"is_archived_field":{"type":"string","format":"column-ref","description":"Column name for the archive boolean flag","default":"is_archived"},"archived_at_field":{"type":"string","format":"column-ref","description":"Column name for the archive timestamp","default":"archived_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds user-reversible archive support with is_archived boolean and archived_at timestamp, plus a partial index for efficient active-row queries."},"DataBulkParams":{"type":"object","properties":{"insert":{"type":"boolean","description":"Enable bulk insert (+bulkInsert)","default":true},"upsert":{"type":"boolean","description":"Enable bulk upsert (+bulkUpsert)","default":false},"update":{"type":"boolean","description":"Enable bulk update (+bulkUpdate)","default":false},"delete":{"type":"boolean","description":"Enable bulk delete (+bulkDelete)","default":false}},"description":"Enables bulk mutation smart tags on a table. When provisioned, adds @behavior tags for the selected bulk operations (insert, upsert, update, delete). Requires the graphile-bulk-mutations plugin."},"DataCapabilitiesParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the bit(n) mask column to create on this table.","default":"required_capabilities"},"capabilities":{"type":"object","description":"Selector for the capabilities module whose bit numbering the mask is measured in, e.g. {\"scope\": \"org\"}. Every key given must match exactly one module; none or several raises naming the candidates. Required only when the database has more than one.","properties":{"scope":{"type":"string","description":"Scope the module is installed at (\"app\", \"org\", or an entity type prefix)."},"prefix":{"type":"string","description":"Table prefix of the module instance; rarely needed since prefix follows scope."}},"additionalProperties":false},"default":{"type":"array","items":{"type":"string"},"description":"Capability names every row requires unless told otherwise, resolved to a literal mask and baked into the column default. Omitted means a zero mask: requires nothing."},"mode":{"type":"string","enum":["direct","derived"],"description":"Who writes the mask: \"direct\" the writer, bounded by the subset guard; \"derived\" the mapping row named by from_column, stamped by generated triggers and hidden from mutations.","default":"direct"},"from_column":{"type":"string","format":"column-ref","description":"Derived mode only: the column on this table naming the mapping row to copy the mask from (e.g. classification_id)."},"mapping_table":{"type":"string","description":"Derived mode only: table holding one mask per class (e.g. document_classifications)."},"mapping_key":{"type":"string","format":"column-ref","description":"Derived mode only: column on the mapping table that from_column matches.","default":"id"},"mapping_column":{"type":"string","format":"column-ref","description":"Derived mode only: the mapping table's own bit(n) mask column. Created when absent, so a classification table needs no DataCapabilities declaration of its own. Defaults to the same name as field."},"subset_guard":{"type":"boolean","description":"Direct mode only: refuse a write requiring bits the writer does not hold, so nobody can lock a row away from everyone including themselves. Off is for trusted-writer tables only.","default":true},"entity_field":{"type":"string","format":"column-ref","description":"Direct mode only: the entity column the subset guard's membership check reads.","default":"entity_id"}},"description":"Per-row required permissions. A profile compiles a person to bits so no policy joins a profiles table; this compiles a row to bits so no policy joins a grant table either — the row stores which permissions are required, and an AuthzEntityMembership policy with mask_column checks that the user has all of them. The mask only narrows: it takes access away from someone membership already lets in, and never grants access to a non-member. Zero requires nothing, which is what an unclassified row defaults to. In direct mode the writer sets the mask and the subset guard bounds it to bits the writer holds; in derived mode it is copied from a mapping row (classification -> mask) by generated triggers, so authors edit one classification instead of every document."},"DataCompositeFieldParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the derived text field to create","default":"embedding_text"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names to concatenate into the target field"},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format: 'labeled' (field_name: value) or 'plain' (values only)","default":"labeled"}},"required":["source_fields"],"description":"Creates a derived text field that automatically concatenates multiple source fields via BEFORE INSERT/UPDATE triggers. Used to produce a unified text representation (e.g., embedding_text) from multiple columns on a table. The trigger fires with '_000' prefix to run before Search* triggers alphabetically."},"DataDenormalizedParams":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"FK field on this table that references the parent row (e.g. view_id)"},"set_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on this table to be populated from the parent (e.g. [\"database_id\"])"},"ref_field":{"type":"string","format":"column-ref","description":"Field on the parent table that is the FK target (e.g. id)"},"ref_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the parent table to copy from (e.g. [\"database_id\"])"},"use_updates":{"type":"boolean","description":"If true, also creates an UPDATE trigger so changes to the FK re-copy values","default":true},"update_defaults":{"type":"boolean","description":"If true, sets the default value of set_fields to uuid_nil() so they are populated by the trigger","default":true},"func_name":{"type":"string","description":"Custom function name suffix (defaults to the FK field name)"},"func_order":{"type":"integer","description":"Trigger ordering (0-padded). Lower numbers fire first","default":0}},"required":["field","set_fields","ref_field","ref_fields"],"description":"Creates INSERT and UPDATE triggers that copy field values from a referenced (parent) table into the current table whenever the FK changes. Used to denormalize frequently-read columns (e.g. database_id on junction tables) so that RLS and queries can filter locally without joining."},"DataDirectOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for owner ID","default":"owner_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from owner_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the owner column","default":true}},"description":"Adds ownership column for direct user ownership. Enables AuthzDirectOwner authorization."},"DataEntityMembershipParams":{"type":"object","properties":{"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for entity ID","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds a foreign key constraint from entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates a B-tree index on the entity column","default":true}},"description":"Adds entity reference for organization/group scoping. Enables AuthzEntityMembership, AuthzMembership, AuthzOrgHierarchy authorization."},"DataFileRefParams":{"type":"object","required":["field"],"properties":{"field":{"type":"string","format":"column-ref","pattern":"\\S","description":"The upload, image or attachment column to register"},"storage":{"type":"object","description":"The storage module the file lives in, selected by its scope and/or key; every key given must match exactly one module. When omitted, the table's scope column decides, and a table with no scope column uses the app's storage.","properties":{"scope":{"type":"string","pattern":"\\S","description":"Scope of the storage module, e.g. \"app\", \"org\" or an entity type's scope"},"key":{"type":"string","pattern":"\\S","description":"Key of the storage module, for a scope with more than one"}},"minProperties":1,"additionalProperties":false},"bucket":{"type":"string","pattern":"\\S","description":"Key of the bucket an upload resolves to. Set this or bucket_tags, not both."},"bucket_tags":{"type":"array","items":{"type":"string"},"description":"Tags of the bucket an upload resolves to. Set this or bucket, not both."},"is_public":{"type":"boolean","description":"With no bucket named, picks the default public (true) or private (false) bucket; with a bucket named, asserts that bucket is public or private. Omitted, the bucket alone decides."},"enforce_fk":{"type":"boolean","description":"Strict mode: a real foreign key beside the column. Not implemented yet, so the backend refuses true.","default":false}},"not":{"required":["bucket","bucket_tags"]},"description":"Registers an existing upload, image or attachment column as a managed reference to a files row: it records which storage module the file lives in and which bucket an upload resolves to, and the backend generates the sync trigger and the GC index from that. The column must be declared in fields[] first; the node creates no column."},"DataForceCurrentUserParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to force to current_user_id()","default":"actor_id"}},"description":"BEFORE INSERT trigger that forces a field to the value of jwt_public.current_user_id(). Prevents clients from spoofing the actor/uploader identity. The field value is always overwritten regardless of what the client provides."},"DataGeneratedParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the generated column to create"},"type":{"type":"object","description":"FieldType for the generated column (default: text)","default":{"name":"text"}},"kind":{"type":"string","enum":["expression","concat","slug","object_name","hash"],"description":"Preset for building the generation expression","default":"expression"},"generation_type":{"type":"string","enum":["stored","virtual"],"description":"Whether the column is STORED (persisted on write) or VIRTUAL (computed on read, PostgreSQL 18+)","default":"stored"},"source_field":{"type":"string","format":"column-ref","description":"Single source field for expression/slug/object_name presets"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Array of source field names for concat/hash presets"},"expression":{"type":"object","description":"Raw FieldGeneration DSL or AST (used when kind is expression)"},"separator":{"type":"string","description":"Separator used by concat preset","default":" "},"format":{"type":"string","enum":["labeled","plain"],"description":"Output format for concat preset: 'labeled' (field_name: value) or 'plain' (values only)","default":"plain"},"prefix":{"type":"string","description":"Optional prefix for object_name preset"},"suffix":{"type":"string","description":"Optional suffix for object_name preset"},"algorithm":{"type":"string","description":"Hash algorithm for hash preset (e.g. sha256, md5)","default":"sha256"},"is_required":{"type":"boolean","description":"Whether the generated column is NOT NULL","default":false}},"required":["target"],"description":"Creates a native PostgreSQL GENERATED ALWAYS AS (expr) column (STORED or VIRTUAL) from a source field expression, preset, or raw AST. The column is read-only for clients and computed automatically by PostgreSQL."},"DataHistoryParams":{"type":"object","properties":{"table_suffix":{"type":"string","description":"Suffix for the history table name","default":"_history"},"recorded_at_field":{"type":"string","format":"column-ref","description":"Column name for the version timestamp (also the partition key when partitioned)","default":"recorded_at"},"operation_field":{"type":"string","format":"column-ref","description":"Column name recording the operation ('INSERT' | 'UPDATE' | 'DELETE')","default":"history_op"},"exclude_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Source columns to omit from the history table (e.g. large jsonb or vector columns). Excluded columns are never created on the history table and never written by the trigger.","default":[]},"copy_mutation_policies":{"type":"boolean","description":"Whether to also clone INSERT/UPDATE/DELETE policies (not just SELECT). Default false — the history table is written only by the trigger and exposed read-only through GraphQL.","default":false},"partitioned":{"type":"boolean","description":"When true, range-partition the history table by recorded_at via pg_partman so old partitions can be dropped per the retention window.","default":false},"partition_interval":{"type":"string","description":"pg_partman partition interval (when partitioned)","default":"1 month"},"retention":{"type":"string","description":"pg_partman retention window; partitions older than this are dropped by run_maintenance (when partitioned). Empty keeps forever.","default":"12 months"},"premake":{"type":"integer","description":"Number of future partitions pg_partman pre-creates","default":2}},"description":"Creates a companion
_history table that records a new version row on every INSERT/UPDATE/DELETE via an AFTER trigger. The history table copies the source columns as plain nullable columns with NO keys or constraints, plus a recorded_at timestamp and a history_op column (NEW-append: INSERT/UPDATE store the new row, DELETE stores a tombstone). SELECT policies are cloned from the base table. Optionally range-partitions the history table by recorded_at (pg_partman) with a retention window so history is kept for a while but not forever. Adds an @history smart comment so the Graphile history plugin can expose version queries and restore mutations."},"DataI18nParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names on the base table to make translatable. Each field is duplicated on the translation table with the same type."},"table_suffix":{"type":"string","description":"Suffix for the translation table name","default":"_translations"},"lang_code_type":{"type":"string","enum":["citext","text"],"description":"Type for the lang_code column","default":"citext"},"copy_mutation_policies":{"type":"boolean","description":"Whether to also copy INSERT/UPDATE/DELETE policies (not just SELECT). Default true — translations should be editable by the same users who can edit the base row.","default":true},"search":{"type":"object","description":"SearchFullText configuration for the translations table. When provided, creates a tsvector column on the translations table with lang_column=lang_code for dynamic per-row language stemming.","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column on the translations table","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the translatable source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"}},"required":["field"]},"description":"Translatable columns that feed the tsvector. Language is determined dynamically from the lang_code column of each row."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"]}},"required":["fields"],"description":"Creates a companion _translations table with lang_code + translatable fields. Copies SELECT policies and column-ref fields from the base table. Adds @i18n smart comment so the Graphile i18n plugin discovers it. Requires i18n_module to be provisioned for the database."},"DataIdParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the primary key","default":"id"}},"description":"Adds a UUID primary key column with auto-generation default (uuidv7). This is the standard primary key pattern for all tables."},"DataIdentityParams":{"type":"object","properties":{"target":{"type":"string","format":"column-ref","description":"Name of the identity column to create"},"type":{"type":"object","description":"FieldType for the identity column (default: bigint)","default":{"name":"bigint"}},"generation":{"type":"string","enum":["always","by_default"],"description":"'always' for GENERATED ALWAYS AS IDENTITY, 'by_default' for GENERATED BY DEFAULT AS IDENTITY","default":"by_default"},"sequence":{"type":"object","description":"Optional sequence tuning for the backing identity sequence","properties":{"start":{"type":"integer","description":"START WITH value"},"increment":{"type":"integer","description":"INCREMENT BY value"},"min":{"type":["integer","null"],"description":"MINVALUE (null uses the default)"},"max":{"type":["integer","null"],"description":"MAXVALUE (null uses the default)"},"cache":{"type":"integer","description":"CACHE value"},"cycle":{"type":"boolean","description":"Whether the sequence cycles (CYCLE / NO CYCLE)"}}},"is_required":{"type":"boolean","description":"Whether the identity column is NOT NULL (identity columns are implicitly NOT NULL)","default":false}},"required":["target"],"description":"Creates a native PostgreSQL identity column (GENERATED ALWAYS / BY DEFAULT AS IDENTITY) backed by an implicit sequence. The database assigns values automatically; ALWAYS identity columns are not writable by clients."},"DataImmutableFieldsParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names that cannot be modified after INSERT (e.g. [\"key\", \"bucket_id\", \"owner_id\"])"}},"required":["fields"],"description":"BEFORE UPDATE trigger that prevents changes to a list of specified fields after INSERT. Raises an exception if any of the listed fields have changed. Unlike FieldImmutable (single-field), this handles multiple fields in a single trigger for efficiency."},"DataInflectionParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to transform"},"ops":{"type":"array","items":{"type":"string","enum":["plural","singular","camel","pascal","dashed","slugify","underscore","lower","upper"]},"description":"Inflection operations to apply in order"}},"required":["field_name","ops"],"description":"Transforms field values using inflection operations (snake_case, camelCase, slugify, plural, singular, etc). Attaches BEFORE INSERT and BEFORE UPDATE triggers. References fields by name in data jsonb."},"DataInheritFromParentParams":{"type":"object","properties":{"parent_fk_field":{"type":"string","format":"column-ref","description":"Name of the FK field on this table that references the parent (e.g. bucket_id)"},"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to copy from the parent row (e.g. [\"owner_id\", \"is_public\"])"},"parent_table":{"type":"string","description":"Parent table name (optional fallback if FK not yet registered in metaschema)"},"parent_schema":{"type":"string","description":"Parent table schema (optional, defaults to same schema as child table)"}},"required":["parent_fk_field","fields"],"description":"BEFORE INSERT OR UPDATE trigger that copies specified fields from a parent table via a foreign key; on UPDATE the fields are re-copied only when the parent FK changes. The parent row is looked up through RLS (SECURITY INVOKER), so the insert or update fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files."},"DataJsonbParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the JSONB field","default":"metadata"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false},"create_index":{"type":"boolean","description":"Whether to create a GIN index","default":true}},"description":"Adds a JSONB column with optional GIN index for containment queries (@>, ?, ?|, ?&). Standard pattern for semi-structured metadata."},"DataLockParams":{"type":"object","properties":{"lock_field":{"type":"string","format":"column-ref","description":"Boolean column holding the lock state","default":"locked"},"events":{"type":"array","items":{"type":"string","enum":["UPDATE","DELETE"]},"description":"Which DML events are guarded while the row is locked. INSERT is not lockable — a row cannot be locked before it exists.","default":["DELETE"]},"enforcement":{"type":"string","enum":["step_up","block"],"description":"How a guarded verb is stopped while locked. step_up requires recent strong verification (needs a provisioned user_auth_module); block refuses the verb outright with ROW_LOCKED until unlocked.","default":"step_up"},"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Verification method satisfying the step-up requirement, for the guarded verbs in step_up mode and for clearing the lock","default":"fresh_auth"},"guard_unlock":{"type":"boolean","description":"Require step-up to change the lock column itself, so a locked row cannot be quietly unlocked and then deleted. Redundant (and therefore skipped) in step_up mode when UPDATE is already guarded.","default":true},"protect_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For a guarded UPDATE, restrict the guard to changes touching these columns. Empty guards the whole row.","default":[]},"default_locked":{"type":"boolean","description":"Initial value of the lock column for new rows","default":false},"min_age":{"type":"string","description":"Optional interval (e.g. \"24 hours\"); in step_up mode the guard only fires for rows older than this, so freshly created rows stay easy to clean up. Empty guards rows of any age.","default":""}},"description":"Adds a boolean lock column and guards mutations while a row is locked, so infrastructure rows other things depend on (a bucket a function needs, a route, a resource) are not deleted or edited by accident. Two enforcement modes: step_up requires recent strong verification (via GuardStepUp / require_step_up) for the guarded verbs, while block refuses them outright until the row is unlocked. Clearing the lock is itself step-up guarded, so unlocking is a deliberate, re-authenticated step rather than a silent prelude to deletion."},"DataMemberOwnerParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true},"entity_type":{"type":"string","description":"Membership scope (e.g. 'org', 'room'). Resolved to a membership type via the database's membership_types_module. This is the authoring form — use it instead of membership_type."},"membership_type":{"type":"integer","description":"Membership type resolved from the scope. Internal: prefer entity_type. Cannot be combined with entity_type."}},"description":"Adds owner_id and entity_id columns with a compound AuthzMemberOwner policy. The current user must own the row and be a member of the entity it belongs to. Use for private data within an entity scope — e.g., personal chat threads that belong to the company but only the author can see."},"DataOwnedFieldsParams":{"type":"object","properties":{"role_key_field_name":{"type":"string","format":"column-ref","description":"Name of the field identifying the owner (e.g. sender_id)"},"protected_field_names":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Names of fields only this owner can modify"}},"required":["role_key_field_name","protected_field_names"],"description":"Restricts which user can modify specific columns in shared objects. Creates an AFTER UPDATE trigger that throws OWNED_PROPS when a non-owner tries to change protected fields. References fields by name in data jsonb."},"DataOwnershipInEntityParams":{"type":"object","properties":{"owner_field_name":{"type":"string","format":"column-ref","description":"Column name for the owner reference","default":"owner_id"},"entity_field_name":{"type":"string","format":"column-ref","description":"Column name for the entity reference","default":"entity_id"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from owner_id and entity_id to the users table","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the owner and entity columns","default":true}},"description":"Combines direct ownership with entity scoping. Adds both owner_id and entity_id columns. Enables AuthzDirectOwner, AuthzEntityMembership, and AuthzOrgHierarchy authorization. Particularly useful for OrgHierarchy where a user owns a row (owner_id) within an entity (entity_id), and managers above can see subordinate-owned records via the hierarchy closure table."},"DataPeoplestampsParams":{"type":"object","properties":{"created_by_field":{"type":"string","format":"column-ref","description":"Column name for the creating user reference","default":"created_by"},"updated_by_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating user reference","default":"updated_by"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"include_user_fk":{"type":"boolean","description":"If true, adds foreign key constraints from created_by and updated_by to the users table","default":false},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the peoplestamp columns","default":true}},"description":"Adds human actor tracking for creates/updates: created_by/updated_by record the human user (jwt_public.current_user_id())."},"DataPrincipalstampsParams":{"type":"object","properties":{"created_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the creating principal reference (agent, API key, or user)","default":"created_by_principal"},"updated_by_principal_field":{"type":"string","format":"column-ref","description":"Column name for the last-updating principal reference (agent, API key, or user)","default":"updated_by_principal"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true},"create_index":{"type":"boolean","description":"If true, creates B-tree indexes on the principalstamp columns","default":true}},"description":"Adds acting-principal tracking for creates/updates: created_by_principal/updated_by_principal record the acting principal — agent, API key, service identity, or the user itself (jwt_public.current_principal_id())."},"DataPublishableParams":{"type":"object","properties":{"is_published_field_name":{"type":"string","format":"column-ref","description":"Column name for the published boolean flag","default":"is_published"},"published_at_field_name":{"type":"string","format":"column-ref","description":"Column name for the publish timestamp","default":"published_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds publish state columns (is_published, published_at) for content visibility. Enables AuthzPublishable and AuthzTemporal authorization."},"DataRealtimeParams":{"type":"object","properties":{"operations":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML operations to track with emit_change triggers","default":["INSERT","UPDATE","DELETE"]},"subscriber_table_name":{"type":"string","description":"Custom name for the subscriber table (defaults to {source_table}_subscriber)"},"ephemeral":{"type":"boolean","description":"When true, events are delivered via pg_notify only without writing to change_log. Ideal for high-frequency ephemeral signals (e.g. cursor positions, live indicators) where persistence is unnecessary. Subscriber table and RLS policies are still created for access control.","default":false}},"description":"Creates per-table subscriber tables in subscriptions_public with RLS policies derived from source table SELECT policies. Attaches statement-level triggers to emit changes to subscribers."},"DataSlugParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the field to slugify","default":"slug"},"source_field_name":{"type":"string","format":"column-ref","description":"Optional source field name (defaults to field_name)"}},"required":[],"description":"Auto-generates URL-friendly slugs from field values on insert/update. Attaches BEFORE INSERT and BEFORE UPDATE triggers that call inflection.slugify() on the target field. References fields by name in data jsonb."},"DataSoftDeleteParams":{"type":"object","properties":{"deleted_at_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete timestamp","default":"deleted_at"},"is_deleted_field":{"type":"string","format":"column-ref","description":"Column name for the soft-delete boolean flag","default":"is_deleted"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds soft delete support with deleted_at and is_deleted columns."},"DataStatusFieldParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the status field","default":"status"},"type":{"$ref":"#/$defs/FieldType","description":"Column type as a FieldType object"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object (e.g., { value: \"active\" })"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":true},"allowed_values":{"type":"array","items":{"type":"string"},"description":"If provided, creates a CHECK constraint restricting the column to these values"}},"description":"Adds a status column with B-tree index for efficient equality filtering and sorting. Optionally constrains values via CHECK constraint when allowed_values is provided."},"DataTagsParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Column name for the tags array","default":"tags"},"default_value":{"$ref":"#/$defs/FieldDefault","description":"Default value as a FieldDefault object"},"is_required":{"type":"boolean","description":"Whether the column has a NOT NULL constraint","default":false}},"description":"Adds a citext[] tags column with GIN index for efficient array containment queries (@>, &&). Standard tagging pattern for categorization and filtering."},"DataTimestampsParams":{"type":"object","properties":{"created_at_field":{"type":"string","format":"column-ref","description":"Column name for the creation timestamp","default":"created_at"},"updated_at_field":{"type":"string","format":"column-ref","description":"Column name for the last-updated timestamp","default":"updated_at"},"include_id":{"type":"boolean","description":"If true, also adds a UUID primary key column with auto-generation","default":true}},"description":"Adds automatic timestamp tracking with created_at and updated_at columns."},"EventReferralParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record for the referrer (e.g., \"invitee_uploaded_avatar\", \"invitee_completed_onboarding\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the invitee (actor) ID on the source table — used to look up the referrer via claimed_invites.receiver_id","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped referral events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"max_depth":{"type":"integer","description":"Maximum depth to walk up the invite chain. Default 1 (direct inviter only). Set 2–10 to enable multi-level referral rewards. App-level only — must not be combined with entity_field.","default":1,"minimum":1,"maximum":10},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events for the referrer (inviter) when their invitees perform actions on a watched table. Resolves the referrer automatically via the invites module's claimed_invites table using the membership_type context. Supports the same compound condition system as EventTracker. Use with achievements to unlock levels and grant credits based on invitee activity."},"EventTrackerParams":{"type":"object","properties":{"event_name":{"type":"string","description":"Event type name to record (e.g., \"avatar_uploaded\", \"order_completed\")"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"DML events that trigger recording","default":["INSERT"]},"count":{"type":"integer","description":"Number of events to record per trigger fire","default":1},"toggle":{"type":"boolean","description":"Toggle mode: records event when condition is met, removes when condition is unmet","default":false},"actor_field":{"type":"string","format":"column-ref","description":"Column containing the actor (user) ID to attribute the event to","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column containing the entity ID (org/group) for entity-scoped events. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup. Omit for user-only events."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"auto_register_type":{"type":"boolean","description":"Automatically register the event_name in event_types during provisioning","default":true},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":["event_name"],"description":"Creates triggers that record events via the events module when table rows change. Supports the same compound condition system as JobTrigger (condition_field, watch_fields, or full AND/OR/NOT conditions). Events are recorded to app_events and aggregated automatically. Use with achievements (blueprint-level) to unlock levels and grant credits based on event accumulation."},"FieldDefault":{"type":"object","description":"A structured default expression, e.g. { value: false }, { function: \"now\" } or { value: {}, cast: { name: \"jsonb\" } }.","properties":{"value":{"description":"Literal value."},"function":{"type":"string","description":"Function name."},"schema":{"type":"string","description":"Schema qualifier of the function."},"args":{"type":"array","items":{"anyOf":[{"type":["string","number","boolean","null"]},{"$ref":"#/$defs/FieldDefault"}]},"description":"Function arguments."},"cast":{"$ref":"#/$defs/FieldType"},"operator":{"type":"string","description":"Binary operator, e.g. \"+\"."},"left":{"$ref":"#/$defs/FieldDefault"},"right":{"$ref":"#/$defs/FieldDefault"},"sql_keyword":{"type":"string","description":"SQL keyword, e.g. \"CURRENT_TIMESTAMP\"."}}},"FieldType":{"type":"object","description":"A structured PostgreSQL type, e.g. { name: \"text\" } or { name: \"numeric\", args: [10, 2] }.","properties":{"name":{"type":"string","description":"Type name."},"schema":{"type":"string","description":"Schema qualifier."},"args":{"type":"array","items":{"type":["string","number","boolean"]},"description":"Type arguments."},"array_dimensions":{"type":"integer","description":"Number of array dimensions: 1 is text[]."},"range":{"type":"array","items":{"type":"string"},"maxItems":2,"description":"Interval field range, e.g. [\"day\", \"second\"]."}},"required":["name"]},"GuardStepUpParams":{"type":"object","properties":{"step_up_type":{"type":"string","enum":["password","mfa","fresh_auth","password_or_mfa"],"description":"Which recent proof satisfies the step-up requirement: password (password re-entry), mfa (second factor), password_or_mfa (either factor; an SSO sign-in alone does not count), or fresh_auth (any recent sign-in or re-verification, including SSO, magic link and OTP)","default":"fresh_auth"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Which DML events require step-up verification","default":["UPDATE","DELETE"]},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"}},"required":[],"description":"Attaches a BEFORE trigger that calls require_step_up() to enforce recent strong verification (password, MFA, or identity-provider assertion) before allowing mutations. Requires a provisioned sessions_module (with app_settings_auth) for the target database. The step_up_window is read from app_settings_auth at runtime (default 30 minutes). Supports compound conditions (AND/OR/NOT), watch_fields (fire only when specific fields change), and simple condition_field/condition_value leaf conditions."},"JobTriggerParams":{"type":"object","properties":{"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier passed to add_job (e.g., process_invoice, sync_to_stripe). Must match a registered function definition when function_module is installed."},"payload_strategy":{"type":"string","enum":["row","row_id","fields","custom"],"description":"How to build the job payload: row (full NEW/OLD), row_id (just id), fields (selected columns), custom (mapped columns)","default":"row_id"},"payload_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names to include in payload (only for fields strategy)"},"payload_custom":{"type":"object","additionalProperties":{"type":"string","format":"column-ref"},"description":"Key-to-column mapping for custom payload (e.g., {\"invoice_id\": \"id\", \"total\": \"amount\"})"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-eb860e1011"},"description":"Trigger events to create","default":["INSERT","UPDATE"]},"include_old":{"type":"boolean","description":"Include OLD row in payload (for UPDATE triggers)","default":false},"include_meta":{"type":"boolean","description":"Include table/schema metadata in payload","default":false},"condition_field":{"$ref":"#/$defs/shared-88656ecafa"},"condition_value":{"$ref":"#/$defs/shared-f7ad90b1e2"},"conditions":{"$ref":"#/$defs/shared-cc52e308f2"},"watch_fields":{"$ref":"#/$defs/shared-fe3f452ee5"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"$ref":"#/$defs/shared-6b829f5502"},"obj_schema":{"$ref":"#/$defs/shared-11a9ffe32a"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"job_key":{"type":"string","description":"Static job key for upsert semantics (prevents duplicate jobs)"},"queue_name":{"type":"string","description":"Job queue name for routing to specific workers"},"queue_key_field":{"type":"string","format":"column-ref","description":"Column whose value keys the job queue, so the queue name becomes \":\". A named queue is held for the whole job, so a shared literal queue serializes every job that uses it; keying on the work's subject keeps same-subject jobs ordered while unrelated subjects run in parallel."},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0},"run_at_delay":{"type":"string","description":"Delay before job runs as PostgreSQL interval (e.g., 30 seconds, 5 minutes)"},"max_attempts":{"type":"integer","description":"Maximum retry attempts for the job","default":25}},"required":["task_identifier"],"description":"Dynamically creates PostgreSQL triggers that enqueue jobs via app_jobs.add_job() when table rows are inserted, updated, or deleted. Supports configurable payload strategies (full row, row ID, selected fields, or custom mapping), conditional firing via WHEN clauses, watched field changes, and extended job options (queue, priority, delay, max attempts)."},"LimitEnforceAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to track (must match a default_limits entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches aggregate limit-tracking triggers to a table. On INSERT the named limit is incremented per entity; on DELETE it is decremented. Uses org_limit_aggregates_inc/dec for per-entity (org-level) aggregate limits rather than per-user limits. Requires a provisioned limits_module for the target database."},"LimitEnforceCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to track (must match a default_limits entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor or entity id used for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for entity context resolution. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]}},"required":["limit_name"],"description":"Declaratively attaches limit-tracking triggers to a table. On INSERT the named limit is incremented; on DELETE it is decremented. Requires a provisioned limits_module for the target scope."},"LimitEnforceFeatureParams":{"type":"object","properties":{"feature_name":{"type":"string","description":"Cap name representing this feature (must match a limit_caps_defaults entry with max=0 or max=1)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for per-entity cap lookups (only used for org scope). For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Which DML events the cap gates. UPDATE is required when a row can reach the gated state after creation (e.g. a discriminator flipped from an ungated value to a gated one). DELETE is not supported: a cap answers whether a row may exist.","default":["INSERT"]},"conditions":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Compound conditions for the trigger WHEN clause, so the cap gates a subset of rows rather than the whole table (e.g. only the rows a customer authors on a table the platform also writes). Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema."}},"required":["feature_name"],"description":"Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). Gate INSERT and UPDATE when a row can reach the gated state after creation, and narrow the gate with conditions when only some of the table's rows are the gated feature."},"LimitEnforceRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry, e.g. \"messaging\", \"inference\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limiting. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id (user) for rate limiting","default":"owner_id"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Which DML events to enforce rate limits on (DELETE is excluded since it reduces load)","default":["INSERT"]}},"required":["meter_slug"],"description":"Attaches a BEFORE trigger that calls check_rate_limit() to enforce sliding-window rate limits before allowing mutations. The function checks all three scopes (entity, actor-in-entity, actor) in a single call; which scopes are actually enforced is controlled by what rows exist in rate_window_limits (plan-based config). Requires a provisioned meter_rate_limits_module and billing_module for the target database."},"LimitTrackUsageParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to record usage against (must match a meters table entry, e.g. \"databases\", \"seats\")"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for billing. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"quantity":{"type":"integer","description":"Units to record per event (default 1)","default":1},"events":{"type":"array","items":{"$ref":"#/$defs/shared-6eb30390ff"},"description":"Which DML events to attach triggers for","default":["INSERT","DELETE"]},"enforce":{"type":"boolean","description":"With INSERT tracked, also attach a BEFORE INSERT gate on check_billing_quota that refuses a row past the allowance (BILLING_QUOTA_EXCEEDED), like the invocation quota gate. Off (default), rows past the allowance are inserted and their charge is refused. A slug with no meter row is never refused.","default":false}},"required":["meter_slug"],"description":"Declaratively attaches billing usage-recording triggers to a table. On INSERT the named meter is incremented via record_usage; on DELETE it is decremented (reversal). On UPDATE, if the entity_field changes, the old entity is decremented and the new entity is incremented. Requires a provisioned billing_module for the target database."},"LimitWarningAggregateParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the aggregate limit to watch (must match a limit_warnings.name entry, e.g. \"databases\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"org\", \"data_room\", \"channel\", \"team\").","default":"org"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for aggregate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the entity's aggregate usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor/entity triple. Requires a provisioned limits_module with limit_warnings and aggregate limits enabled."},"LimitWarningCounterParams":{"type":"object","properties":{"limit_name":{"type":"string","description":"Name of the limit to watch (must match a limit_warnings.name entry, e.g. \"projects\", \"members\")"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for limit lookup","default":"owner_id"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id. When provided, entity_id is included in the job payload and dedup state. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup."},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"}},"required":["limit_name"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current usage has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires a provisioned limits_module with limit_warnings enabled."},"LimitWarningRateParams":{"type":"object","properties":{"meter_slug":{"type":"string","description":"Slug of the billing meter to check rate limits against (must match a meters table entry)"},"scope":{"type":"string","description":"Membership type prefix that determines which limits_module row to use for warnings and warning_state tables. Resolved dynamically via memberships_module — supports any provisioned type (e.g. \"app\", \"org\", \"data_room\", \"channel\", \"team\").","default":"app"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds (or references) the entity id for rate limit lookup. For direct entity_id columns, just set this field. For FK lookups (e.g., channel_id → channels.entity_id), combine with entity_lookup.","default":"entity_id"},"entity_lookup":{"$ref":"#/$defs/shared-230094622e"},"actor_field":{"type":"string","format":"column-ref","description":"Column on the target table that holds the actor id for rate limit lookup","default":"owner_id"}},"required":["meter_slug"],"description":"Attaches an AFTER INSERT trigger that checks if the actor's current request count in the active sliding window has crossed any warning threshold configured in the limit_warnings table. If a threshold is reached for the first time, enqueues a background job (e.g. email notification). Uses limit_warning_state for one-time dedup per warning/actor pair. Requires both a limits_module with limit_warnings enabled and a rate_limit_meters_module."},"ProcessChunksParams":{"type":"object","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Parent columns the chunks are cut from. When set, the enqueue triggers fire only once one of them is populated (INSERT) or changed (UPDATE), and the worker chunks exactly those columns. Omit to chunk every readable content column on every write."},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"dimensions":{"type":"integer","description":"Vector dimensions for per-chunk embeddings","default":768},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric for the HNSW index on chunk embeddings","default":"cosine"},"embedding_model":{"type":"string","description":"Embedding model identifier for per-chunk embeddings. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"chunks_table_name":{"type":"string","description":"Override the chunks table name. Defaults to {parent_table}_chunks."},"metadata_fields":{"type":"array","items":{"type":"string"},"description":"Field names from the parent table to copy into chunk metadata"},"search_indexes":{"type":"array","items":{"$ref":"#/$defs/shared-5492e6a87c"},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override (e.g. [\"fulltext\", \"bm25\"])."},"entity_field":{"type":"string","format":"column-ref","description":"Column on the parent table that holds (or references) the entity_id for billing scope. Forwarded to the chunking job trigger."},"entity_lookup":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the chunking job trigger.","properties":{"obj_table":{"$ref":"#/$defs/shared-462d3d2412"},"obj_schema":{"$ref":"#/$defs/shared-3d0fa23a34"},"obj_field":{"$ref":"#/$defs/shared-d4553f7be9"}},"required":["obj_table","obj_field"]},"enqueue_chunking_job":{"type":"boolean","description":"Whether to create a job trigger that auto-enqueues chunking on parent INSERT/UPDATE","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}},"description":"Creates a chunked-embedding child table for any parent table. Provisions the chunks table with content, chunk_index, embedding vector, metadata, HNSW index, inherited RLS, and optional job trigger for automatic text splitting. Composed internally by ProcessFileEmbedding (enabled by default in extract mode) but can also be used standalone."},"ProcessCustomParams":{"type":"object","required":["task_identifier"],"properties":{"task_identifier":{"type":"string","format":"function-ref","description":"Task identifier of the tenant-registered function (namespace:name). Must resolve through the function registry for this database at provisioning time."},"result_field":{"type":"string","format":"column-ref","description":"Optional jsonb field on the files table that receives the result the task hands to the generated writer. When omitted the writer only records the uploaded → processed transition."},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"Optional MIME type LIKE patterns to match. Multiple patterns are OR'd together. When omitted every uploaded file is processed."},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"type":"string","format":"column-ref","description":"Column on the files table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger."},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for the task","default":"process_custom"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Enqueues a tenant-registered task when a file on a storage files table reaches status = 'uploaded' and generates the result writer the task calls back over the function lane. The task must already be registered for the database (register_function with scope database); the node is refused otherwise."},"ProcessExtractionParams":{"type":"object","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"extraction_model":{"$ref":"#/$defs/shared-f862b57bdc"},"extraction_provider":{"$ref":"#/$defs/shared-82428b2411"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%'].","default":["application/pdf","text/%"]},"routes":{"$ref":"#/$defs/shared-9649b5119d"},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the extraction worker","default":"document:extract_file_text"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and text_field (created as jsonb) and metadata_field hold one entry per element, as jsonb objects keyed by the element's object key."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for extraction tasks","default":"extraction"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates extraction output fields and a job trigger for file text extraction. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks."},"ProcessFileEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 512 for CLIP, 768 for nomic, 1536 for ada-002)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-c9b32dbf00"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"$ref":"#/$defs/shared-cf7316ac6e"},"task_identifier":{"$ref":"#/$defs/shared-f90494132b"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_FILE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"source_bucket":{"$ref":"#/$defs/shared-41591dfcf8"},"variants_bucket":{"$ref":"#/$defs/shared-8aa6c03738"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"extraction":{"$ref":"#/$defs/shared-a0d2b7ccf1"},"include_chunks":{"$ref":"#/$defs/shared-347ff05f99"},"chunks":{"type":"object","description":"Chunking configuration passed through to ProcessChunks. When include_chunks is true (or defaults to true in extract mode), these params configure the chunks table, embedding dimensions, strategy, etc.","default":{},"properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"paragraph"},"metadata_fields":{"$ref":"#/$defs/shared-6119be8d95"},"search_indexes":{"$ref":"#/$defs/shared-0ed784651d"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}},"description":"Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided; extract mode composes ProcessExtraction for the text (its task, MIME rule, queue and, on a storage files table, its result writer). On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies."},"ProcessImageEmbeddingParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector embedding column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (default 512 for CLIP-style image embeddings)","default":512},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"embedding_model":{"$ref":"#/$defs/shared-0d918e14b9"},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image embedding worker. The payload is the file row (file_id, key, mime_type, bucket_id), so the task must be a record worker that reads the object itself — not embedding:process_image_embedding, which embeds an image_url it is handed.","default":"embedding:process_file_embedding"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_IMAGE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"}},"description":"Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_file_embedding', direct mode only: there is no image extraction (OCR) worker, so extraction is refused. Every other parameter is forwarded through."},"ProcessImageVersionsParams":{"type":"object","properties":{"versions":{"$ref":"#/$defs/shared-1232a5e8ca"},"versions_field":{"type":"string","format":"column-ref","description":"Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document.","default":"image_versions"},"mime_patterns":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it.","default":["image/%"]},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier for the image processing worker","default":"image:process_image_versions"},"events":{"type":"array","items":{"type":"string","enum":["INSERT","UPDATE"]},"description":"Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested).","default":["INSERT"]},"file_field":{"type":"string","format":"column-ref","description":"Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and each element carries its own manifest in its versions member."},"payload_custom":{"$ref":"#/$defs/shared-8cef65cfda"},"trigger_conditions":{"$ref":"#/$defs/shared-787b8adf81"},"entity_field":{"$ref":"#/$defs/shared-1a317ed066"},"entity_lookup":{"$ref":"#/$defs/shared-7edb884d72"},"queue_name":{"type":"string","description":"Job queue name for image processing tasks","default":"image_processing"},"max_attempts":{"type":"integer","description":"Maximum number of retry attempts","default":5},"priority":{"type":"integer","description":"Job priority (lower = higher priority)","default":0}},"description":"Creates a job trigger for image variant generation. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The image worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.), stores them beside the source object in the file's own bucket, and records each variant's name, key, format, dimensions and size: inside the file column's own document (its versions member) on a business table, in the manifest column on a storage files table. With no versions given the worker uses the default ladder (thumbnail, small, medium, large, xlarge), resolved when the job runs, and skips any version larger than the source."},"SearchBm25Params":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of existing text column to index with BM25"},"text_config":{"type":"string","description":"PostgreSQL text search configuration for BM25","default":"english"},"k1":{"type":"number","description":"BM25 k1 parameter: term frequency saturation (typical: 1.2-2.0)"},"b":{"type":"number","description":"BM25 b parameter: document length normalization (0=none, 1=full, typical: 0.75)"},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["field_name"],"description":"Creates a BM25 index on an existing text column using pg_textsearch. Enables statistical relevance ranking with configurable k1 and b parameters. The BM25 index is auto-detected by graphile-search."},"SearchFullTextParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the tsvector column","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref","description":"Name of the source column"},"weight":{"type":"string","enum":["A","B","C","D"],"description":"tsvector weight class (A=highest, D=lowest)","default":"D"},"lang":{"type":"string","description":"PostgreSQL text search configuration","default":"english"}},"required":["field"]},"description":"Source columns that feed the tsvector. Each has a field name, weight (A-D), and language config."},"lang_column":{"type":"string","format":"column-ref","description":"Column name whose value determines the text search configuration per row. When set, the tsvector trigger uses NEW.::regconfig instead of a static language, enabling dynamic per-row language stemming. The per-field lang values in source_fields are used as fallback defaults for the langs array but the trigger reads from this column at runtime."},"search_score_weight":{"type":"number","description":"Weight for this algorithm in composite searchScore","default":1}},"required":["source_fields"],"description":"Adds a tsvector column with GIN index and automatic trigger population from source fields. Enables PostgreSQL full-text search with configurable weights and language support. Leverages the existing metaschema full_text_search infrastructure."},"SearchSpatialAggregateParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the aggregate geometry column on the parent table","default":"geom_aggregate"},"source_table_id":{"type":"string","format":"uuid","description":"UUID of the source (child) table containing individual geometries"},"source_geom_field":{"type":"string","format":"column-ref","description":"Name of the geometry column on the source table","default":"geom"},"source_fk_field":{"type":"string","format":"column-ref","description":"Name of the foreign key column on the source table pointing to the parent"},"aggregate_function":{"type":"string","enum":["union","collect","convex_hull","concave_hull"],"description":"PostGIS aggregation function: union (ST_Union, merges overlapping), collect (ST_Collect, groups without merging), convex_hull (smallest convex polygon), concave_hull (tighter boundary)","default":"union"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"Output geometry type constraint for the aggregate field","default":"MultiPolygon"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method for the aggregate field","default":"gist"}},"required":["source_table_id","source_fk_field"],"description":"Creates a derived/materialized geometry field on the parent table that automatically aggregates geometries from a source (child) table via triggers. When child rows are inserted/updated/deleted, the parent aggregate field is recalculated using the specified PostGIS aggregation function (ST_Union, ST_Collect, ST_ConvexHull, ST_ConcaveHull). Useful for materializing spatial boundaries from collections of points or polygons."},"SearchSpatialParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the geometry/geography column","default":"geom"},"geometry_type":{"type":"string","enum":["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection","Geometry"],"description":"PostGIS geometry type constraint","default":"Point"},"srid":{"type":"integer","description":"Spatial Reference System Identifier (e.g. 4326 for WGS84)","default":4326},"dimension":{"type":"integer","enum":[2,3,4],"description":"Coordinate dimension (2=XY, 3=XYZ, 4=XYZM)","default":2},"use_geography":{"type":"boolean","description":"Use geography type instead of geometry (for geodetic calculations on the sphere)","default":false},"index_method":{"type":"string","enum":["gist","spgist"],"description":"Spatial index method","default":"gist"}},"description":"Adds a PostGIS geometry or geography column with a spatial index (GiST or SP-GiST). Supports configurable geometry types (Point, Polygon, etc.), SRID, and dimensionality. The graphile-postgis plugin auto-detects geometry/geography columns by codec type for spatial filtering (ST_Contains, ST_DWithin, bbox operators)."},"SearchTrgmParams":{"type":"object","properties":{"fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to create trigram indexes on (fields must already exist on the table)"}},"required":["fields"],"description":"Creates GIN trigram indexes (gin_trgm_ops) on specified text/citext fields for fuzzy LIKE/ILIKE/similarity search. Adds @trgmSearch smart tag for PostGraphile integration. Fields must already exist on the table."},"SearchUnifiedParams":{"type":"object","properties":{"full_text_search":{"type":"object","description":"SearchFullText parameters. Omit to skip FTS setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"search"},"source_fields":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"weight":{"type":"string","enum":["A","B","C","D"]},"lang":{"type":"string"}},"required":["field"]}},"search_score_weight":{"type":"number","default":1}}},"bm25":{"type":"object","description":"SearchBm25 parameters. Omit to skip BM25 setup.","properties":{"field_name":{"type":"string","format":"column-ref"},"text_config":{"type":"string","default":"english"},"k1":{"type":"number"},"b":{"type":"number"},"search_score_weight":{"type":"number","default":1}}},"embedding":{"type":"object","description":"SearchVector parameters. Omit to skip embedding setup.","properties":{"field_name":{"type":"string","format":"column-ref","default":"embedding"},"dimensions":{"type":"integer","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"]},"metric":{"type":"string","enum":["cosine","l2","ip"]},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"}},"embedding_model":{"type":"string","description":"Embedding model identifier. When null, the worker falls back to runtime config."},"embedding_provider":{"type":"string","description":"Embedding provider name. When null, the worker falls back to runtime config."},"search_score_weight":{"type":"number","default":1},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue","default":"embedding:chunk_record"}}}}},"embedding_text_field":{"type":"string","format":"column-ref","description":"Name of the composite text field created for embedding input","default":"embedding_text"},"composite_format":{"type":"string","enum":["labeled","plain"],"description":"Output format for the composite text field","default":"labeled"},"trgm_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Field names to tag with @trgmSearch for fuzzy/typo-tolerant matching"},"search_config":{"type":"object","description":"Unified search score configuration written to @searchConfig smart tag","properties":{"weights":{"type":"object","description":"Per-algorithm weights: {tsv: 1.5, bm25: 1.0, pgvector: 0.8, trgm: 0.3}"},"normalization":{"type":"string","enum":["linear","sigmoid"],"description":"Score normalization strategy","default":"linear"},"boost_recent":{"type":"boolean","description":"Enable recency boost for search results","default":false},"boost_recency_field":{"type":"string","format":"column-ref","description":"Timestamp field for recency boost (e.g. created_at, updated_at)"},"boost_recency_decay":{"type":"number","description":"Decay rate for recency boost (0-1, lower = faster decay)","default":0.5}}}},"description":"Composite node type that orchestrates multiple search modalities (full-text search, BM25, embeddings, trigram) on a single table. Configures per-table search score weights, normalization strategy, and recency boost via the @searchConfig smart tag."},"SearchVectorParams":{"type":"object","properties":{"field_name":{"type":"string","format":"column-ref","description":"Name of the vector column","default":"embedding"},"dimensions":{"type":"integer","description":"Vector dimensions (e.g. 384, 768, 1536, 3072)","default":768},"index_method":{"type":"string","enum":["hnsw","ivfflat"],"description":"Index type for similarity search","default":"hnsw"},"metric":{"type":"string","enum":["cosine","l2","ip"],"description":"Distance metric (cosine, l2, ip)","default":"cosine"},"index_options":{"type":"object","description":"Index-specific options. HNSW: {m, ef_construction}. IVFFlat: {lists}.","default":{}},"source_fields":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"Column names that feed the embedding. Used by stale trigger to detect content changes."},"embedding_model":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"embedding_provider":{"$ref":"#/$defs/shared-ac9a0977fa"},"enqueue_job":{"type":"boolean","description":"Auto-create trigger that enqueues embedding generation jobs","default":true},"job_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the job queue. Must match a registered function definition when function_module is installed.","default":"embedding:embed_record"},"chunks":{"type":"object","description":"Chunking configuration for long-text embedding. Creates an embedding_chunks record that drives automatic text splitting and per-chunk embedding. Omit to skip chunking.","properties":{"content_field_name":{"type":"string","format":"column-ref","description":"Name of the text content column in the chunks table","default":"content"},"chunk_size":{"type":"integer","description":"Maximum number of characters per chunk","default":1000},"chunk_overlap":{"type":"integer","description":"Number of overlapping characters between consecutive chunks","default":200},"chunk_strategy":{"type":"string","enum":["fixed","sentence","paragraph","semantic"],"description":"Strategy for splitting text into chunks","default":"fixed"},"metadata_fields":{"$ref":"#/$defs/shared-3a33134347"},"enqueue_chunking_job":{"type":"boolean","description":"Whether to auto-enqueue a chunking job on insert/update","default":true},"chunking_task_name":{"type":"string","format":"function-ref","description":"Task identifier for the chunking job queue. Must match a registered function definition when function_module is installed.","default":"embedding:chunk_record"}}}},"description":"Adds a vector embedding column with HNSW or IVFFlat index for similarity search. Supports configurable dimensions, distance metrics (cosine, l2, ip), per-field {field_name}_updated_at timestamp tracking (read-only in GraphQL), and automatic job enqueue triggers for embedding generation."},"TableOrganizationSettingsParams":{"type":"object","properties":{},"description":"Creates an organization settings table with standard business fields (legal_name, address fields). Uses AuthzEntityMembership for access control."},"TableUserProfilesParams":{"type":"object","properties":{},"description":"Creates a user profiles table with standard profile fields (profile_picture, bio, first_name, last_name, tags, desired). Uses AuthzDirectOwner for edit access and AuthzAllowAll for select."},"TableUserSettingsParams":{"type":"object","properties":{},"description":"Creates a user settings table for user-specific configuration. Uses AuthzDirectOwner for access control."},"TriggerCondition":{"type":"object","properties":{"field":{"type":"string","description":"Column name (validated against the table)."},"op":{"enum":["=","!=",">","<",">=","<=","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS DISTINCT FROM"],"description":"Comparison operator."},"value":{"description":"Comparison value. Type is resolved from the column definition."},"row":{"enum":["NEW","OLD"],"description":"Row reference (default: NEW)."},"ref":{"type":"object","properties":{"field":{"type":"string"},"row":{"enum":["NEW","OLD"]}},"description":"Column reference for field-to-field comparison (alternative to value)."},"AND":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with AND."},"OR":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"},"description":"Array of conditions combined with OR."},"NOT":{"$ref":"#/$defs/TriggerCondition","description":"Negated condition."}},"description":"Recursive condition type for compound trigger WHEN clauses. Leaf conditions specify {field, op, value?, row?, ref?}. Combinators nest via AND, OR, NOT."},"shared-001d8d7cd3":{"anyOf":[{"required":["obj_table_id"]},{"required":["obj_schema","obj_table"]}]},"shared-0022037ad5":{"if":{"properties":{"$type":{"const":"AuthzValueAllowed"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueAllowedParams"}},"required":["data"]}},"shared-0165627a32":{"type":"array","items":{"type":"string"},"description":"Capability names of any kind (capability, level, ...) merged into the same mask"},"shared-0379afb669":{"if":{"properties":{"$type":{"const":"AuthzDirectOwnerAny"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerAnyParams"}},"required":["data"]}},"shared-040cc005ef":{"type":"array","minItems":1,"items":{"$ref":"#/$defs/AuthzExpression"}},"shared-066977ff2f":{"anyOf":[{"required":["obj_field"]},{"required":["obj_field_id"]}]},"shared-078ee82414":{"properties":{"$type":{"const":"CheckOneOf"}},"required":["$type"]},"shared-0968d06284":{"type":"string","description":"Schema of the join table (or use obj_table_id)"},"shared-0a22d2c3f6":{"type":"string","description":"Single column name for the index."},"shared-0d918e14b9":{"type":"string","description":"Embedding model identifier (e.g. \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"shared-0ed784651d":{"type":"array","items":{"type":"string","enum":["fulltext","bm25","trigram"]},"description":"Text search indexes to create on the chunks content column. Omit to mirror the parent table's text search indexes. Set explicitly to override."},"shared-11a9ffe32a":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"shared-1232a5e8ca":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","description":"Version identifier (e.g., \"thumb\", \"preview\", \"hero\")"},"width":{"type":"integer","description":"Target width in pixels"},"height":{"type":"integer","description":"Target height in pixels"},"fit":{"type":"string","enum":["cover","contain","fill","inside","outside"],"description":"Resize fitting strategy","default":"cover"},"format":{"type":"string","enum":["jpeg","png","webp","avif"],"description":"Output image format","default":"webp"},"quality":{"type":"integer","description":"Output quality (1-100)","default":80}},"required":["name"]},"description":"Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Optional: when omitted the worker resolves the default ladder at job time (thumbnail 160x160 cover, then small 320, medium 640, large 1280 and xlarge 1920 wide, WebP quality 80), so a later change to the default reaches tables already provisioned. A version larger than the source is skipped rather than upscaled.","minItems":1},"shared-13aff2afe8":{"type":"string","description":"The member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-152f619c56":{"if":{"properties":{"$type":{"const":"AuthzDenyAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDenyAllParams"}}}},"shared-1a317ed066":{"type":"string","format":"column-ref","description":"Column on the trigger table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger."},"shared-1afc3ee393":{"if":{"properties":{"$type":{"const":"AuthzNotReadOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzNotReadOnlyParams"}},"required":["data"]}},"shared-1c8d46d43b":{"properties":{"$type":{"const":"CheckNotEqual"}},"required":["$type"]},"shared-1d336e787f":{"if":{"properties":{"$type":{"const":"AuthzValueExists"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueExistsParams"}},"required":["data"]}},"shared-21a1ba9587":{"if":{"properties":{"$type":{"const":"AuthzAppMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMembershipParams"}}}},"shared-22f38cc906":{"type":"array","items":{"type":"string"},"description":"Operator classes for the index columns."},"shared-230094622e":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Used when entity_field is a FK (e.g., channel_id) rather than a direct entity_id. The generator validates all fields against metaschema within the same database_id.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, e.g., \"public\"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous)."},"obj_field":{"type":"string","description":"Column on the related table that holds the entity_id (e.g., \"entity_id\"). Required."}},"required":["obj_table","obj_field"]},"shared-2997c2f821":{"if":{"properties":{"$type":{"const":"AuthzSystemOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzSystemOnlyParams"}}}},"shared-2a834ba4ff":{"type":"string","description":"Index access method (e.g., \"BTREE\", \"GIN\", \"GIST\", \"HNSW\", \"BM25\")."},"shared-2c20767ba3":{"properties":{"$type":{"const":"CheckGreaterThan"}},"required":["$type"]},"shared-33af0ede37":{"type":"string","format":"column-ref","description":"Single column to compare against value (mutually exclusive with columns)"},"shared-347ff05f99":{"type":"boolean","description":"Whether to create a chunks table via ProcessChunks. Defaults to true when extraction is provided, false in direct mode. Set explicitly to override."},"shared-35954fc61d":{"if":{"properties":{"$type":{"const":"AuthzPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPeerOwnershipParams"}},"required":["data"]}},"shared-36ea8e912e":{"if":{"properties":{"$type":{"const":"AuthzDatabaseClaim"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDatabaseClaimParams"}}}},"shared-39f66ad592":{"if":{"properties":{"$type":{"const":"AuthzAllowAll"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAllowAllParams"}}}},"shared-3a33134347":{"type":"object","description":"Metadata fields from parent to copy into chunks"},"shared-3d0fa23a34":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"shared-411f8ee76d":{"type":"string","description":"Schema of the referenced table (or use ref_table_id)"},"shared-41591dfcf8":{"type":"object","description":"Typed bucket reference ({\"$ref\":\"bucket\",\"tags\":[...],\"type\":...}) for the bucket the source files live in, when it is not the record's own bucket_id (which payload_custom already carries). Stamped into the trigger payload at attach time and resolved to coordinates at dispatch.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"shared-462d3d2412":{"type":"string","description":"Name of the related table to look up entity_id from"},"shared-48649a3a43":{"type":"array","items":{"$ref":"#/$defs/TriggerCondition"}},"shared-51c1d9a5f0":{"type":"string","minLength":1,"not":{"const":"app"},"description":"Entity type prefix (e.g. 'org', 'channel', 'department'), resolved to its membership_type; use it instead of membership_type for readability."},"shared-5492e6a87c":{"type":"string","enum":["fulltext","bm25","trigram"]},"shared-55595a36d2":{"type":["array","object"],"items":{"type":"object"},"description":"Optional higher-level condition JSON applied to the referenced table (row alias d)"},"shared-5a2832df1c":{"type":"array","items":{"type":"string"},"description":"Array of column names for a multi-column index."},"shared-5a2b860e32":{"if":{"properties":{"$type":{"const":"AuthzMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberListParams"}},"required":["data"]}},"shared-5e11bfeb01":{"type":"boolean","description":"If true, require is_owner flag on current user membership"},"shared-6119be8d95":{"type":"array","items":{"type":"string"},"description":"Field names from parent to copy into chunk metadata"},"shared-626b0c3c0b":{"type":"array","items":{"$ref":"#/$defs/BlueprintFtsSource"},"description":"Source fields that feed into this tsvector."},"shared-637ef72440":{"type":"string","pattern":"^[01]+$","description":"Capability bits a member must hold, as a bit string. Capabilities or levels, when given, replace it."},"shared-6639e33d04":{"if":{"properties":{"$type":{"const":"AuthzComposite"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzCompositeParams"}}}},"shared-693097b0e5":{"if":{"properties":{"$type":{"const":"AuthzValueMatch"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzValueMatchParams"}},"required":["data"]}},"shared-698b2fd59a":{"type":"integer","minimum":2,"maximum":2147483647,"description":"The team kind: 2=org, 3+=dynamic entity types."},"shared-6ac44ac2ba":{"if":{"properties":{"$type":{"const":"AuthzDirectOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzDirectOwnerParams"}},"required":["data"]}},"shared-6adc1df48e":{"type":"string","description":"Optional schema name for disambiguation (falls back to top-level default)."},"shared-6b829f5502":{"type":"string","description":"Name of the related table to look up entity_id from (e.g., \"channels\"). Required."},"shared-6dbc2f5a83":{"if":{"properties":{"$type":{"const":"AuthzPublishable"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzPublishableParams"}}}},"shared-6ea79cf84b":{"type":"array","minItems":1,"description":"Join conditions between the protected row and the referenced table","items":{"type":"object","properties":{"local_column":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column on the protected table"},"ref_column":{"$ref":"#/$defs/shared-7539b204c0"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"shared-6eb30390ff":{"type":"string","enum":["INSERT","DELETE","UPDATE"]},"shared-7539b204c0":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the referenced table"},"shared-757c15800e":{"type":"string","description":"Name of the CHECK constraint."},"shared-7756a0ed5a":{"if":{"properties":{"$type":{"const":"AuthzRelatedEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedEntityMembershipParams"}},"required":["data"]}},"shared-787b8adf81":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Additional compound conditions beyond auto-generated filtering. Merged with the auto-generated conditions via AND."},"shared-7a53e1103e":{"type":"boolean","description":"Select sel_field from the related row instead of the team id; the platform's own related policies set it with sel_field \"id\"."},"shared-7edb884d72":{"type":"object","description":"FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger.","properties":{"obj_table":{"type":"string","description":"Name of the related table to look up entity_id from"},"obj_schema":{"type":"string","description":"Schema of the related table (user-facing name, optional)"},"obj_field":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"}},"required":["obj_table","obj_field"]},"shared-7f50b0e5b7":{"type":"string","description":"Name of the referenced table (or use ref_table_id)"},"shared-82428b2411":{"type":"string","description":"Extraction provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"shared-8358853df2":{"properties":{"$type":{"const":"CheckLessThan"}},"required":["$type"]},"shared-8763e18b77":{"anyOf":[{"required":["membership_type"]},{"required":["entity_type"]},{"required":["sprt_schema","sprt_table"]}]},"shared-88656ecafa":{"type":"string","format":"column-ref","description":"Column name for conditional WHEN clause (fires only when field equals condition_value)"},"shared-8881b94a41":{"if":{"properties":{"$type":{"const":"AuthzTemporal"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzTemporalParams"}}}},"shared-8aa6c03738":{"type":"object","description":"Typed bucket reference for where derived outputs (thumbnails, resized variants, extracted assets) are written. Stamped into the trigger payload at attach time and resolved to coordinates at dispatch, so the function never selects a bucket.","properties":{"$ref":{"type":"string","enum":["bucket"]},"tags":{"type":"array","items":{"type":"string"}},"key":{"type":"string"},"type":{"$ref":"#/$defs/shared-f4262069e5"}},"required":["$ref"]},"shared-8cc6b29877":{"type":"string","format":"uuid","description":"UUID of the referenced table (alternative to ref_schema/ref_table)"},"shared-8cef65cfda":{"type":"object","additionalProperties":{"oneOf":[{"type":"string","format":"column-ref"},{"type":"object","properties":{"field":{"type":"string","format":"column-ref"},"path":{"$ref":"#/$defs/shared-9b5e4c440f"}},"required":["field","path"]}]},"description":"Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({\"field\": \"upload\", \"path\": [\"key\"]}). Defaults to the four file columns, or to the file_field document when file_field is set."},"shared-9146e81ef6":{"type":"string","format":"uuid","description":"UUID of the join table (alternative to obj_schema/obj_table)"},"shared-927486214a":{"type":"boolean","description":"If true, require is_admin flag"},"shared-9572999fa8":{"type":"string","description":"The schema of the member list the policy reads. With a team kind the backend resolves it and replaces this value."},"shared-9649b5119d":{"type":"array","items":{"type":"object","properties":{"mime_patterns":{"type":"array","items":{"type":"string"},"minItems":1,"description":"MIME type LIKE patterns this route takes, e.g. ['application/vnd.openxmlformats-officedocument.%']."},"task_identifier":{"type":"string","format":"function-ref","description":"Job task identifier of the function that extracts these MIME types"},"extraction_model":{"type":"string","description":"Extraction model for this route; the node's when omitted"},"extraction_provider":{"type":"string","description":"Extraction provider for this route; the node's when omitted"},"queue_name":{"type":"string","description":"Job queue name for this route; the node's when omitted"},"max_attempts":{"type":"integer","description":"Maximum retry attempts for this route; the node's when omitted"},"priority":{"type":"integer","description":"Job priority for this route; the node's when omitted"}},"required":["mime_patterns","task_identifier"]},"description":"MIME types sent to another extraction function. A file runs the first route whose mime_patterns match it; the node's own mime_patterns and task_identifier take only the files no route matched, so one file never runs two functions. Every route writes the node's text_field and metadata_field, and shares its file_field, events, trigger_conditions and billing scope. A task is named once across the node and its routes (PROCESS_EXTRACTION_DUPLICATE_ROUTE_TASK). Example: [{\"mime_patterns\": [\"application/vnd.openxmlformats-officedocument.%\"], \"task_identifier\": \"office:extract_text\"}]."},"shared-968a890679":{"if":{"properties":{"$type":{"const":"AuthzOrgHierarchy"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzOrgHierarchyParams"}},"required":["data"]}},"shared-9b5e4c440f":{"type":"array","items":{"type":"string"},"minItems":1},"shared-9d6147637c":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name referencing the entity (e.g., entity_id, org_id)"},"shared-a0bfcadf85":{"type":"array","items":{"type":"string"},"description":"Column names that form the unique constraint."},"shared-a0d2b7ccf1":{"type":"object","description":"Text extraction configuration. When present, the node composes ProcessExtraction (output fields, MIME-conditional trigger on queue extraction with 5 attempts, and on a storage files table the _write_extraction writer) and configures SearchVector with the text field as source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction).","properties":{"text_field":{"type":"string","format":"column-ref","description":"Field to store extracted text/markdown","default":"extracted_text"},"metadata_field":{"type":"string","format":"column-ref","description":"JSONB field for extraction metadata (page count, language, etc.)","default":"extracted_metadata"},"routes":{"type":"array","items":{"type":"object","properties":{"mime_patterns":{"$ref":"#/$defs/shared-9b5e4c440f"},"task_identifier":{"type":"string","format":"function-ref"}},"required":["mime_patterns","task_identifier"]},"description":"MIME types sent to another extraction function, as ProcessExtraction.routes: the first matching route takes a file, and the node's own mime_patterns and task take the rest."}}},"shared-a5a04dd84a":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberList"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberListParams"}},"required":["data"]}},"shared-a9d73b8ba7":{"if":{"properties":{"$type":{"const":"AuthzMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzMemberOwnerParams"}}}},"shared-ab071ec2f8":{"type":"boolean","description":"If true, require is_owner flag"},"shared-ab15ceab40":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations."},"shared-ac9a0977fa":{"type":"string","description":"Embedding provider name (e.g. \"ollama\", \"openai\"). When null, the worker falls back to runtime config."},"shared-aced6572ca":{"if":{"properties":{"$type":{"const":"AuthzHumanOnly"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzHumanOnlyParams"}}}},"shared-ad437cb66f":{"type":"string","format":"column-ref","x-column-scope":"local"},"shared-ad8f69741a":{"type":"string","description":"Optional schema name override."},"shared-af38a22089":{"enum":["AuthzAllowAll","AuthzAppMemberOwner","AuthzAppMembership","AuthzComposite","AuthzDatabaseClaim","AuthzDenyAll","AuthzDirectOwner","AuthzDirectOwnerAny","AuthzEntityMembership","AuthzFilePath","AuthzHumanOnly","AuthzMemberList","AuthzMemberOwner","AuthzNotReadOnly","AuthzOrgHierarchy","AuthzPeerOwnership","AuthzPublishable","AuthzRelatedEntityMembership","AuthzRelatedMemberList","AuthzRelatedMemberOwner","AuthzRelatedPeerOwnership","AuthzSystemOnly","AuthzTemporal","AuthzValueAllowed","AuthzValueExists","AuthzValueMatch"]},"shared-b0876b5627":{"type":"array","items":{"type":"string"},"description":"Achievement level names to require (kind=level catalog rows, merged into the same mask)"},"shared-b1944d8f7b":{"description":"Allowed values as a constant list, or a local column name containing the allowed values","anyOf":[{"type":"string","format":"column-ref","x-column-scope":"local","description":"Local column name containing allowed values"},{"type":"array","items":{"type":["string","boolean","number","null"]},"description":"Constant list of allowed values. Element JSON type is preserved: booleans/numbers emit typed constants (e.g. [true] -> TRUE, [5] -> 5), strings emit text literals."}]},"shared-b297346d46":{"if":{"properties":{"$type":{"const":"AuthzRelatedPeerOwnership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedPeerOwnershipParams"}},"required":["data"]}},"shared-b68f53d1ed":{"type":"integer","description":"The width the mask is padded to; by default the length of the mask."},"shared-bb55f34041":{"type":"boolean","description":"Whether this is a unique index."},"shared-bc381c03de":{"type":"object","properties":{"roles":{"type":"array","items":{"type":"string"}},"privileges":{"type":"array","items":{}}},"required":["roles","privileges"]},"shared-c5c620bfe3":{"type":"string","description":"Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. A zero mask requires nothing."},"shared-c9b32dbf00":{"type":"string","description":"Embedding model identifier (e.g. \"nomic-embed-text\", \"text-embedding-3-small\", \"clip-vit-base-patch32\"). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config (llm_module / env vars)."},"shared-ca5d04c28d":{"if":{"properties":{"$type":{"const":"AuthzEntityMembership"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzEntityMembershipParams"}},"required":["data"]}},"shared-cc52e308f2":{"anyOf":[{"$ref":"#/$defs/TriggerCondition"},{"$ref":"#/$defs/shared-48649a3a43"}],"description":"Compound conditions for the trigger WHEN clause. Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema. Cannot be combined with condition_field or watch_fields."},"shared-cd4dc6cdf6":{"type":"string","description":"Name of the join table (or use obj_table_id)"},"shared-cf7316ac6e":{"type":"array","items":{"type":"string"},"description":"MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%']. Defaults to ['image/%'] in direct mode and to ['application/pdf', 'text/%'] in extract mode."},"shared-d3e6ac0b5d":{"type":"boolean","description":"If true, require is_admin flag on current user membership"},"shared-d4553f7be9":{"type":"string","format":"column-ref","description":"Column on the related table that holds the entity_id"},"shared-d85a10e177":{"type":"object","description":"Reference to a table an installed module generated, resolved during blueprint construction (alternative to ref_table_id / ref_schema + ref_table)","properties":{"type":{"type":"string","description":"Module type owning the table, e.g. \"agent\""},"table":{"type":"string","description":"Logical table key within the module, e.g. \"thread\""},"scope":{"type":"string","description":"Scope of the module instance, e.g. \"app\" or \"org\""},"prefix":{"type":"string","description":"Prefix of the module instance, for entity-scoped installations"}},"required":["type","table"]},"shared-d8e76848ea":{"type":"string","format":"uuid","description":"UUID of field on join table (alternative to obj_field)"},"shared-db0e2e6361":{"type":"string","format":"uuid","description":"Table being referenced by the FK"},"shared-dfbaf50fc6":{"type":"string","format":"column-ref","x-column-scope":"local","description":"Column name on protected table referencing the join table"},"shared-e1125a4a5e":{"type":"string","description":"Scope of the module instance (e.g. \"app\", \"org\"). Required when the database installs the module at more than one scope."},"shared-e6dbbbcd8d":{"type":"string","enum":["c","r","n","d","a"],"description":"FK delete action: c=CASCADE, r=RESTRICT, n=SET NULL, d=SET DEFAULT, a=NO ACTION. Required."},"shared-e772a2f2a5":{"type":"object","additionalProperties":{},"description":"Additional index-specific options."},"shared-eb6d498d14":{"if":{"properties":{"$type":{"const":"AuthzAppMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzAppMemberOwnerParams"}}}},"shared-eb860e1011":{"type":"string","enum":["INSERT","UPDATE","DELETE"]},"shared-ee69c55731":{"type":"string","description":"Name of the tsvector field on the table."},"shared-effacc6003":{"type":"object","description":"A further row that must exist in a third table, joined to the referenced row (alias b unless ref_alias says otherwise).","properties":{"ref_table_id":{"type":"string","format":"uuid","description":"UUID of the third table (alternative to ref_schema/ref_table)"},"ref_schema":{"type":"string","description":"Schema of the third table (or use ref_table_id)"},"ref_table":{"type":"string","description":"Name of the third table (or use ref_table_id)"},"ref_alias":{"type":"string","description":"Alias of the third table in the join","default":"b"},"join":{"type":"array","description":"Join conditions between the referenced row and the third table","items":{"type":"object","properties":{"local_column":{"$ref":"#/$defs/shared-7539b204c0"},"ref_column":{"type":"string","format":"column-ref","x-column-scope":"foreign","description":"Column on the third table"},"operator":{"type":"string","enum":["=","!=",">","<",">=","<="],"default":"=","description":"Join operator"}},"required":["local_column","ref_column"],"additionalProperties":false}},"conditions":{"type":["array","object"],"items":{"type":"object"},"description":"Optional condition JSON applied to the third table"}},"anyOf":[{"required":["ref_table_id"]},{"required":["ref_schema","ref_table"]}],"additionalProperties":false},"shared-f35a015b21":{"type":"string","description":"Optional custom name for the index."},"shared-f4262069e5":{"type":"string","enum":["public","private","temp"]},"shared-f5f12fa8f6":{"if":{"properties":{"$type":{"const":"AuthzRelatedMemberOwner"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzRelatedMemberOwnerParams"}},"required":["data"]}},"shared-f7ad90b1e2":{"type":"string","description":"Value to compare against condition_field in WHEN clause"},"shared-f862b57bdc":{"type":"string","description":"Extraction model identifier (e.g. a vision model for OCR, an LLM for structured extraction). Included in the job payload so the worker knows which model to use. When null, the worker falls back to runtime config."},"shared-f90494132b":{"type":"string","format":"function-ref","description":"Job task identifier for the worker. In direct mode this is the embedding worker (default embedding:process_file_embedding); in extract mode this is the extraction worker (default document:extract_file_text)."},"shared-fe3f452ee5":{"type":"array","items":{"type":"string","format":"column-ref"},"description":"For UPDATE triggers, only fire when these fields change (uses DISTINCT FROM)"},"shared-ff315e2ff3":{"if":{"properties":{"$type":{"const":"AuthzFilePath"}},"required":["$type"]},"then":{"properties":{"data":{"$ref":"#/$defs/AuthzFilePathParams"}},"required":["data"]}}}}; diff --git a/packages/node-type-registry/src/blueprint-types.generated.ts b/packages/node-type-registry/src/blueprint-types.generated.ts index 318a01db09..ef846ea548 100644 --- a/packages/node-type-registry/src/blueprint-types.generated.ts +++ b/packages/node-type-registry/src/blueprint-types.generated.ts @@ -87,6 +87,7 @@ export interface CheckOwnedRelationParams { /* Optional link column additionally restricted regardless of ownership (e.g. a bucket type) */target_type_field_name?: string; /* Value target_type_field_name must equal */target_type_value?: string; /* Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database */allow_owner_tier?: boolean; + /* Admit rows owned by any frame on the referencing row's own scope-frame chain (its own scopes, then the platform database's chain) for this column, for pointers naming a definition published UP the hierarchy — the shared platform function image a tenant route targets. Ancestry only: a peer or another keyed owner is on no chain. Requires owner_key_field_name */allow_frame_chain?: boolean; }[]; /* How many pointers a row must set: exactly_one for a polymorphic target (route → api OR site OR bucket), all for a junction/join row of a has-and-belongs-to-many relation (and for a mandatory belongs-to), any for optional pointers that are only checked when set */ arity?: 'exactly_one' | 'all' | 'any'; @@ -131,8 +132,11 @@ export interface DataBulkParams { export interface DataCapabilitiesParams { /* Name of the bit(n) mask column to create on this table. */ field?: string; - /* Selects the capabilities module whose bit numbering the mask is measured in, by scope (e.g. "app", "org") or by table prefix. Required only when the database has more than one; several with no selector raises naming the candidates. */ - capabilities?: string; + /* Selector for the capabilities module whose bit numbering the mask is measured in, e.g. {"scope": "org"}. Every key given must match exactly one module; none or several raises naming the candidates. Required only when the database has more than one. */ + capabilities?: { + /* Scope the module is installed at ("app", "org", or an entity type prefix). */scope?: string; + /* Table prefix of the module instance; rarely needed since prefix follows scope. */prefix?: string; + }; /* Capability names every row requires unless told otherwise, resolved to a literal mask and baked into the column default. Omitted means a zero mask: requires nothing. */ default?: string[]; /* Who writes the mask: "direct" the writer, bounded by the subset guard; "derived" the mapping row named by from_column, stamped by generated triggers and hidden from mutations. */ @@ -336,7 +340,7 @@ export interface DataInflectionParams { /* Inflection operations to apply in order */ ops: ('plural' | 'singular' | 'camel' | 'pascal' | 'dashed' | 'slugify' | 'underscore' | 'lower' | 'upper')[]; } -/** BEFORE INSERT trigger that copies specified fields from a parent table via a foreign key. The parent row is looked up through RLS (SECURITY INVOKER), so the insert fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files. */ +/** BEFORE INSERT OR UPDATE trigger that copies specified fields from a parent table via a foreign key; on UPDATE the fields are re-copied only when the parent FK changes. The parent row is looked up through RLS (SECURITY INVOKER), so the insert or update fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files. */ export interface DataInheritFromParentParams { /* Name of the FK field on this table that references the parent (e.g. bucket_id) */ parent_fk_field: string; @@ -638,7 +642,7 @@ export interface LimitEnforceCounterParams { /* Which DML events to attach triggers for */ events?: ('INSERT' | 'DELETE' | 'UPDATE')[]; } -/** Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE INSERT trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). */ +/** Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). Gate INSERT and UPDATE when a row can reach the gated state after creation, and narrow the gate with conditions when only some of the table's rows are the gated feature. */ export interface LimitEnforceFeatureParams { /* Cap name representing this feature (must match a limit_caps_defaults entry with max=0 or max=1) */ feature_name: string; @@ -652,6 +656,10 @@ export interface LimitEnforceFeatureParams { /* Schema of the related table (user-facing name, e.g., "public"). Optional — if omitted, resolved by table name within the same database_id (raises error if ambiguous). */obj_schema?: string; /* Column on the related table that holds the entity_id (e.g., "entity_id"). Required. */obj_field: string; }; + /* Which DML events the cap gates. UPDATE is required when a row can reach the gated state after creation (e.g. a discriminator flipped from an ungated value to a gated one). DELETE is not supported: a cap answers whether a row may exist. */ + events?: ('INSERT' | 'UPDATE')[]; + /* Compound conditions for the trigger WHEN clause, so the cap gates a subset of rows rather than the whole table (e.g. only the rows a customer authors on a table the platform also writes). Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema. */ + conditions?: TriggerCondition | TriggerCondition[]; } /** Attaches a BEFORE trigger that calls check_rate_limit() to enforce sliding-window rate limits before allowing mutations. The function checks all three scopes (entity, actor-in-entity, actor) in a single call; which scopes are actually enforced is controlled by what rows exist in rate_window_limits (plan-based config). Requires a provisioned meter_rate_limits_module and billing_module for the target database. */ export interface LimitEnforceRateParams { @@ -692,6 +700,8 @@ export interface LimitTrackUsageParams { quantity?: number; /* Which DML events to attach triggers for */ events?: ('INSERT' | 'DELETE' | 'UPDATE')[]; + /* With INSERT tracked, also attach a BEFORE INSERT gate on check_billing_quota that refuses a row past the allowance (BILLING_QUOTA_EXCEEDED), like the invocation quota gate. Off (default), rows past the allowance are inserted and their charge is refused. A slug with no meter row is never refused. */ + enforce?: boolean; } /** * =========================================================================== @@ -965,6 +975,8 @@ export interface JobTriggerParams { job_key?: string; /* Job queue name for routing to specific workers */ queue_name?: string; + /* Column whose value keys the job queue, so the queue name becomes ":". A named queue is held for the whole job, so a shared literal queue serializes every job that uses it; keying on the work's subject keeps same-subject jobs ordered while unrelated subjects run in parallel. */ + queue_key_field?: string; /* Job priority (lower = higher priority) */ priority?: number; /* Delay before job runs as PostgreSQL interval (e.g., 30 seconds, 5 minutes) */ @@ -982,6 +994,8 @@ export interface JobTriggerParams { export interface ProcessChunksParams { /* Name of the text content column in the chunks table */ content_field_name?: string; + /* Parent columns the chunks are cut from. When set, the enqueue triggers fire only once one of them is populated (INSERT) or changed (UPDATE), and the worker chunks exactly those columns. Omit to chunk every readable content column on every write. */ + source_fields?: string[]; /* Maximum number of characters per chunk */ chunk_size?: number; /* Number of overlapping characters between consecutive chunks */ @@ -1015,7 +1029,32 @@ export interface ProcessChunksParams { /* Task identifier for the chunking job queue */ chunking_task_name?: string; } -/** Creates extraction output fields and a job trigger for file text extraction. Fires when a file is uploaded (status = 'uploaded') or on INSERT. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks. */ +/** Enqueues a tenant-registered task when a file on a storage files table reaches status = 'uploaded' and generates the result writer the task calls back over the function lane. The task must already be registered for the database (register_function with scope database); the node is refused otherwise. */ +export interface ProcessCustomParams { + /* Task identifier of the tenant-registered function (namespace:name). Must resolve through the function registry for this database at provisioning time. */ + task_identifier: string; + /* Optional jsonb field on the files table that receives the result the task hands to the generated writer. When omitted the writer only records the uploaded → processed transition. */ + result_field?: string; + /* Optional MIME type LIKE patterns to match. Multiple patterns are OR'd together. When omitted every uploaded file is processed. */ + mime_patterns?: string[]; + /* Additional compound conditions beyond auto-generated filtering. Merged with the auto-generated conditions via AND. */ + trigger_conditions?: TriggerCondition | TriggerCondition[]; + /* Column on the files table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger. */ + entity_field?: string; + /* FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger. */ + entity_lookup?: { + /* Name of the related table to look up entity_id from */obj_table: string; + /* Schema of the related table (user-facing name, optional) */obj_schema?: string; + /* Column on the related table that holds the entity_id */obj_field: string; + }; + /* Job queue name for the task */ + queue_name?: string; + /* Maximum number of retry attempts */ + max_attempts?: number; + /* Job priority (lower = higher priority) */ + priority?: number; +} +/** Creates extraction output fields and a job trigger for file text extraction. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) and writes the result back to the configured output fields. Typically used upstream of ProcessFileEmbedding or ProcessChunks. */ export interface ProcessExtractionParams { /* Field to store extracted text/markdown */ text_field?: string; @@ -1027,11 +1066,21 @@ export interface ProcessExtractionParams { extraction_provider?: string; /* MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['application/pdf', 'text/%'], ['application/vnd.openxmlformats%']. */ mime_patterns?: string[]; + /* MIME types sent to another extraction function. A file runs the first route whose mime_patterns match it; the node's own mime_patterns and task_identifier take only the files no route matched, so one file never runs two functions. Every route writes the node's text_field and metadata_field, and shares its file_field, events, trigger_conditions and billing scope. A task is named once across the node and its routes (PROCESS_EXTRACTION_DUPLICATE_ROUTE_TASK). Example: [{"mime_patterns": ["application/vnd.openxmlformats-officedocument.%"], "task_identifier": "office:extract_text"}]. */ + routes?: { + /* MIME type LIKE patterns this route takes, e.g. ['application/vnd.openxmlformats-officedocument.%']. */mime_patterns: string[]; + /* Job task identifier of the function that extracts these MIME types */task_identifier: string; + /* Extraction model for this route; the node's when omitted */extraction_model?: string; + /* Extraction provider for this route; the node's when omitted */extraction_provider?: string; + /* Job queue name for this route; the node's when omitted */queue_name?: string; + /* Maximum retry attempts for this route; the node's when omitted */max_attempts?: number; + /* Job priority for this route; the node's when omitted */priority?: number; + }[]; /* Job task identifier for the extraction worker */ task_identifier?: string; - /* Trigger events that fire the job */ + /* Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested). */ events?: ('INSERT' | 'UPDATE')[]; - /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */ + /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and text_field (created as jsonb) and metadata_field hold one entry per element, as jsonb objects keyed by the element's object key. */ file_field?: string; /* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */ payload_custom?: { @@ -1054,7 +1103,7 @@ export interface ProcessExtractionParams { /* Job priority (lower = higher priority) */ priority?: number; } -/** Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies. */ +/** Generic, MIME-scoped embedding node for file tables. Supports two modes: direct (whole-file to single vector, e.g. CLIP for images) when extraction is omitted, or extract (file to text to chunks to per-chunk vectors) when extraction config is provided; extract mode composes ProcessExtraction for the text (its task, MIME rule, queue and, on a storage files table, its result writer). On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. Composes SearchVector + JobTrigger + ProcessChunks (enabled by default in extract mode) internally. Multiple instances can coexist on the same table with different MIME scopes, field names, and embedding strategies. */ export interface ProcessFileEmbeddingParams { /* Name of the vector embedding column */ field_name?: string; @@ -1072,13 +1121,13 @@ export interface ProcessFileEmbeddingParams { embedding_model?: string; /* Embedding provider name (e.g. "ollama", "openai"). When null, the worker falls back to runtime config. */ embedding_provider?: string; - /* MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%']. */ + /* MIME type LIKE patterns to match. Multiple patterns are OR'd together. Examples: ['image/%'], ['application/pdf', 'text/%'], ['audio/%']. Defaults to ['image/%'] in direct mode and to ['application/pdf', 'text/%'] in extract mode. */ mime_patterns?: string[]; - /* Job task identifier for the worker. In direct mode this is the embedding worker; in extract mode this is the extraction worker. */ + /* Job task identifier for the worker. In direct mode this is the embedding worker (default embedding:process_file_embedding); in extract mode this is the extraction worker (default document:extract_file_text). */ task_identifier?: string; - /* Trigger events that fire the job */ + /* Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested). */ events?: ('INSERT' | 'UPDATE')[]; - /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */ + /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_FILE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element. */ file_field?: string; /* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */ payload_custom?: { @@ -1108,10 +1157,14 @@ export interface ProcessFileEmbeddingParams { /* Schema of the related table (user-facing name, optional) */obj_schema?: string; /* Column on the related table that holds the entity_id */obj_field: string; }; - /* Text extraction configuration. When present, the generator creates extraction output fields on the table and configures SearchVector with source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction). */ + /* Text extraction configuration. When present, the node composes ProcessExtraction (output fields, MIME-conditional trigger on queue extraction with 5 attempts, and on a storage files table the _write_extraction writer) and configures SearchVector with the text field as source_fields + stale tracking. When absent, the node operates in direct mode (single vector per file, no text extraction). */ extraction?: { /* Field to store extracted text/markdown */text_field?: string; /* JSONB field for extraction metadata (page count, language, etc.) */metadata_field?: string; + /* MIME types sent to another extraction function, as ProcessExtraction.routes: the first matching route takes a file, and the node's own mime_patterns and task take the rest. */routes?: { + mime_patterns: string[]; + task_identifier: string; + }[]; }; /* Whether to create a chunks table via ProcessChunks. Defaults to true when extraction is provided, false in direct mode. Set explicitly to override. */ include_chunks?: boolean; @@ -1127,7 +1180,7 @@ export interface ProcessFileEmbeddingParams { /* Task identifier for the chunking job queue */chunking_task_name?: string; }; } -/** Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_image_embedding', direct mode (no extraction). Accepts all ProcessFileEmbedding parameters — any overrides are forwarded through. */ +/** Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=['image/%'], task_identifier='embedding:process_file_embedding', direct mode only: there is no image extraction (OCR) worker, so extraction is refused. Every other parameter is forwarded through. */ export interface ProcessImageEmbeddingParams { /* Name of the vector embedding column */ field_name?: string; @@ -1147,11 +1200,11 @@ export interface ProcessImageEmbeddingParams { embedding_provider?: string; /* MIME type LIKE patterns to match. Multiple patterns are OR'd together. */ mime_patterns?: string[]; - /* Job task identifier for the image embedding worker */ + /* Job task identifier for the image embedding worker. The payload is the file row (file_id, key, mime_type, bucket_id), so the task must be a record worker that reads the object itself — not embedding:process_image_embedding, which embeds an image_url it is handed. */ task_identifier?: string; /* Trigger events that fire the job */ events?: ('INSERT' | 'UPDATE')[]; - /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */ + /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. An array column (image[]/upload[]) is refused (PROCESS_IMAGE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element. */ file_field?: string; /* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */ payload_custom?: { @@ -1167,28 +1220,11 @@ export interface ProcessImageEmbeddingParams { /* Schema of the related table (user-facing name, optional) */obj_schema?: string; /* Column on the related table that holds the entity_id */obj_field: string; }; - /* Text extraction configuration. Forwarded to ProcessFileEmbedding. When present, enables extract mode (e.g., OCR for images). */ - extraction?: { - /* Field to store extracted text */text_field?: string; - /* JSONB field for extraction metadata */metadata_field?: string; - }; - /* Chunking configuration. Forwarded to ProcessFileEmbedding. Only meaningful when extraction is also provided. */ - chunks?: { - content_field_name?: string; - chunk_size?: number; - chunk_overlap?: number; - chunk_strategy?: 'fixed' | 'sentence' | 'paragraph' | 'semantic'; - metadata_fields?: { - [key: string]: unknown; - }; - enqueue_chunking_job?: boolean; - chunking_task_name?: string; - }; } -/** Creates a job trigger for image variant generation. Fires when an image file is uploaded (status = 'uploaded') or on INSERT. The external worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.) and stores them as new file records linked to the source image. */ +/** Creates a job trigger for image variant generation. On a storage files table it fires when the file reaches status = 'uploaded'; on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. The image worker generates resized, cropped, or reformatted versions (thumbnails, previews, WebP conversions, etc.), stores them beside the source object in the file's own bucket, and records each variant's name, key, format, dimensions and size: inside the file column's own document (its versions member) on a business table, in the manifest column on a storage files table. With no versions given the worker uses the default ladder (thumbnail, small, medium, large, xlarge), resolved when the job runs, and skips any version larger than the source. */ export interface ProcessImageVersionsParams { - /* Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Required — the blueprint must explicitly define what variants to generate. */ - versions: { + /* Array of version definitions. Each version specifies dimensions, format, and quality for a generated image variant. Optional: when omitted the worker resolves the default ladder at job time (thumbnail 160x160 cover, then small 320, medium 640, large 1280 and xlarge 1920 wide, WebP quality 80), so a later change to the default reaches tables already provisioned. A version larger than the source is skipped rather than upscaled. */ + versions?: { /* Version identifier (e.g., "thumb", "preview", "hero") */name: string; /* Target width in pixels */width?: number; /* Target height in pixels */height?: number; @@ -1196,13 +1232,15 @@ export interface ProcessImageVersionsParams { /* Output image format */format?: 'jpeg' | 'png' | 'webp' | 'avif'; /* Output quality (1-100) */quality?: number; }[]; - /* MIME type LIKE patterns to match. Defaults to all image types. */ + /* Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document. */ + versions_field?: string; + /* MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it. */ mime_patterns?: string[]; /* Job task identifier for the image processing worker */ task_identifier?: string; - /* Trigger events that fire the job */ + /* Trigger events that fire the job on a business table. Ignored on a storage files table, where the trigger is always the status transition to uploaded (INSERT is rejected there: the row is still requested). */ events?: ('INSERT' | 'UPDATE')[]; - /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. */ + /* Name of an upload/image domain column holding the file reference. When set, the trigger reads the object key, MIME type and bucket id out of that document (NEW. ->> 'key', ...) instead of requiring key/mime_type/bucket_id columns beside it, and the MIME patterns match against ->> 'mime'. The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and each element carries its own manifest in its versions member. */ file_field?: string; /* Custom payload key-to-source mapping for the job trigger. A source is either a column name or a read into a jsonb column ({"field": "upload", "path": ["key"]}). Defaults to the four file columns, or to the file_field document when file_field is set. */ payload_custom?: { @@ -1346,7 +1384,7 @@ export interface AuthzEntityMembershipParams { levels?: string[]; /* Capability names of any kind (capability, level, ...) merged into the same mask */ capabilities?: string[]; - /* Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capability/capabilities — both are ANDed. */ + /* Per-row required permissions (DataCapabilities): a bit(n) column on this table that lists the permissions the user must have. Narrows access row by row without joining a grant table; a zero mask requires nothing. Composes with capabilities — both checks must pass. */ mask_column?: string; /* If true, require is_admin flag */ is_admin?: boolean; @@ -1762,6 +1800,8 @@ export interface RelationBelongsToParams { delete_action: 'c' | 'r' | 'n' | 'd' | 'a'; /* Whether the FK field is NOT NULL */ is_required?: boolean; + /* Columns both tables carry that the referenced row must share with the referencing row (e.g. ["entity_id"], or ["project_id"] for a stage of the same project). Adds a hidden composite FK (field_name, ...scope_fields) -> target (id, ...scope_fields) plus the target unique key it needs, so a row cannot point at another scope's row even when it knows the id. */ + scope_fields?: string[]; } /** Creates a foreign key field on the target table referencing the source table. Inverse of RelationBelongsTo — same FK, different perspective. "projects has many tasks" creates tasks.project_id. Auto-derives the FK field name from the source table name using inflection. delete_action is required and must be explicitly provided by the caller. */ export interface RelationHasManyParams { @@ -1916,6 +1956,15 @@ export interface ViewTableProjectionParams { * =========================================================================== */ ; +/** What runs on the files of an upload or image field. Each key is a lane and provisions the same node an entry in nodes[] would, with file_field filled in; naming the field in such a node instead leaves that lane to the node. */ +export interface BlueprintFieldProcessing { + /** Image fields. Resized versions of the image, written into the image document as `versions`. On by default with the default set of sizes; a list states the versions instead, an object any ProcessImageVersions parameter, false turns it off. */ + versions?: boolean | NonNullable | Omit; + /** Image and upload fields. A vector embedding of the file. Off by default; true takes the node defaults, an object any ProcessImageEmbedding (image) or ProcessFileEmbedding (upload) parameter. The vector column is `_embedding` unless `field_name` names it. */ + embedding?: boolean | Omit | Omit; + /** Upload fields. Text and metadata extracted from the file. Off by default; true takes the node defaults, an object any ProcessExtraction parameter. The columns are `_text` and `_metadata` unless `text_field` / `metadata_field` name them. */ + extraction?: boolean | Omit; +} /** A custom field (column) to add to a blueprint table. */ export interface BlueprintField { /** The column name. */ @@ -1932,6 +1981,8 @@ export interface BlueprintField { index?: 'btree' | 'gin' | 'gist' | 'brin' | 'hash'; /** Comment/description for this field. */ description?: string; + /** Upload and image fields only. The processing lanes that run on the field's files. Omitted, an image field newly added by the blueprint renders the default versions and nothing else runs; false runs nothing. */ + processing?: false | BlueprintFieldProcessing; } /** A WITH CHECK override node for an UPDATE policy. Its expression governs the resulting row while the main policy node governs the targeted row. */ export interface BlueprintPolicyWithCheck { @@ -2094,8 +2145,14 @@ export interface BlueprintBucketSeed { name: string; /** Human-readable description of this bucket. */ description?: string; - /** Whether the bucket is publicly readable. Defaults to false. */ + /** Bucket access type. Defaults to public when is_public is true and private otherwise. */ + type?: 'public' | 'private' | 'temp'; + /** Whether the bucket is publicly readable. Must agree with type when both are supplied. */ is_public?: boolean; + /** Destination bucket key for a temporary bucket. */ + destination?: string; + /** Maximum staging time for a temporary bucket as a PostgreSQL interval. */ + staging_ttl?: string; /** MIME type allowlist (e.g., ["image/png", "image/jpeg"]). NULL means all types allowed. */ allowed_mime_types?: string[]; /** Maximum file size in bytes for this bucket. NULL means no limit. */ @@ -2109,8 +2166,6 @@ export interface BlueprintStorageConfig { scope?: 'app' | 'org'; /** Module key discriminator. Defaults to "default" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case. */ key?: string; - /** @deprecated Use `key` instead. Kept for backward compatibility. */ - storage_key?: string; /** Initial bucket seed entries. Each creates a row in {prefix}_buckets during provisioning. */ buckets?: BlueprintBucketSeed[]; /** Override for presigned upload URL expiry time in seconds. */ @@ -2121,7 +2176,7 @@ export interface BlueprintStorageConfig { default_max_file_size?: number; /** CORS allowed origins for the storage module. */ allowed_origins?: string[]; - /** Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Defaults to "30 seconds". */ + /** Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Every files table runs the confirm loop: the AFTER INSERT trigger enqueues a storage:confirm_upload job that verifies the object exists in S3 before moving status from requested to uploaded, and expires a requested row whose bytes never arrived within upload_url_expiry_seconds. Defaults to "30 seconds". */ confirm_upload_delay?: string; /** Provision a temporary staging bucket (type temp, tagged default-temp) that stages for the private default bucket, so uploads land there and are promoted into their destination on confirmation. Setting staging_ttl implies this. Defaults to false. */ staging?: boolean; @@ -2211,6 +2266,8 @@ export interface BlueprintAgentConfig { has_resources?: boolean; /** Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false. */ has_agents?: boolean; + /** Whether to attach resources to the repositories they apply to, through an agent_resource_repository junction (resource_id, repository_id, priority). Requires resources and a repository module at this same scope — with no repository catalog to point at, the junction is not created. Defaults to false. */ + has_repository_resources?: boolean; /** Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false. */ has_runs?: boolean; /** Resource configuration array. First element configures the agent_resource table: vector dimensions (default 768), chunk_size (default 1000), chunk_strategy (default "paragraph"), chunk_overlap (default 200), embedding_model, embedding_provider, search_indexes (default ["bm25"]). */ @@ -2309,7 +2366,7 @@ export interface BlueprintEntityType { */ ; /** String shorthand -- just the node type name. */ -export type BlueprintNodeShorthand = 'AuthzAllowAll' | 'AuthzAppMemberOwner' | 'AuthzAppMembership' | 'AuthzColumnSecurity' | 'AuthzComposite' | 'AuthzDatabaseClaim' | 'AuthzDenyAll' | 'AuthzDirectOwner' | 'AuthzDirectOwnerAny' | 'AuthzEntityMembership' | 'AuthzFilePath' | 'AuthzHumanOnly' | 'AuthzMemberList' | 'AuthzMemberOwner' | 'AuthzNotReadOnly' | 'AuthzOrgHierarchy' | 'AuthzPeerOwnership' | 'AuthzPublishable' | 'AuthzRelatedEntityMembership' | 'AuthzRelatedMemberList' | 'AuthzRelatedMemberOwner' | 'AuthzRelatedPeerOwnership' | 'AuthzSystemOnly' | 'AuthzTemporal' | 'AuthzValueAllowed' | 'AuthzValueExists' | 'AuthzValueMatch' | 'CheckGreaterThan' | 'CheckLessThan' | 'CheckNotEqual' | 'CheckOneOf' | 'CheckOwnedRelation' | 'DataArchivable' | 'DataBulk' | 'DataCapabilities' | 'DataCompositeField' | 'DataDenormalized' | 'DataDirectOwner' | 'DataEntityMembership' | 'DataFileRef' | 'DataForceCurrentUser' | 'DataGenerated' | 'DataHistory' | 'DataI18n' | 'DataId' | 'DataIdentity' | 'DataImmutableFields' | 'DataInflection' | 'DataInheritFromParent' | 'DataJsonb' | 'DataLock' | 'DataMemberOwner' | 'DataOwnedFields' | 'DataOwnershipInEntity' | 'DataPeoplestamps' | 'DataPrincipalstamps' | 'DataPublishable' | 'DataRealtime' | 'DataSlug' | 'DataSoftDelete' | 'DataStatusField' | 'DataTags' | 'DataTimestamps' | 'SearchBm25' | 'SearchFullText' | 'SearchSpatial' | 'SearchSpatialAggregate' | 'SearchTrgm' | 'SearchUnified' | 'SearchVector' | 'TableOrganizationSettings' | 'TableUserProfiles' | 'TableUserSettings' | 'EventReferral' | 'EventTracker' | 'GuardStepUp' | 'JobTrigger' | 'LimitEnforceAggregate' | 'LimitEnforceCounter' | 'LimitEnforceFeature' | 'LimitEnforceRate' | 'LimitTrackUsage' | 'LimitWarningAggregate' | 'LimitWarningCounter' | 'LimitWarningRate' | 'ProcessChunks' | 'ProcessExtraction' | 'ProcessFileEmbedding' | 'ProcessImageEmbedding' | 'ProcessImageVersions'; +export type BlueprintNodeShorthand = 'AuthzAllowAll' | 'AuthzAppMemberOwner' | 'AuthzAppMembership' | 'AuthzComposite' | 'AuthzDatabaseClaim' | 'AuthzDenyAll' | 'AuthzHumanOnly' | 'AuthzMemberOwner' | 'AuthzPublishable' | 'AuthzSystemOnly' | 'AuthzTemporal' | 'CheckGreaterThan' | 'CheckLessThan' | 'DataArchivable' | 'DataBulk' | 'DataCapabilities' | 'DataDirectOwner' | 'DataEntityMembership' | 'DataForceCurrentUser' | 'DataHistory' | 'DataId' | 'DataJsonb' | 'DataLock' | 'DataMemberOwner' | 'DataOwnershipInEntity' | 'DataPeoplestamps' | 'DataPrincipalstamps' | 'DataPublishable' | 'DataRealtime' | 'DataSlug' | 'DataSoftDelete' | 'DataStatusField' | 'DataTags' | 'DataTimestamps' | 'SearchSpatial' | 'SearchUnified' | 'SearchVector' | 'TableOrganizationSettings' | 'TableUserProfiles' | 'TableUserSettings' | 'GuardStepUp' | 'ProcessChunks' | 'ProcessExtraction' | 'ProcessFileEmbedding' | 'ProcessImageEmbedding' | 'ProcessImageVersions'; /** Object form -- { $type, data } with typed parameters. */ export type BlueprintNodeObject = { $type: 'AuthzAllowAll'; @@ -2569,6 +2626,9 @@ export type BlueprintNodeObject = { } | { $type: 'ProcessChunks'; data: ProcessChunksParams; +} | { + $type: 'ProcessCustom'; + data: ProcessCustomParams; } | { $type: 'ProcessExtraction'; data: ProcessExtractionParams; diff --git a/packages/node-type-registry/src/codegen/generate-reference.ts b/packages/node-type-registry/src/codegen/generate-reference.ts index 3fcb6a4c5f..a1cdb83233 100644 --- a/packages/node-type-registry/src/codegen/generate-reference.ts +++ b/packages/node-type-registry/src/codegen/generate-reference.ts @@ -1,14 +1,18 @@ /** - * Write the generated Authz node reference page as Markdown, for the constructive-security skill. A copy that differs - * from this output is stale. Dev-time only: the page is not part of the runtime exports. + * Write the registry's reference pages as Markdown into the skills folder of a constructive-skills checkout: the Authz + * node reference for the constructive-security skill, and the blueprint node reference for the constructive-blueprints + * skill. A copy that differs from this output is stale; --check lists the stale pages and exits 1. Dev-time only: the + * pages are not part of the runtime exports. * * Usage: - * ts-node src/codegen/generate-reference.ts --outdir /.agents/skills/constructive-security/references + * ts-node src/codegen/generate-reference.ts [--check] --outdir /.agents/skills */ -import { mkdirSync, writeFileSync } from 'fs'; -import { join } from 'path'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; +import { dirname, join } from 'path'; import * as authz from '../authz'; +import { blueprintDefinitionJsonSchema } from '../blueprint-schema.generated'; +import { allNodeTypes } from '../index'; import type { JSONSchema, NodeTypeDefinition } from '../types'; const GENERATED = '> Generated from `node-type-registry`. Do not edit this file by hand; regenerate it from the registry.'; @@ -27,10 +31,9 @@ function typeOf(schema: JSONSchema): string { return schema.format === 'column-ref' ? `${named} (a column${schema['x-column-scope'] === 'foreign' ? ' of the other table' : ''})` : named; } -function parameters(node: NodeTypeDefinition): string[] { - const properties = Object.entries(node.parameter_schema.properties ?? {}).filter(([, schema]) => !schema.readOnly); +function parameters(node: NodeTypeDefinition, omit: ReadonlySet = new Set(), required: ReadonlySet = new Set(node.parameter_schema.required ?? [])): string[] { + const properties = Object.entries(node.parameter_schema.properties ?? {}).filter(([name, schema]) => !schema.readOnly && !omit.has(name)); if (properties.length === 0) return ['No parameters.']; - const required = new Set(node.parameter_schema.required ?? []); return [ '| Parameter | Type | Default | Required | What it does |', '|---|---|---|---|---|', @@ -43,6 +46,7 @@ function parameters(node: NodeTypeDefinition): string[] { } const keys = (names: string[]): string => names.map(code).join(' and '); +const listed = (names: string[]): string => (names.length < 2 ? names.map(code).join('') : `${names.slice(0, -1).map(code).join(', ')} and ${code(names[names.length - 1])}`); // The cross-key rules of a schema that name groups of keys: exactly one of them (oneOf), or at least one (anyOf). function keyRules(schema: JSONSchema): string[] { @@ -98,20 +102,191 @@ export function renderAuthzReferencePage(nodes: NodeTypeDefinition[] = Object.va ]); } +type Json = Record; + +const DEFS = (blueprintDefinitionJsonSchema as Json).$defs as Record; + +const refName = (schema: Json | undefined): string | undefined => (typeof schema?.$ref === 'string' ? schema.$ref.split('/').pop() : undefined); +const resolved = (schema: Json | undefined): Json | undefined => (refName(schema) ? DEFS[refName(schema) as string] : schema); + +/** The part of a `$type`-keyed blueprint schema for one node: what an entry of that type must give, if the schema takes it. */ +const branchOf = (schema: Json, name: string): Json | undefined => + (schema.allOf as Json[] | undefined)?.find((part) => (part.then?.properties?.$type?.const ?? part.if?.properties?.$type?.const) === name)?.then; + +/** Each key of a blueprint, or of a table in it, that takes a list of entries, and the `$defs` entry its items follow. */ +const ENTRY_KEYS: ReadonlyArray<{ key: string; def: string }> = ( + [['', 'BlueprintDefinition'], ['tables[].', 'BlueprintTable']] as const +).flatMap(([prefix, def]) => + Object.entries((DEFS[def].properties ?? {}) as Record).flatMap(([key, property]) => { + const items = refName(property?.items); + return items ? [{ key: `${prefix}${key}[]`, def: items }] : []; + }) +); + +/** The `$type` names an entry takes: of the entry itself and of its branches, through `$ref`, never of what it nests. */ +function entryTypes(schema: Json | undefined, seen: Set = new Set()): string[] { + const ref = refName(schema); + if (ref) return seen.has(ref) ? [] : (seen.add(ref), entryTypes(DEFS[ref], seen)); + if (!schema) return []; + const own = schema.properties?.$type; + const parts = [...(schema.allOf ?? []), ...(schema.anyOf ?? []), ...(schema.oneOf ?? [])] as Json[]; + return [ + ...(own?.enum ?? []), + ...(own?.const !== undefined ? [own.const] : []), + ...parts.flatMap((part) => [...entryTypes(part, seen), ...entryTypes(part.then, seen)]), + ]; +} + +/** The keys an entry of `name` must give, beside `$type`: those of its branch, and those its schema requires of every entry. */ +function entryRequired(schema: Json | undefined, name: string, seen: Set = new Set()): string[] { + const ref = refName(schema); + if (ref) return seen.has(ref) ? [] : (seen.add(ref), entryRequired(DEFS[ref], name, seen)); + if (!schema) return []; + const plain = ((schema.allOf ?? []) as Json[]).filter((part) => !part.if && !part.then); + const keys = [...(schema.required ?? []), ...(branchOf(schema, name)?.required ?? []), ...plain.flatMap((part) => entryRequired(part, name, seen))]; + return [...new Set(keys as string[])].filter((key) => key !== '$type'); +} + +// The families in the order a person builds a table, then the entries beside tables. A new family comes last. +const FAMILIES = ['data', 'check', 'search', 'process', 'job', 'event', 'guard', 'limit', 'relation', 'view']; +const familyOf = (node: NodeTypeDefinition): string => node.category.split('_')[0]; +const familyRank = (family: string): number => (FAMILIES.includes(family) ? FAMILIES.indexOf(family) : FAMILIES.length); + +interface Placement { + where: string; + string: string; + lines: string[]; + omit: Set; + required?: Set; + rules: string[]; +} + +// Where a blueprint names a node and what its entry must give, read from the blueprint JSON Schema, which the tools +// check blueprints with: every key whose entries take the node's `$type`. +function placementOf(node: NodeTypeDefinition): Placement { + // A table's own keys first, then the blueprint's. + const keys = ENTRY_KEYS.filter((entry) => entryTypes(DEFS[entry.def]).includes(node.name)).sort((a, b) => Number(!a.key.startsWith('tables[].')) - Number(!b.key.startsWith('tables[].'))); + if (!keys.length) return { where: 'none', string: '', lines: ['**In a blueprint:** no key of a blueprint takes it.'], omit: new Set(), rules: [] }; + const shorthand = (DEFS.BlueprintNodeShorthand.enum as string[]).includes(node.name); + const placement: Placement = { where: keys.map(({ key }) => code(key)).join(', '), string: '', lines: [], omit: new Set(), rules: [] }; + for (const { key, def } of keys) { + const relation = def === 'BlueprintRelation' ? branchOf(DEFS.BlueprintRelation, node.name) : undefined; + if (def === 'BlueprintNode') { + const object = `\`{ "$type": "${node.name}", "data": { … } }\``; + placement.string = shorthand ? 'yes' : 'no'; + placement.lines.push(`in ${code(key)}, as ${shorthand ? `\`"${node.name}"\` or as ${object}.` : `${object}. \`data\` is required.`}`); + } else if (relation) { + const required: string[] = relation.required ?? []; + const set = (node.parameter_schema.required ?? []).filter((name) => !required.includes(name)); + const ends = (DEFS.BlueprintRelation.allOf as Json[]).filter((part) => !part.if); + placement.lines.push( + `in ${code(key)}, as \`{ "$type": "${node.name}", … }\` with the parameters at the top level. ` + + `${required.length ? `Required: ${listed(required)}.` : 'Nothing is required beyond the two ends.'}` + + `${set.length ? ` The backend sets ${listed(set)} from the two ends.` : ''}` + ); + set.forEach((name) => placement.omit.add(name)); + placement.required = new Set(required); + placement.rules.push(...keyRules({ allOf: ends })); + } else { + const required = entryRequired(resolved({ $ref: `#/$defs/${def}` }), node.name); + placement.lines.push(`in ${code(key)}, as \`{ "$type": "${node.name}", … }\`.${required.length ? ` Required: ${listed(required)}.` : ''}`); + } + } + const [only, ...more] = placement.lines; + placement.lines = more.length ? ['**In a blueprint:**', '', ...placement.lines.map((line) => `- ${line}`)] : [`**In a blueprint:** ${only}`]; + return placement; +} + +function blueprintNodeSection(node: NodeTypeDefinition): string[] { + const placement = placementOf(node); + return [ + `### ${node.name}`, + '', + node.description, + '', + ...placement.lines, + '', + '**Parameters**', + '', + ...parameters(node, placement.omit, placement.required), + '', + ...list('Rules', [...placement.rules, ...keyRules(node.parameter_schema)]) + ]; +} + +/** + * Every node that is not an Authz node as a Markdown reference page, by family and in name order: where a blueprint + * names it, whether a table can name it as a string, and its parameters. Pure: the same nodes give the same page. + */ +export function renderBlueprintNodeReferencePage(nodes: NodeTypeDefinition[] = allNodeTypes): string { + const sorted = nodes + .filter((node) => node.category !== 'authz') + .sort((a, b) => familyRank(familyOf(a)) - familyRank(familyOf(b)) || familyOf(a).localeCompare(familyOf(b)) || a.name.localeCompare(b.name)); + const families = [...new Set(sorted.map(familyOf))]; + const heading = (family: string) => `${family[0].toUpperCase()}${family.slice(1)} nodes`; + return page([ + '# Blueprint node reference', + '', + GENERATED, + '', + 'Every node of the registry except the Authz nodes, by family and in name order: where a blueprint names it, and its ' + + 'parameters. A table names a node in `nodes` as a string only when the node needs no data; otherwise it gives the ' + + 'object with `data`. The Authz nodes are in the Authz node reference of the constructive-security skill.', + '', + '| Node | In a blueprint | As a string |', + '|---|---|---|', + ...sorted.map((node) => { + const placement = placementOf(node); + return `| [${code(node.name)}](#${anchor(node.name)}) | ${placement.where} | ${placement.string} |`; + }), + '', + ...families.flatMap((family) => [`## ${heading(family)}`, '', ...sorted.filter((node) => familyOf(node) === family).flatMap(blueprintNodeSection)]) + ]); +} + +/** Each reference page this package renders, under its path in the skills folder of constructive-skills. */ +export function referencePages(): Array<{ path: string; text: string }> { + return [ + { path: 'constructive-security/references/authz-node-reference.md', text: renderAuthzReferencePage() }, + { path: 'constructive-blueprints/references/node-reference.md', text: renderBlueprintNodeReferencePage() } + ]; +} + +/** The pages under `skillsDir` that are missing or differ from a fresh render. */ +export function stalePages(skillsDir: string): string[] { + return referencePages() + .filter(({ path, text }) => !existsSync(join(skillsDir, path)) || readFileSync(join(skillsDir, path), 'utf8') !== text) + .map(({ path }) => path); +} + function main(): void { const argv = process.argv.slice(2); const i = argv.indexOf('--outdir'); if (i === -1 || !argv[i + 1]) { throw new Error( - 'generate-reference: no output folder was given. Pass --outdir , for example the references folder of the constructive-security skill.' + 'generate-reference: no output folder was given. Pass --outdir : the .agents/skills folder of a constructive-skills checkout.' ); } - const outdir = argv[i + 1]; - mkdirSync(outdir, { recursive: true }); - const file = join(outdir, 'authz-node-reference.md'); - writeFileSync(file, renderAuthzReferencePage()); - // eslint-disable-next-line no-console - console.log(`[node-type-registry] wrote ${file}`); + const skillsDir = argv[i + 1]; + if (argv.includes('--check')) { + const stale = stalePages(skillsDir); + // eslint-disable-next-line no-console + for (const path of stale) console.log(`stale ${path}`); + if (stale.length) { + // eslint-disable-next-line no-console + console.error(`\n${stale.length} reference page(s) differ from the registry. Run this again without --check, and commit the pages.`); + process.exit(1); + } + // eslint-disable-next-line no-console + console.log('[node-type-registry] the reference pages match the registry.'); + return; + } + for (const { path, text } of referencePages()) { + mkdirSync(dirname(join(skillsDir, path)), { recursive: true }); + writeFileSync(join(skillsDir, path), text); + // eslint-disable-next-line no-console + console.log(`[node-type-registry] wrote ${join(skillsDir, path)}`); + } } if (require.main === module) main(); diff --git a/packages/node-type-registry/src/codegen/generate-types.ts b/packages/node-type-registry/src/codegen/generate-types.ts index 48d64c9670..a505626c11 100644 --- a/packages/node-type-registry/src/codegen/generate-types.ts +++ b/packages/node-type-registry/src/codegen/generate-types.ts @@ -428,6 +428,67 @@ function findTable( return tables.find((tbl) => tbl.schemaName === schemaName && tbl.name === tableName); } +/** + * The processing lanes a file field can state, as the backend lists them: the + * option key, and the node types whose parameters the lane's value takes (one + * per field type the key applies to). `list` is set when the node has a + * parameter of the lane's own name, which a bare list stands for. + */ +const FILE_FIELD_LANES: { key: string; nodes: string[]; list?: boolean; doc: string }[] = [ + { + key: 'versions', + nodes: ['ProcessImageVersions'], + list: true, + doc: 'Image fields. Resized versions of the image, written into the image document as `versions`. On by default with the default set of sizes; a list states the versions instead, an object any ProcessImageVersions parameter, false turns it off.' + }, + { + key: 'embedding', + nodes: ['ProcessImageEmbedding', 'ProcessFileEmbedding'], + doc: 'Image and upload fields. A vector embedding of the file. Off by default; true takes the node defaults, an object any ProcessImageEmbedding (image) or ProcessFileEmbedding (upload) parameter. The vector column is `_embedding` unless `field_name` names it.' + }, + { + key: 'extraction', + nodes: ['ProcessExtraction'], + doc: 'Upload fields. Text and metadata extracted from the file. Off by default; true takes the node defaults, an object any ProcessExtraction parameter. The columns are `_text` and `_metadata` unless `text_field` / `metadata_field` name them.' + } +]; + +function buildBlueprintFieldProcessing(): t.ExportNamedDeclaration { + const paramsOf = (node: string) => t.tsTypeReference(t.identifier(`${node}Params`)); + const withoutField = (node: string) => + t.tsTypeReference( + t.identifier('Omit'), + t.tsTypeParameterInstantiation([paramsOf(node), strLit('file_field')]) + ); + return addJSDoc( + exportInterface( + 'BlueprintFieldProcessing', + FILE_FIELD_LANES.map((lane) => + addJSDoc( + optionalProp( + lane.key, + t.tsUnionType([ + t.tsBooleanKeyword(), + ...(lane.list + ? lane.nodes.map((node) => + t.tsTypeReference( + t.identifier('NonNullable'), + t.tsTypeParameterInstantiation([ + t.tsIndexedAccessType(paramsOf(node), strLit(lane.key)) + ]) + )) + : []), + ...lane.nodes.map(withoutField) + ]) + ), + lane.doc + ) + ) + ), + 'What runs on the files of an upload or image field. Each key is a lane and provisions the same node an entry in nodes[] would, with file_field filled in; naming the field in such a node instead leaves that lane to the node.' + ); +} + function buildBlueprintField(): t.ExportNamedDeclaration { // Blueprint field input is not the stored metaschema field row. return addJSDoc( @@ -440,7 +501,17 @@ function buildBlueprintField(): t.ExportNamedDeclaration { optionalProp('max', t.tsNumberKeyword()), optionalProp('regexp', t.tsStringKeyword()), optionalProp('index', strUnion(['btree', 'gin', 'gist', 'brin', 'hash'])), - addJSDoc(optionalProp('description', t.tsStringKeyword()), 'Comment/description for this field.') + addJSDoc(optionalProp('description', t.tsStringKeyword()), 'Comment/description for this field.'), + addJSDoc( + optionalProp( + 'processing', + t.tsUnionType([ + t.tsLiteralType(t.booleanLiteral(false)), + t.tsTypeReference(t.identifier('BlueprintFieldProcessing')) + ]) + ), + 'Upload and image fields only. The processing lanes that run on the field\'s files. Omitted, an image field newly added by the blueprint renders the default versions and nothing else runs; false runs nothing.' + ) ]), 'A custom field (column) to add to a blueprint table.' ); @@ -624,7 +695,7 @@ function buildNodeTypes( addJSDoc( exportTypeAlias( 'BlueprintNodeShorthand', - strUnion(dataNodes.map((nt) => nt.name)) + strUnion(dataNodes.filter((nt) => !needsNodeData(nt)).map((nt) => nt.name)) ), 'String shorthand -- just the node type name.' ) @@ -886,9 +957,21 @@ function buildBlueprintBucketSeed(): t.ExportNamedDeclaration { optionalProp('description', t.tsStringKeyword()), 'Human-readable description of this bucket.' ), + addJSDoc( + optionalProp('type', strUnion(['public', 'private', 'temp'])), + 'Bucket access type. Defaults to public when is_public is true and private otherwise.' + ), addJSDoc( optionalProp('is_public', t.tsBooleanKeyword()), - 'Whether the bucket is publicly readable. Defaults to false.' + 'Whether the bucket is publicly readable. Must agree with type when both are supplied.' + ), + addJSDoc( + optionalProp('destination', t.tsStringKeyword()), + 'Destination bucket key for a temporary bucket.' + ), + addJSDoc( + optionalProp('staging_ttl', t.tsStringKeyword()), + 'Maximum staging time for a temporary bucket as a PostgreSQL interval.' ), addJSDoc( optionalProp( @@ -907,7 +990,7 @@ function buildBlueprintBucketSeed(): t.ExportNamedDeclaration { t.tsArrayType(t.tsStringKeyword()) ), 'CORS allowed origins for this bucket.' - ) + ), ]), 'A bucket seed entry for storage.buckets[]. Creates an initial bucket row in the {prefix}_buckets table during entity type provisioning. Only used for app-level storage (not entity-scoped).' ); @@ -935,10 +1018,6 @@ function buildBlueprintStorageConfig(): t.ExportNamedDeclaration { optionalProp('key', t.tsStringKeyword()), 'Module key discriminator. Defaults to "default" (omitted from table names). Non-default keys appear as an infix: {prefix}_{key}_buckets. Max 16 chars, lowercase snake_case.' ), - addJSDoc( - optionalProp('storage_key', t.tsStringKeyword()), - '@deprecated Use `key` instead. Kept for backward compatibility.' - ), addJSDoc( optionalProp( 'buckets', @@ -969,7 +1048,7 @@ function buildBlueprintStorageConfig(): t.ExportNamedDeclaration { ), addJSDoc( optionalProp('confirm_upload_delay', t.tsStringKeyword()), - 'Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Defaults to "30 seconds".' + 'Delay before the first upload confirmation attempt (PostgreSQL interval string, e.g. "30 seconds"). Every files table runs the confirm loop: the AFTER INSERT trigger enqueues a storage:confirm_upload job that verifies the object exists in S3 before moving status from requested to uploaded, and expires a requested row whose bytes never arrived within upload_url_expiry_seconds. Defaults to "30 seconds".' ), addJSDoc( optionalProp('staging', t.tsBooleanKeyword()), @@ -1245,6 +1324,10 @@ function buildBlueprintAgentConfig(): t.ExportNamedDeclaration { optionalProp('has_agents', t.tsBooleanKeyword()), 'Whether to provision the agent registry (agent table + agent_persona table). Implies has_resources = true. Defaults to false.' ), + addJSDoc( + optionalProp('has_repository_resources', t.tsBooleanKeyword()), + 'Whether to attach resources to the repositories they apply to, through an agent_resource_repository junction (resource_id, repository_id, priority). Requires resources and a repository module at this same scope — with no repository catalog to point at, the junction is not created. Defaults to false.' + ), addJSDoc( optionalProp('has_runs', t.tsBooleanKeyword()), "Whether to provision the agent execution surface: agent_run (one supervised run of a thread — placement, cursor, artifacts), agent_event (that run's append-only transcript, agent session entries stored verbatim, append-only by grant with UNIQUE (run_id, seq)) and agent_run_workspace (the repositories a run works in — zero rows for a chat with no clone, one per repository otherwise, UNIQUE (run_id, repo)). Defaults to false." @@ -1818,7 +1901,9 @@ function tsTypeSchema(type: t.TSType): Json { if (t.isTSBooleanKeyword(type)) return { type: 'boolean' }; if (t.isTSUnknownKeyword(type) || t.isTSAnyKeyword(type)) return {}; if (t.isTSNeverKeyword(type)) return { not: {} }; - if (t.isTSLiteralType(type) && t.isStringLiteral(type.literal)) return { const: type.literal.value }; + if (t.isTSLiteralType(type) && (t.isStringLiteral(type.literal) || t.isBooleanLiteral(type.literal) || t.isNumericLiteral(type.literal))) { + return { const: type.literal.value }; + } if (t.isTSArrayType(type)) return { type: 'array', items: tsTypeSchema(type.elementType) }; if (t.isTSTypeLiteral(type)) return membersSchema(type.members); if (t.isTSIntersectionType(type)) return { allOf: type.types.map(tsTypeSchema) }; @@ -1831,13 +1916,38 @@ function tsTypeSchema(type: t.TSType): Json { } return { anyOf: type.types.map(tsTypeSchema) }; } + if (t.isTSIndexedAccessType(type) && t.isTSLiteralType(type.indexType) && t.isStringLiteral(type.indexType.literal)) { + return (nodeParams(type.objectType).properties as Json)[type.indexType.literal.value] as Json; + } if (t.isTSTypeReference(type) && t.isIdentifier(type.typeName)) { - if (type.typeName.name === 'Record') return { type: 'object', additionalProperties: tsTypeSchema(type.typeParameters.params[1]) }; + const params = type.typeParameters?.params ?? []; + if (type.typeName.name === 'Record') return { type: 'object', additionalProperties: tsTypeSchema(params[1]) }; + // The parameter schemas allow no null, so NonNullable leaves them as they are. + if (type.typeName.name === 'NonNullable') return tsTypeSchema(params[0]); + if (type.typeName.name === 'Omit') { + const omitted = (tsTypeSchema(params[1]).enum as string[]) ?? [tsTypeSchema(params[1]).const as string]; + const schema = nodeParams(params[0]); + return { + ...schema, + properties: Object.fromEntries(Object.entries(schema.properties as Json).filter(([key]) => !omitted.includes(key))), + ...(schema.required ? { required: (schema.required as string[]).filter((key) => !omitted.includes(key)) } : {}) + }; + } return refTo(type.typeName.name); } throw new Error(`blueprint JSON Schema: no rule turns the TS type ${type.type} into JSON Schema; add one to tsTypeSchema.`); } +// A node's parameters as a caller writes them, for Omit<...Params> and ...Params['key'] in the structural types. +function nodeParams(type: t.TSType): Json { + const name = t.isTSTypeReference(type) && t.isIdentifier(type.typeName) ? type.typeName.name : undefined; + const node = allNodeTypes.find((nt) => `${nt.name}Params` === name); + if (!node) { + throw new Error(`blueprint JSON Schema: ${name ?? type.type} is not a node's parameters; Omit and indexed access are turned into JSON Schema for node parameters only.`); + } + return nodeDataSchema(node.parameter_schema, new Map()); +} + // The `$type` literal of an object type, which makes a union of them a union keyed by `$type`. function typeTag(type: t.TSType): string | undefined { if (!t.isTSTypeLiteral(type)) return undefined; @@ -1867,17 +1977,31 @@ function byType(base: Json, branches: Array<{ name: string; then: Json }>): Json ...base, required: [...new Set(['$type', ...((base.required as string[]) ?? [])])], properties: { ...properties, $type: { enum: branches.map((branch) => branch.name) } }, - allOf: branches.map((branch) => ({ if: { properties: { $type: { const: branch.name } }, required: ['$type'] }, then: branch.then })) + allOf: [ + ...((base.allOf ?? []) as Json[]), + ...branches.map((branch) => ({ if: { properties: { $type: { const: branch.name } }, required: ['$type'] }, then: branch.then })) + ] }; } +function needsNodeData(node: NodeTypeDefinition): boolean { + return (node.parameter_schema.required ?? []).some((key) => { + const property = node.parameter_schema.properties?.[key]; + return !property?.readOnly && property?.default === undefined; + }); +} + +function nodeDataBranches(nodes: NodeTypeDefinition[]): Array<{ name: string; then: Json }> { + return nodes.map((nt) => ({ + name: nt.name, + then: { properties: { data: refTo(`${nt.name}Params`) }, ...(needsNodeData(nt) ? { required: ['data'] } : {}) } + })); +} + function nodeEntrySchema(dataNodes: NodeTypeDefinition[]): Json { return byType( { type: 'object', properties: { data: { type: 'object' } }, additionalProperties: false }, - dataNodes.map((nt) => ({ - name: nt.name, - then: { properties: { data: refTo(`${nt.name}Params`) }, ...((nt.parameter_schema.required ?? []).length ? { required: ['data'] } : {}) } - })) + nodeDataBranches(dataNodes) ); } @@ -1885,7 +2009,7 @@ function nodeEntrySchema(dataNodes: NodeTypeDefinition[]): Json { const PRIVILEGE_PATTERN = '^([Ss][Ee][Ll][Ee][Cc][Tt]|[Ii][Nn][Ss][Ee][Rr][Tt]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee])$'; function policySchemas(authzNodes: NodeTypeDefinition[]): Record { - const data = authzNodes.map((nt) => ({ name: nt.name, then: { properties: { data: refTo(`${nt.name}Params`) } } })); + const data = nodeDataBranches(authzNodes); return { BlueprintPolicyWithCheck: byType({ type: 'object', properties: { data: { type: 'object' } }, additionalProperties: false }, data), BlueprintPolicy: { @@ -1911,6 +2035,31 @@ function policySchemas(authzNodes: NodeTypeDefinition[]): Record { }; } +function namedOrModuleTarget(name: string, schema: string, module: string): Json { + return { + oneOf: [ + { required: [name], not: { required: [module] } }, + { required: [module], not: { anyOf: [{ required: [name] }, { required: [schema] }] } } + ] + }; +} + +function tableTargetSchema(): Json { + return { + ...namedOrModuleTarget('table_name', 'schema_name', 'module'), + if: { required: ['provisions'] }, + then: { + required: ['module'], + not: { anyOf: ['policies', 'grants', 'nodes', 'fields'].map((key) => ({ required: [key] })) }, + properties: { + module: { not: { required: ['table'] } }, + provisions: { minProperties: 1 } + } + }, + else: { properties: { module: refTo('BlueprintModuleTableRef') } } + }; +} + function relationSchema(relationNodes: NodeTypeDefinition[]): Json { const ends: Json = { source_table: { type: 'string' }, @@ -1921,15 +2070,27 @@ function relationSchema(relationNodes: NodeTypeDefinition[]): Json { target_module: refTo('BlueprintModuleTableRef') }; return byType( - { type: 'object', description: 'A relation entry in a blueprint definition.', properties: ends }, + { + type: 'object', + description: 'A relation entry in a blueprint definition.', + properties: ends, + allOf: ['source', 'target'].map((end) => namedOrModuleTarget(`${end}_table`, `${end}_schema`, `${end}_module`)) + }, relationNodes.map((nt) => { const params = nodeDataSchema(nt.parameter_schema, new Map()); const spatial = nt.name === 'RelationSpatial'; + const resolved = ['source_table_id', 'target_table_id', 'source_field_id', 'target_field_id']; + const required = ((params.required ?? []) as string[]).filter((key) => !resolved.includes(key)); + if (spatial) required.push('source_field', 'target_field'); return { name: nt.name, then: { - properties: { ...(params.properties as Json), ...(spatial ? { source_field: { type: 'string' }, target_field: { type: 'string' } } : {}) }, - ...(spatial ? { required: ['source_field', 'target_field'] } : {}) + properties: { + ...(params.properties as Json), + ...(spatial ? { source_field: { type: 'string' }, target_field: { type: 'string' } } : {}), + ...(nt.name === 'RelationManyToMany' ? { policies: { type: 'array', items: refTo('BlueprintPolicy') } } : {}) + }, + ...(required.length ? { required } : {}) } }; }) @@ -1944,7 +2105,14 @@ function buildBlueprintJsonSchema(statements: t.Statement[], nodeTypes: NodeType for (const statement of statements) { if (!t.isExportNamedDeclaration(statement)) continue; const declaration = statement.declaration; - if (t.isTSInterfaceDeclaration(declaration)) declared.set(declaration.id.name, () => withDoc(membersSchema(declaration.body.body), statement)); + if (t.isTSInterfaceDeclaration(declaration)) { + declared.set(declaration.id.name, () => { + const schema = withDoc(membersSchema(declaration.body.body), statement); + return declaration.id.name === 'BlueprintTable' + ? { ...schema, ...tableTargetSchema() } + : schema; + }); + } if (t.isTSTypeAliasDeclaration(declaration)) declared.set(declaration.id.name, () => withDoc(tsTypeSchema(declaration.typeAnnotation), statement)); } const dataNodes = nodeTypes.filter((nt) => nt.category !== 'relation' && nt.category !== 'view'); @@ -1964,7 +2132,7 @@ function buildBlueprintJsonSchema(statements: t.Statement[], nodeTypes: NodeType ), additionalProperties: false }); - declared.set('BlueprintNodeShorthand', { enum: dataNodes.map((nt) => nt.name), description: 'String shorthand -- just the node type name.' }); + declared.set('BlueprintNodeShorthand', { enum: dataNodes.filter((nt) => !needsNodeData(nt)).map((nt) => nt.name), description: 'String shorthand -- just the node type name.' }); declared.set('BlueprintNodeObject', { ...nodeEntrySchema(dataNodes), description: 'Object form -- { $type, data } with typed parameters.' }); for (const [name, schema] of Object.entries(policySchemas(policyNodeTypes))) declared.set(name, schema); declared.set('BlueprintRelation', relationSchema(nodeTypes.filter((nt) => nt.category === 'relation'))); @@ -2073,6 +2241,7 @@ function renderBlueprintSchema(schema: Json): string { '// Regenerate with:', '// cd packages/node-type-registry && pnpm generate:types', '', + '/* eslint-disable */', "import type { JSONSchema } from './types';", '', '/** JSON Schema (draft-07) of a blueprint definition: the shapes construct_blueprint() reads, with each node\'s data checked against its parameter_schema in the form a caller writes it. */', @@ -2141,6 +2310,7 @@ function buildProgram(meta?: MetaTableInfo[]): { types: string; schema: string } ? 'Derived from _meta' : 'Static fallback (no _meta provided)'; statements.push(sectionComment(`Structural types — ${metaSource}`)); + statements.push(buildBlueprintFieldProcessing()); statements.push(buildBlueprintField()); statements.push(buildBlueprintPolicyWithCheck(policyNodeTypes)); statements.push(buildBlueprintPolicy(policyNodeTypes, meta)); diff --git a/packages/node-type-registry/src/content-presets/agent.ts b/packages/node-type-registry/src/content-presets/agent.ts new file mode 100644 index 0000000000..c363c9e203 --- /dev/null +++ b/packages/node-type-registry/src/content-presets/agent.ts @@ -0,0 +1,47 @@ +import type { TrustLadderPreset } from './types'; + +/** + * How an agent principal earns standing in a scope: by finishing runs there. + * + * `agent_proven` — three completed runs. Cheap, and deliberately so: it says + * the agent has done real work here, nothing more. + * + * `agent_trusted` — ten completed runs inside a 30-day window, and it lapses + * 30 days after it is earned, so an idle agent drifts back to proven rather + * than keeping a standing nobody has re-checked. A replayed refresh token or a + * refused attempt to widen its own scope demotes it on the spot, and demotion + * resets the count: the agent re-earns trust from zero, it does not get it + * back on the next run. + * + * Neither rung unlocks anything by itself. Which permissions wait for which + * rung is the scope administrator's vocabulary, not the platform's — a tenant + * arms the ladder by adding `unlocks: ['manage_domains', …]` in its own + * catalog's names, and an unknown name fails the seed rather than silently + * un-gating. Seeding `agent` alone therefore changes no principal's mask. + * + * Trust is earned per scope: the ladder an entity seeds counts that entity's + * runs, and an agent proven in one organization is a stranger in the next. + */ +export const agent: TrustLadderPreset = { + kind: 'trust_ladder', + slug: 'agent', + label: 'Agent trust', + description: + 'Proven after three completed runs, trusted after ten in a 30-day window; a replayed refresh token or a refused widening demotes trusted. Unlocks are the scope administrator\'s to name.', + rungs: [ + { + level: 'agent_proven', + event: 'agent.run.completed', + required_count: 3, + period_interval: '30 days', + }, + { + level: 'agent_trusted', + event: 'agent.run.completed', + required_count: 10, + period_interval: '30 days', + expires_interval: '30 days', + revoked_by: ['token.refresh_reused', 'PRINCIPAL_CHILD_WIDENS'], + }, + ], +}; diff --git a/packages/node-type-registry/src/content-presets/approvals.ts b/packages/node-type-registry/src/content-presets/approvals.ts new file mode 100644 index 0000000000..0b9d48d541 --- /dev/null +++ b/packages/node-type-registry/src/content-presets/approvals.ts @@ -0,0 +1,27 @@ +import type { RouteBindingsPreset } from './types'; + +/** + * Approvals: where a parked graph node's notification points. + * + * Its own slug rather than a widening of `mantra`, because the two answer + * different questions and a site should be able to take one without the other: + * Mantra is who you are, approvals is what is waiting on you. A tenant serving + * its own auth pages still wants this set, and a tenant with no human-in-the- + * loop graphs wants neither. + * + * One binding, not two, because a route path is a *prefix*: `resolve_route` + * matches the path exactly or followed by `/`, longest first, so `/approvals` + * serves both the queue and `/approvals//`. The + * question's reference therefore travels in the path — an address, never a + * credential — and the page reads it back. Binding the parameterised form + * separately would be a second row saying the same thing, and the two could + * disagree. + */ +export const approvals: RouteBindingsPreset = { + kind: 'route_bindings', + slug: 'approvals', + label: 'Approvals pages', + description: + "The human-in-the-loop answer surface served by the approvals function image: /approvals is everything waiting on you, and /approvals// is one question, rendered from its graph node-state row and settled through that scope's own approve_node. Bound as a single path prefix; claims no root or catch-all path, and installs independently of the auth pages.", + bindings: [{ path: '/approvals', task_identifier: 'approvals:pages' }], +}; diff --git a/packages/node-type-registry/src/content-presets/index.ts b/packages/node-type-registry/src/content-presets/index.ts index 53a2ecbe0a..7c6cf5c93a 100644 --- a/packages/node-type-registry/src/content-presets/index.ts +++ b/packages/node-type-registry/src/content-presets/index.ts @@ -1,15 +1,53 @@ export type { + BlockPageDocument, ContentPreset, ContentPresetKind, + FunctionRouteBinding, LimitBaselinePreset, + PageDocument, + PagesPreset, + PrincipalPreset, + PrincipalPresetCredentials, + PrincipalPresetDefinition, + PrincipalPresetScope, + ProsePageDocument, + RedirectRouteBinding, + RobotsDirective, + RobotsPreset, + RouteBinding, + RouteBindingsPreset, TrustLadderPreset, } from './types'; +import { agent } from './agent'; +import { approvals } from './approvals'; import { humanity } from './humanity'; +import { layouts } from './layouts'; +import { legal } from './legal'; +import { mantra } from './mantra'; +import { mantraStandalone } from './mantra-standalone'; import { metered, meteredBaseline } from './metered'; +import { deployBot, readOnlyAnalyst } from './principals'; +import { robotsNoAi, robotsOpen } from './robots'; +import { sso } from './sso'; import type { ContentPreset } from './types'; -export { humanity, metered, meteredBaseline }; +export { + agent, + approvals, + deployBot, + humanity, + layouts, + legal, + mantra, + mantraStandalone, + metered, + meteredBaseline, + readOnlyAnalyst, + robotsNoAi, + robotsOpen, + sso, +}; /** * Every shipped content preset, in catalog order. Consumed by `generate.ts`, @@ -24,6 +62,21 @@ export const allContentPresets: ContentPreset[] = [ humanity, metered, meteredBaseline, + mantra, + legal, + approvals, + robotsOpen, + robotsNoAi, + // Appended, not grouped with `legal`: the catalog's order is the order of the + // generated alteration files, so inserting a preset in the middle renumbers + // every one after it and rewrites alterations deployed databases have already + // applied. A new preset goes last. + layouts, + readOnlyAnalyst, + deployBot, + agent, + mantraStandalone, + sso, ]; /** Look up a shipped content preset by kind and slug. */ diff --git a/packages/node-type-registry/src/content-presets/layouts.ts b/packages/node-type-registry/src/content-presets/layouts.ts new file mode 100644 index 0000000000..70d0c32d3f --- /dev/null +++ b/packages/node-type-registry/src/content-presets/layouts.ts @@ -0,0 +1,91 @@ +import type { PagesPreset } from './types'; + +/** + * The one layout a site is worth being born with: chrome around its pages. + * + * A layout is a page whose content is a block document with a `Slot` in it, + * stored at the reserved `_layout/default` path — reserved because a request path + * always begins with `/` and this one does not, so the template is addressable by + * the page API and by the renderer and by nothing arriving over HTTP. Pages that + * name no layout are served in it; a page naming another one gets that one or a + * refusal. + * + * Deliberately one preset rather than a set. The value of shipping a layout at + * all is that a site has something real to author over — a document a tenant can + * read, edit and publish through the same page API as its prose, instead of a + * template compiled into the image. That argument is satisfied by one; a + * `login`/`marketing`/`app` trio would be three guesses at product decisions + * nobody has made, each of which a tenant would have to delete. + * + * What it deliberately does not carry: + * - no `meta.robots`: served pages default to `noindex`, and a preset that + * flipped a site to indexable as a side effect of installing chrome would + * make crawlability an accident; + * - no `meta.title`/`description`: those are the page's to state, and a layout + * stating them would put the same title on every page that omitted one; + * - no class names beyond the semantic ones: there is no stylesheet served with + * documents yet, so Tailwind/shadcn classes here would name CSS that never + * arrives. + * + * The masthead reads `{{ site.title }}` rather than a name, which is what makes + * one layout serve every tenant: the binding is resolved while rendering, + * against the site being served, so the seeded document is identical everywhere + * and correct everywhere. + */ +export const layouts: PagesPreset = { + kind: 'pages', + slug: 'layouts', + label: 'Default page layout', + description: + 'The starter template a site serves its pages in: a block document with a content slot, stored at the reserved _layout/default page so it is versioned and published exactly like the pages it wraps. Pages that name no layout are served in it — edit it through the page API to change the chrome of every such page.', + pages: [ + { + path: '_layout/default', + kind: 'block_document', + title: 'Default layout', + document: { + formatVersion: '1.0', + type: 'UISchema', + id: 'layout-default', + page: { + type: 'Page', + key: 'shell', + props: {}, + children: [ + { + type: 'Section', + key: 'masthead', + props: { className: 'masthead' }, + // The tenant's own name, resolved per render rather than seeded. + children: [ + { + type: 'Markdown', + key: 'brand', + props: {}, + bindings: { content: '{{ site.title }}' }, + children: [] + } + ] + }, + // Where the page goes. A slot nothing fills renders its own + // children, so the fallback text below is what a layout served with + // no page in it says — a visible statement rather than a blank page. + { + type: 'Slot', + key: 'content', + props: { name: 'content' }, + children: [ + { + type: 'Markdown', + key: 'content-empty', + props: { content: 'This layout is serving no page content.' }, + children: [] + } + ] + } + ] + } + } + } + ] +}; diff --git a/packages/node-type-registry/src/content-presets/legal.ts b/packages/node-type-registry/src/content-presets/legal.ts new file mode 100644 index 0000000000..fd5023232f --- /dev/null +++ b/packages/node-type-registry/src/content-presets/legal.ts @@ -0,0 +1,34 @@ +import type { PagesPreset } from './types'; + +/** + * Legal: the two documents every signup flow links to, as starter pages. + * + * These are page rows, not prose anyone should ship as-is: a tenant installs + * them into its site's merkle-backed pages, replaces the placeholder text with + * its own counsel's, and publishes. From then on the site's active commit is + * the version — the `/terms` and `/privacy` pages serve it, and an acceptance + * event records exactly which `commit_id` was on screen. That is the point of + * seeding them as pages rather than a JSON blob: a blob has no versions to + * cite, so acceptance against it is a checkbox rather than evidence. + * + * `body` is blank-line-separated prose, rendered escaped — never markup. + */ +export const legal: PagesPreset = { + kind: 'pages', + slug: 'legal', + label: 'Legal starter pages', + description: + 'Placeholder Terms of Service and Privacy Policy pages, installed into a site\u2019s merkle-backed pages so publishing versions them and acceptance events can cite the exact commit that was on screen. Replace the placeholder prose before publishing.', + pages: [ + { + path: '/terms', + title: 'Terms of Service', + body: 'These placeholder terms describe the agreement between this service and the people who use it. Replace this text with your own terms before publishing.\n\nUntil then, this page exists so every signup flow has a URL to link to and a version to record.' + }, + { + path: '/privacy', + title: 'Privacy Policy', + body: 'This placeholder policy describes what data this service collects and why. Replace this text with your own policy before publishing.\n\nUntil then, this page exists so every signup flow has a URL to link to and a version to record.' + } + ] +}; diff --git a/packages/node-type-registry/src/content-presets/mantra-standalone.ts b/packages/node-type-registry/src/content-presets/mantra-standalone.ts new file mode 100644 index 0000000000..fac2830a97 --- /dev/null +++ b/packages/node-type-registry/src/content-presets/mantra-standalone.ts @@ -0,0 +1,28 @@ +import { mantra } from './mantra'; +import type { RouteBindingsPreset } from './types'; + +/** + * Mantra on a host of its own. + * + * The `mantra` set deliberately claims no `/`, because it layers onto a site + * that has content of its own. A hostname provisioned only to carry the auth + * pages (`mantra.`) has no such content: its root is the placeholder + * the route guard created targeting the empty site, which answers 404. This + * set is the same pages plus that one root, as a redirect onto sign-in — a + * redirects-table row, not a Mantra task, so the image still owns exactly the + * pages it serves. + * + * Composed from `mantra` rather than copied, so retuning the page set retunes + * both; the redirect is the only thing this preset adds. + */ +export const mantraStandalone: RouteBindingsPreset = { + kind: 'route_bindings', + slug: 'mantra-standalone', + label: 'Mantra platform pages, on a dedicated host', + description: + "The mantra page set for a hostname that serves nothing else: every binding of 'mantra', plus the site root redirecting to sign-in. Install onto a site provisioned only to carry the auth pages; a site with authored content keeps its root by installing 'mantra' instead.", + bindings: [ + ...mantra.bindings, + { path: '/', target: 'redirect', to_path: '/login', anonymous: true }, + ], +}; diff --git a/packages/node-type-registry/src/content-presets/mantra.ts b/packages/node-type-registry/src/content-presets/mantra.ts new file mode 100644 index 0000000000..8dc1b307bc --- /dev/null +++ b/packages/node-type-registry/src/content-presets/mantra.ts @@ -0,0 +1,72 @@ +import type { RouteBindingsPreset } from './types'; + +/** + * Mantra: the platform's own website, as a table of rows. + * + * Mantra is ONE function image exposing many named tasks — `mantra:signin`, + * `mantra:robots_txt`, and so on. Nothing about serving it is a new routing + * mode: each binding below becomes an ordinary route row whose target is a + * function, which the routing resolver already answers on the function lane by + * emitting the definition's task identifier for the sync gateway. + * + * So the only real question is *which paths* Mantra owns on a site, and that is + * a product decision — which is why it lives here as a preset rather than as a + * list inside a PL/pgSQL function. Adding `/reset-password` becomes a row a + * reviewer can read, a tenant can ship a different set under its own slug, and + * retuning the set is an UPDATE with history rather than a migration. + * + * Deliberately no `/` and no catch-all: a site's own root route keeps serving + * authored content, and Mantra layers onto the hostname that site already + * serves. A path here is claimed from the site, so every one of them is a page + * we intend to own. + * + * No SSO legs either: `/auth/start` and `/auth/callback` are the `sso` preset, + * installed only by a tenant that signs people in with an identity provider. + */ +export const mantra: RouteBindingsPreset = { + kind: 'route_bindings', + slug: 'mantra', + label: 'Mantra platform pages', + description: + "The platform-owned page set served by the mantra function image: authentication (sign in/up/out, confirming an address, password recovery, 2FA), the legal pages, and the well-known crawler and manifest files. Layers onto a site's existing hostname; claims no root or catch-all path.", + bindings: [ + // Authentication. + { path: '/login', task_identifier: 'mantra:signin', anonymous: true }, + // The phone-number lane under it: one page that signs a registered number + // in and provisions an unregistered one, so it nests under /login rather + // than sitting beside it as a second sign-up surface. + { path: '/login/phone', task_identifier: 'mantra:phone_signin', anonymous: true }, + { path: '/login/magic', task_identifier: 'mantra:magic_link', anonymous: true }, + { path: '/logout', task_identifier: 'mantra:signout', anonymous: true }, + { path: '/signup', task_identifier: 'mantra:signup', anonymous: true }, + { path: '/forgot-password', task_identifier: 'mantra:forgot', anonymous: true }, + { path: '/reset-password', task_identifier: 'mantra:reset', anonymous: true }, + { path: '/2fa', task_identifier: 'mantra:two_factor', anonymous: true }, + { path: '/device-approval', task_identifier: 'mantra:device_approval', anonymous: true }, + // Turning a second factor on; /login sends a require_mfa sign-in here. + { path: '/setup-2fa', task_identifier: 'mantra:setup_two_factor', anonymous: true }, + { path: '/auth/magic', task_identifier: 'mantra:magic_landing', anonymous: true }, + // The confirmation link a sign-up mails: a password sign-up stays pending + // until this is followed, so without it a new account cannot sign in. + { path: '/verify-email', task_identifier: 'mantra:verify_email', anonymous: true }, + + // Legal pages every signup flow links to. + { path: '/terms', task_identifier: 'mantra:terms', anonymous: true }, + { path: '/privacy', task_identifier: 'mantra:privacy', anonymous: true }, + + // Well-known files a crawler or an installing browser asks for by name. + { path: '/robots.txt', task_identifier: 'mantra:robots_txt', anonymous: true }, + { path: '/sitemap.xml', task_identifier: 'mantra:sitemap_xml', anonymous: true }, + { path: '/site.webmanifest', task_identifier: 'mantra:webmanifest', anonymous: true }, + + // The browser bundle a page that asked to hydrate loads. A path rather than + // a page: it is this image's own asset, served immutable by content hash, + // and a site whose documents never ask for it never requests it. + { path: '/_mantra/runtime.js', task_identifier: 'mantra:runtime_asset', anonymous: true }, + + // What every page this image serves looks like: one stylesheet built into + // the image, cached immutably by content hash, and overridden by any sheet a + // site loads after it. + { path: '/_mantra/styles.css', task_identifier: 'mantra:styles_asset', anonymous: true }, + ], +}; diff --git a/packages/node-type-registry/src/content-presets/principals.ts b/packages/node-type-registry/src/content-presets/principals.ts new file mode 100644 index 0000000000..5bcd9eaffb --- /dev/null +++ b/packages/node-type-registry/src/content-presets/principals.ts @@ -0,0 +1,87 @@ +import type { PrincipalPreset } from './types'; + +/** + * Principal presets: blueprints a human instantiates in one call. + * + * Both rows name capabilities rather than bit positions. A principal's SPRT is + * `owner_rows & preset_mask`, and the mask is resolved against the tenant's + * own capabilities table when the row is instantiated, so the same catalog row + * fits a tenant with 64 bits and a tenant with 256 without granting a bit + * either does not know. A name the tenant lacks is an error, never a silently + * narrower principal. + * + * The lifetimes are ceilings the tenant's `auth_settings` may lower but a + * preset may never raise; a tenant whose settings are tighter than the row + * rejects the instantiation rather than quietly widening. + */ + +/** + * Reads everything the owner can read, writes nothing. The mask at each scope + * is null — every bit the owner holds, so a capability-gated read the owner + * has is one the analyst has — and `is_read_only` is what forbids the writes. + * No delegation: an analyst does not mint agents. + */ +export const readOnlyAnalyst: PrincipalPreset = { + kind: 'principal', + slug: 'read-only-analyst', + label: 'Read-only analyst', + description: + 'Sees what its owner sees and changes nothing: read-only at every scope, all of the owner\'s bits, no delegation.', + definition: { + is_read_only: true, + use_admin_owner: false, + bypass_step_up: false, + scopes: [ + { membership_type: 'app', allowed_mask_capabilities: null }, + { membership_type: 'org', allowed_mask_capabilities: null } + ], + entity_policy: 'inherit_owner', + delegation: { allowed: false, max_depth: 0 }, + credentials: { + api_key_ttl: '30 days', + access_token_ttl: '15 minutes', + refresh_token_ttl: '7 days', + max_chain_age: '30 days' + } + } +}; + +/** + * Ships code: the organization capabilities that move services, sites, and + * domains, and nothing else — no member administration, no secrets, no + * exports. `require_list` pins it to the organizations it deploys for, and it + * may mint exactly one level of child (a per-job worker) beneath itself. + * `bypass_step_up` lets an unattended pipeline past the MFA guards its owner + * would otherwise have to satisfy in person — so instantiating this preset is + * itself MFA-gated: the principals INSERT guard demands a fresh MFA proof from + * the human caller (a password re-entry is not enough) before a + * `bypass_step_up` principal may come into existence. Narrowing the preset + * with `bypass_step_up: false` lifts that requirement. + */ +export const deployBot: PrincipalPreset = { + kind: 'principal', + slug: 'deploy-bot', + label: 'Deploy bot', + description: + 'Manages services, sites, and domains for the organizations it is scoped to; nothing else. Unattended: bypasses step-up, may delegate one level. Creating one requires a fresh MFA proof.', + definition: { + is_read_only: false, + use_admin_owner: false, + bypass_step_up: true, + scopes: [ + { membership_type: 'app', allowed_mask_capabilities: [] }, + { + membership_type: 'org', + allowed_mask_capabilities: ['manage_services', 'manage_sites', 'manage_domains'] + } + ], + entity_policy: 'require_list', + delegation: { allowed: true, max_depth: 1 }, + credentials: { + api_key_ttl: '30 days', + access_token_ttl: '15 minutes', + refresh_token_ttl: '7 days', + max_chain_age: '30 days' + } + } +}; diff --git a/packages/node-type-registry/src/content-presets/robots.ts b/packages/node-type-registry/src/content-presets/robots.ts new file mode 100644 index 0000000000..4c234651df --- /dev/null +++ b/packages/node-type-registry/src/content-presets/robots.ts @@ -0,0 +1,72 @@ +import type { RobotsPreset } from './types'; + +/** + * Robots: the directives a site puts in front of crawlers, as starter rows. + * + * A site's `robots` column is emitted verbatim by `/robots.txt`, so what goes + * in it is a product decision — which crawlers a tenant is willing to feed — + * and a decision belongs in a catalog row a reviewer can read, not inside an + * emitter. The image already disallows its own session and token paths, so a + * preset never restates them: it carries only what a tenant chooses. + * + * Two are shipped because the choice is genuinely binary. `open` is the default + * a public marketing site wants; `no-ai` is the same file plus the named + * training crawlers, listed by name because `User-agent: *` cannot express + * "index me, do not train on me". Neither is privileged — a tenant that wants + * a third writes a row of exactly this shape. + */ +export const robotsOpen: RobotsPreset = { + kind: 'robots', + slug: 'open', + label: 'Open to crawlers', + description: + 'Nothing disallowed beyond the session and token paths the page set already excludes \u2014 the file a public site wants, stated rather than assumed.', + directives: [] +}; + +/** + * The named training crawlers, each as its own group. + * + * They are listed rather than pattern-matched because robots.txt has no + * wildcard for "an AI crawler": a group applies to the user-agent token it + * names, so a list is the only thing a crawler actually obeys. It will go stale + * as vendors rename — that is a row to update, which is why it is a row. + */ +export const robotsNoAi: RobotsPreset = { + kind: 'robots', + slug: 'no-ai', + label: 'Open to search, closed to AI training', + description: + 'Indexable by search engines, disallowed for the named model-training crawlers. The list names each user-agent because robots.txt has no wildcard for \u201Can AI crawler\u201D, so it is a row to keep current rather than a pattern.', + directives: [ + 'User-agent: GPTBot', + 'Disallow: /', + '', + 'User-agent: ChatGPT-User', + 'Disallow: /', + '', + 'User-agent: CCBot', + 'Disallow: /', + '', + 'User-agent: ClaudeBot', + 'Disallow: /', + '', + 'User-agent: anthropic-ai', + 'Disallow: /', + '', + 'User-agent: Google-Extended', + 'Disallow: /', + '', + 'User-agent: Applebot-Extended', + 'Disallow: /', + '', + 'User-agent: meta-externalagent', + 'Disallow: /', + '', + 'User-agent: Bytespider', + 'Disallow: /', + '', + 'User-agent: PerplexityBot', + 'Disallow: /' + ] +}; diff --git a/packages/node-type-registry/src/content-presets/sso.ts b/packages/node-type-registry/src/content-presets/sso.ts new file mode 100644 index 0000000000..bf253eed05 --- /dev/null +++ b/packages/node-type-registry/src/content-presets/sso.ts @@ -0,0 +1,32 @@ +import type { RouteBindingsPreset } from './types'; + +/** + * SSO: the browser legs of signing in with an external identity provider. + * + * Its own slug rather than part of `mantra`, because a provider sign-in is + * something a tenant turns on, not something every site serves: a tenant with + * no identity providers has no callback to answer, and a callback path that + * answers anyway is a public endpoint that does nothing but advertise itself. + * Absent this preset the paths are simply unrouted, so they 404 — there is no + * fallback page behind them. + * + * The pages are mantra's tasks (the `/login` provider buttons link to + * `/auth/start`), so this installs beside `mantra` with the same verb: + * `_install_mantra(site_id, entity_id, 'sso')`. The tenant still needs + * `auth:sso` (identity providers + connected accounts) for there to be a + * provider to start against. + */ +export const sso: RouteBindingsPreset = { + kind: 'route_bindings', + slug: 'sso', + label: 'SSO sign-in pages', + description: + "The OAuth/OIDC browser legs served by the mantra function image: /auth/start sends the browser to the tenant's identity provider and /auth/callback consumes the return, signs the browser in and sets the session cookie, and /auth/error sends a return that failed back to /login naming why. Opt-in: install beside 'mantra' on a site whose tenant has auth:sso; without it these paths 404.", + bindings: [ + { path: '/auth/start', task_identifier: 'mantra:oauth_start', anonymous: true }, + { path: '/auth/callback', task_identifier: 'mantra:oauth_callback', anonymous: true }, + // Where a return that failed is sent: the tenant's oauth_error_redirect_path + // defaults here, so without it a cancelled sign-in ends on a 404. + { path: '/auth/error', task_identifier: 'mantra:oauth_error', anonymous: true }, + ], +}; diff --git a/packages/node-type-registry/src/content-presets/types.ts b/packages/node-type-registry/src/content-presets/types.ts index 39eae6f844..2b83201bd5 100644 --- a/packages/node-type-registry/src/content-presets/types.ts +++ b/packages/node-type-registry/src/content-presets/types.ts @@ -15,10 +15,18 @@ * lookup — these are simply the ones we ship. */ +import type { UIDocument } from 'blocks-schema'; + import type { LimitDefault, TrustLadderRung } from '../module-presets/types'; /** The catalog kinds a content preset can be authored for. */ -export type ContentPresetKind = 'trust_ladder' | 'limit_defaults'; +export type ContentPresetKind = + | 'trust_ladder' + | 'limit_defaults' + | 'route_bindings' + | 'pages' + | 'robots' + | 'principal'; /** Fields every content preset carries, whatever its kind. */ type ContentPresetBase = { @@ -46,11 +54,219 @@ export type LimitBaselinePreset = ContentPresetBase & { limits: LimitDefault[]; }; -export type ContentPreset = TrustLadderPreset | LimitBaselinePreset; +/** + * One URL path served by one named function task, e.g. + * `/login` -> `mantra:signin`. The task identifier is resolved through the + * functions catalog at install time, so a binding names a task and never an + * image, a scope, or a URL. + */ +export type FunctionRouteBinding = { + /** Path the route claims on the site's hostname; never `/` or a catch-all. */ + path: string; + /** Published function task that serves it. */ + task_identifier: string; + /** + * Whether the installed route answers callers carrying no identity. A page + * set whose sign-in surface required a session would be unreachable, so a + * binding states its half of the anonymous contract here; the targeted + * definition must itself declare `anonymous_callable`. + */ + anonymous?: boolean; +}; + +/** + * One URL path the edge answers with a redirect onto another path of the same + * hostname, e.g. `/` -> `/login` on a host that exists only to serve a page set. + * A row in the routing plane's redirects table, not a function: no backend is + * involved. The one binding kind allowed to take over an existing route — the + * placeholder root the route guard created targeting the site itself. + */ +export type RedirectRouteBinding = { + /** Path the route claims on the site's hostname. */ + path: string; + target: 'redirect'; + /** Destination path on the same hostname; must start with `/`. */ + to_path: string; + /** HTTP status the edge answers with; 302 when omitted. */ + status_code?: 301 | 302 | 307 | 308; + /** Whether the installed route answers callers carrying no identity. */ + anonymous?: boolean; +}; + +/** One entry of a route-bindings preset. */ +export type RouteBinding = FunctionRouteBinding | RedirectRouteBinding; + +/** + * A named set of path -> task bindings installed onto a site as ordinary + * function-target routes. Which paths a page set owns is a product decision, so + * it is a catalog row rather than a list inside a generator. + */ +export type RouteBindingsPreset = ContentPresetBase & { + kind: 'route_bindings'; + bindings: RouteBinding[]; +}; + +/** + * One starter page of prose: a path and the `{title, body}` content a site's + * merkle-backed pages store at it. `body` is blank-line-separated prose, + * rendered escaped — never markup. It states no `kind` because untagged content + * *is* prose to the page handlers, which is what every page written before the + * discriminator existed holds. + */ +export type ProsePageDocument = { + /** Path the page is served at on the site's hostname. */ + path: string; + /** The page's own heading. */ + title: string; + /** Blank-line-separated prose. */ + body: string; +}; + +/** + * One starter page whose content is a block `UIDocument` — the blocks spec's + * JSON, served by the page handlers' document renderer rather than as prose. + * + * A layout is exactly this: a document with `Slot` nodes, stored at the reserved + * `_layout/` path a request can never ask for, so the template a site + * serves its pages in is a page row it owns, versioned by its own publishing. + */ +export type BlockPageDocument = { + /** Path the page is served at, or `_layout/` for a layout. */ + path: string; + /** What the content holds, read by the page handlers before rendering it. */ + kind: 'block_document'; + /** The page's own heading, beside the document rather than in it. */ + title: string; + /** The document itself, as `blocks-schema` accepts it. */ + document: UIDocument; +}; + +/** One starter page, of either content kind the page handlers serve. */ +export type PageDocument = ProsePageDocument | BlockPageDocument; + +/** + * A named set of starter pages a site seeds into its merkle-backed pages and + * then authors over. Installed as page rows — versioned by the site's own + * publishing — never as a configuration blob. + */ +export type PagesPreset = ContentPresetBase & { + kind: 'pages'; + pages: PageDocument[]; +}; + +/** + * One line of a `robots.txt`, in file order — a `User-agent:` group header, a + * `Disallow:`, or an empty string separating groups. Lines rather than a parsed + * shape because robots.txt is a line-oriented file whose grouping *is* its + * order: a site's `robots` column is emitted verbatim, so what is authored here + * is exactly what a crawler reads. + */ +export type RobotsDirective = string; + +/** + * A named starter `robots.txt` body a site adopts into its `robots` column. + * Which crawlers a tenant feeds is a product decision, so it is a catalog row + * rather than a list inside the emitter. + */ +export type RobotsPreset = ContentPresetBase & { + kind: 'robots'; + directives: RobotsDirective[]; +}; + +/** + * The capability posture a principal preset grants at one membership scope. + * Capabilities are named, never bit positions: the generated + * `create_principal_from_preset` resolves each name against the tenant's own + * capabilities table at instantiation, so one catalog row fits every tenant + * whatever its bit width, and a name the tenant does not know fails loudly + * instead of silently narrowing. + */ +export type PrincipalPresetScope = { + /** Membership scope the mask applies at: `app` or `org`. */ + membership_type: 'app' | 'org'; + /** + * Capability names the principal keeps at this scope. The owner's own + * capabilities are AND-ed with this set, so it can only narrow — an empty + * list keeps membership (reads) and drops every capability bit. `null` is + * no mask at all: the principal keeps every bit the owner holds there. + */ + allowed_mask_capabilities: string[] | null; +}; + +/** + * Credential lifetimes a preset asks for. Each is an interval literal and may + * only cap the tenant's `auth_settings` defaults, never exceed them. + */ +export type PrincipalPresetCredentials = { + api_key_ttl: string; + access_token_ttl: string; + refresh_token_ttl: string; + max_chain_age: string; +}; + +/** + * The shape `create_principal_from_preset` instantiates. `permissions` in the + * planning text is `scopes[].allowed_mask_capabilities` plus `is_read_only`; + * `session_settings` is `credentials`. There is no `invocable_by`: only the + * owning human may instantiate a principal, and organization reach is fenced + * by the owner's own membership. + */ +export type PrincipalPresetDefinition = { + is_read_only: boolean; + use_admin_owner: boolean; + bypass_step_up: boolean; + scopes: PrincipalPresetScope[]; + /** `require_list`: the caller must scope the principal to named entities; `inherit_owner`: optional, defaults to the owner's reach. */ + entity_policy: 'require_list' | 'inherit_owner'; + delegation: { + allowed: boolean; + max_depth: number; + }; + credentials: PrincipalPresetCredentials; +}; + +/** + * A named blueprint for a principal — read-only analyst, deploy bot — that a + * human instantiates in one call instead of composing create_principal + + * set_principal_scope + set_principal_entities by hand. Catalog data, not + * code: the row names capabilities and lifetimes, and the generated function + * resolves them against the tenant it runs in. + */ +export type PrincipalPreset = ContentPresetBase & { + kind: 'principal'; + definition: PrincipalPresetDefinition; +}; + +export type ContentPreset = + | TrustLadderPreset + | LimitBaselinePreset + | RouteBindingsPreset + | PagesPreset + | RobotsPreset + | PrincipalPreset; -/** The document provisioning installs for a preset: an array of rows. */ +/** The document provisioning installs for a preset: an array of rows, or one object for a principal. */ export function contentPresetDefinition( preset: ContentPreset -): TrustLadderRung[] | LimitDefault[] { - return preset.kind === 'trust_ladder' ? preset.rungs : preset.limits; +): + | TrustLadderRung[] + | LimitDefault[] + | RouteBinding[] + | PageDocument[] + | RobotsDirective[] + | PrincipalPresetDefinition { + switch (preset.kind) { + case 'principal': + return preset.definition; + case 'trust_ladder': + return preset.rungs; + case 'limit_defaults': + return preset.limits; + case 'route_bindings': + return preset.bindings; + case 'pages': + return preset.pages; + case 'robots': + return preset.directives; + } } diff --git a/packages/node-type-registry/src/data/check-owned-relation.ts b/packages/node-type-registry/src/data/check-owned-relation.ts index 673c6b2b5d..920c8e1003 100644 --- a/packages/node-type-registry/src/data/check-owned-relation.ts +++ b/packages/node-type-registry/src/data/check-owned-relation.ts @@ -49,6 +49,11 @@ export const CheckOwnedRelation: NodeTypeDefinition = { type: 'boolean', description: "Admit the same database's global-scope rows (app/platform, ownerless by construction) for this column, for pointers whose legal target set is a scope hierarchy within one database", default: false + }, + allow_frame_chain: { + type: 'boolean', + description: "Admit rows owned by any frame on the referencing row's own scope-frame chain (its own scopes, then the platform database's chain) for this column, for pointers naming a definition published UP the hierarchy — the shared platform function image a tenant route targets. Ancestry only: a peer or another keyed owner is on no chain. Requires owner_key_field_name", + default: false } }, required: ['field_name', 'link_table_name'] diff --git a/packages/node-type-registry/src/data/data-capabilities.ts b/packages/node-type-registry/src/data/data-capabilities.ts index 4c872bb66e..acced3620e 100644 --- a/packages/node-type-registry/src/data/data-capabilities.ts +++ b/packages/node-type-registry/src/data/data-capabilities.ts @@ -16,8 +16,19 @@ export const DataCapabilities: NodeTypeDefinition = { default: 'required_capabilities' }, capabilities: { - type: 'string', - description: 'Selects the capabilities module whose bit numbering the mask is measured in, by scope (e.g. "app", "org") or by table prefix. Required only when the database has more than one; several with no selector raises naming the candidates.' + type: 'object', + description: 'Selector for the capabilities module whose bit numbering the mask is measured in, e.g. {"scope": "org"}. Every key given must match exactly one module; none or several raises naming the candidates. Required only when the database has more than one.', + properties: { + scope: { + type: 'string', + description: 'Scope the module is installed at ("app", "org", or an entity type prefix).' + }, + prefix: { + type: 'string', + description: 'Table prefix of the module instance; rarely needed since prefix follows scope.' + } + }, + additionalProperties: false }, default: { type: 'array', diff --git a/packages/node-type-registry/src/data/data-inherit-from-parent.ts b/packages/node-type-registry/src/data/data-inherit-from-parent.ts index ccb7f1b900..8c9b408b24 100644 --- a/packages/node-type-registry/src/data/data-inherit-from-parent.ts +++ b/packages/node-type-registry/src/data/data-inherit-from-parent.ts @@ -5,7 +5,7 @@ export const DataInheritFromParent: NodeTypeDefinition = { slug: 'data_inherit_from_parent', category: 'data', display_name: 'Inherit From Parent', - description: 'BEFORE INSERT trigger that copies specified fields from a parent table via a foreign key. The parent row is looked up through RLS (SECURITY INVOKER), so the insert fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files.', + description: 'BEFORE INSERT OR UPDATE trigger that copies specified fields from a parent table via a foreign key; on UPDATE the fields are re-copied only when the parent FK changes. The parent row is looked up through RLS (SECURITY INVOKER), so the insert or update fails if the caller cannot see the parent. Used by the storage module to inherit owner_id and is_public from buckets to files.', parameter_schema: { type: 'object', properties: { diff --git a/packages/node-type-registry/src/data/data-member-owner.ts b/packages/node-type-registry/src/data/data-member-owner.ts index 795a3ff3e0..8b0d2d8e31 100644 --- a/packages/node-type-registry/src/data/data-member-owner.ts +++ b/packages/node-type-registry/src/data/data-member-owner.ts @@ -42,8 +42,7 @@ export const DataMemberOwner: NodeTypeDefinition = { }, membership_type: { type: 'integer', - description: 'Membership type resolved from the scope. Internal: prefer entity_type. Cannot be combined with entity_type.', - default: null + description: 'Membership type resolved from the scope. Internal: prefer entity_type. Cannot be combined with entity_type.' } } }, diff --git a/packages/node-type-registry/src/data/search-bm25.ts b/packages/node-type-registry/src/data/search-bm25.ts index 87f8618c38..f902b66146 100644 --- a/packages/node-type-registry/src/data/search-bm25.ts +++ b/packages/node-type-registry/src/data/search-bm25.ts @@ -21,13 +21,11 @@ export const SearchBm25: NodeTypeDefinition = { }, k1: { type: 'number', - description: 'BM25 k1 parameter: term frequency saturation (typical: 1.2-2.0)', - default: null + description: 'BM25 k1 parameter: term frequency saturation (typical: 1.2-2.0)' }, b: { type: 'number', - description: 'BM25 b parameter: document length normalization (0=none, 1=full, typical: 0.75)', - default: null + description: 'BM25 b parameter: document length normalization (0=none, 1=full, typical: 0.75)' }, search_score_weight: { type: 'number', diff --git a/packages/node-type-registry/src/job/trigger.ts b/packages/node-type-registry/src/job/trigger.ts index aa9dbe866d..b827f698c0 100644 --- a/packages/node-type-registry/src/job/trigger.ts +++ b/packages/node-type-registry/src/job/trigger.ts @@ -106,6 +106,11 @@ export const JobTrigger: NodeTypeDefinition = { type: 'string', description: 'Job queue name for routing to specific workers' }, + queue_key_field: { + type: 'string', + format: 'column-ref', + description: 'Column whose value keys the job queue, so the queue name becomes ":". A named queue is held for the whole job, so a shared literal queue serializes every job that uses it; keying on the work\'s subject keeps same-subject jobs ordered while unrelated subjects run in parallel.' + }, priority: { type: 'integer', description: 'Job priority (lower = higher priority)', diff --git a/packages/node-type-registry/src/limit/enforce-feature.ts b/packages/node-type-registry/src/limit/enforce-feature.ts index 5a4b5fa5dd..f540c9e16a 100644 --- a/packages/node-type-registry/src/limit/enforce-feature.ts +++ b/packages/node-type-registry/src/limit/enforce-feature.ts @@ -1,3 +1,4 @@ +import { conditionDefs, conditionProperties } from '../conditions'; import type { NodeTypeDefinition } from '../types'; export const LimitEnforceFeature: NodeTypeDefinition = { @@ -6,9 +7,10 @@ export const LimitEnforceFeature: NodeTypeDefinition = { category: 'limit_enforce', display_name: 'Enforce Feature Flag', description: - 'Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE INSERT trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0).', + 'Gates a table behind a feature flag backed by the cap tables. Attaches a BEFORE trigger that checks whether the named feature cap value is > 0. Features are modeled as caps with max=0 (disabled) or max=1 (enabled) in limit_caps / limit_caps_defaults tables. Resolution: COALESCE(per-entity cap, scope default, 0). Gate INSERT and UPDATE when a row can reach the gated state after creation, and narrow the gate with conditions when only some of the table\'s rows are the gated feature.', parameter_schema: { type: 'object', + $defs: conditionDefs, properties: { feature_name: { type: 'string', @@ -51,6 +53,21 @@ export const LimitEnforceFeature: NodeTypeDefinition = { }, required: ['obj_table', 'obj_field'], }, + events: { + type: 'array', + items: { + type: 'string', + enum: ['INSERT', 'UPDATE'], + }, + description: + 'Which DML events the cap gates. UPDATE is required when a row can reach the gated state after creation (e.g. a discriminator flipped from an ungated value to a gated one). DELETE is not supported: a cap answers whether a row may exist.', + default: ['INSERT'], + }, + conditions: { + ...conditionProperties.conditions, + description: + 'Compound conditions for the trigger WHEN clause, so the cap gates a subset of rows rather than the whole table (e.g. only the rows a customer authors on a table the platform also writes). Accepts a single leaf condition, an array of conditions (implicitly AND), or a nested combinator tree ({AND: [...], OR: [...], NOT: {...}}). Each leaf is {field, op, value?, row?, ref?}. Column types are resolved automatically from the table schema.', + }, }, required: ['feature_name'], }, diff --git a/packages/node-type-registry/src/limit/track-usage.ts b/packages/node-type-registry/src/limit/track-usage.ts index 4ceb3e71c5..de1648b105 100644 --- a/packages/node-type-registry/src/limit/track-usage.ts +++ b/packages/node-type-registry/src/limit/track-usage.ts @@ -59,6 +59,12 @@ export const LimitTrackUsage: NodeTypeDefinition = { description: 'Which DML events to attach triggers for', default: ['INSERT', 'DELETE'], }, + enforce: { + type: 'boolean', + description: + 'With INSERT tracked, also attach a BEFORE INSERT gate on check_billing_quota that refuses a row past the allowance (BILLING_QUOTA_EXCEEDED), like the invocation quota gate. Off (default), rows past the allowance are inserted and their charge is refused. A slug with no meter row is never refused.', + default: false, + }, }, required: ['meter_slug'], }, diff --git a/packages/node-type-registry/src/module-presets/auth-byo.ts b/packages/node-type-registry/src/module-presets/auth-byo.ts new file mode 100644 index 0000000000..8c7fa24527 --- /dev/null +++ b/packages/node-type-registry/src/module-presets/auth-byo.ts @@ -0,0 +1,53 @@ +import type { ModulePreset } from './types'; + +/** + * `auth:byo` — Constructive's users, organizations, memberships, + * capabilities, limits, profiles and hierarchy, with no authentication + * surface. Authentication and the API layer belong to the adopter. + * + * Identity arrives on the transaction as the claims contract + * (`docs/architecture/claims-contract.md`): a role (`authenticated` / + * `anonymous`) and `jwt.claims.user_id`. Every Authz* policy the membership + * planes compile reads `jwt_public.current_user_id()`, so nothing here needs + * a session, a credential, or a sign-in procedure. + * + * Invites and events are opt-in: add `invites_module` (needs `emails_module`) + * or `events_module` per scope when the app wants them. + */ +export const PresetAuthByo: ModulePreset = { + name: 'auth:byo', + display_name: 'Bring Your Own Auth', + summary: 'Users + orgs + memberships + capabilities + RLS. Authentication and API layer are yours.', + description: + 'Constructive as the multi-tenant authorization layer underneath your own authentication. ' + + 'You get users, organizations (org memberships, hierarchy, profiles), app and org ' + + 'capabilities and limits, and every Authz* policy type — but no sessions, credentials, ' + + 'emails, or sign_up/sign_in procedures. Your API layer verifies its own tokens and sets the ' + + 'role plus `jwt.claims.user_id` (and ideally `jwt.claims.database_id`) on each transaction; ' + + 'the provider subject is a UUID used directly as `users.id`, and your service role inserts ' + + 'the user row the first time it sees one. Add `invites_module` or `events_module` when you ' + + 'need them.', + good_for: [ + 'Apps that keep an existing IdP (Auth0, Clerk, Supabase Auth, Cognito, in-house)', + 'Teams that run their own API layer and want Constructive orgs, memberships and RLS', + 'B2B apps whose sign-in must stay outside the database', + ], + not_for: [ + 'Apps that want Constructive to own sign-up and sign-in — use `auth:hardened` or `b2b:storage`', + 'Single-tenant apps with no organizations — use `minimal`', + 'Providers whose subject is not a UUID, until a mapping table exists — keep your own map to `users.id`', + ], + modules: [ + 'users_module', + 'membership_types_module', + ['capabilities_module', { scope: 'app' }], + ['capabilities_module', { scope: 'org' }], + ['limits_module', { scope: 'app' }], + ['limits_module', { scope: 'org' }], + ['memberships_module', { scope: 'app' }], + ['memberships_module', { scope: 'org' }], + ['profiles_module', { scope: 'app' }], + ['profiles_module', { scope: 'org' }], + ['hierarchy_module', { scope: 'org' }], + ], +}; diff --git a/packages/node-type-registry/src/module-presets/b2b-saas.ts b/packages/node-type-registry/src/module-presets/b2b-saas.ts new file mode 100644 index 0000000000..84b4771b52 --- /dev/null +++ b/packages/node-type-registry/src/module-presets/b2b-saas.ts @@ -0,0 +1,63 @@ +import { PresetB2bStorage } from './b2b-storage'; +import type { ModulePreset } from './types'; + +/** + * `b2b:saas` — `b2b:storage` plus `billing_provider_module`, the Stripe + * provider bridge. The hosted-tenant shape for a B2B SaaS that bills its own + * end customers. + * + * `b2b:storage` already carries the local billing catalog (`plans_module`, + * `billing_module`, `rate_limit_meters_module`); this preset adds the provider + * tables (customers, products, prices, subscriptions, operations ledger) and + * the row-driven `billing:sync_*` triggers that mirror the catalog to Stripe. + * + * Deliberately no `function_module` / `webhook_module` / `route_module` / + * `namespace_module`: a hosted tenant is served by the platform's shared + * `functions/billing` and `functions/checkout` images, which resolve the + * tenant from the invocation and read that tenant's Stripe key via + * `ctx.secrets` per call. Its webhook signing secrets live in the infra lane + * of the tenant's hook namespace, where the webhook gateway verifies + * deliveries. The sync jobs the triggers enqueue are stamped `scope = 'app'`. + * Every execution for the tenant reads the key and the billing config from the + * nearest store along the frame walk: the tenant's own app-scope stores, which + * `b2b:storage` installs, ahead of the platform's database-scope plane. + * + * Provisioning does not activate billing. The owner sets it up from the + * dashboard's Monetization wizard: routes, key, hook namespace, webhook + * endpoints, `billing:connect` (the half that needs the key), a catalog, and a + * green `billing:doctor` verdict before `enable_billing` turns on. + */ +export const PresetB2bSaas: ModulePreset = { + name: 'b2b:saas', + display_name: 'B2B SaaS + Billing', + summary: + 'b2b:storage plus the Stripe provider bridge (customers, products, prices, subscriptions, operations ledger).', + description: + 'Everything in `b2b:storage`, plus `billing_provider_module`: the Stripe-side mirror of the ' + + 'local billing catalog (customers, products, prices, subscriptions, operations ledger) and ' + + 'the row-driven sync triggers on `plans`, `plan_pricing` and `plan_subscriptions` that ' + + 'enqueue `billing:sync_plan` / `billing:sync_price` / `billing:sync_subscription` at the ' + + '`app` scope. The tenant bills its OWN end customers through its OWN Stripe account: the ' + + "platform's shared `functions/billing` and `functions/checkout` images serve every tenant " + + 'and read `STRIPE_SECRET_KEY` via `ctx.secrets` per invocation (webhook signing secrets ' + + "live in the infra lane of the tenant's hook namespace, where the webhook gateway verifies " + + 'deliveries), so the preset installs no function, webhook, route, or namespace module. ' + + "Provisioning alone does not activate billing — the owner sets it up from the dashboard's " + + 'Monetization wizard: the billing and checkout routes on the tenant host, the Stripe key, ' + + 'a hook namespace with its webhook definitions and endpoints, `billing:connect` (the half ' + + 'that needs the key), a catalog, and a green `billing:doctor` verdict, which ' + + '`database_settings.enable_billing = true` is gated on. Choose this when your B2B app ' + + 'sells plans to its customers and needs the Stripe bridge from day one.', + good_for: [ + 'B2B SaaS that bills its own end customers through its own Stripe account', + 'Apps that sell plans, prices and subscriptions from the local billing catalog', + 'Hosted tenants served by the shared `functions/billing` / `functions/checkout` images' + ], + not_for: [ + 'Apps without customer billing — use `b2b:storage`, which already carries plans, billing and meters', + 'The kitchen-sink / dev shape — use `full`, which adds `function_module` and `namespace_module`', + 'Turnkey billing — activation still needs Stripe secrets, webhook rows, `checkout:session` route rows and `enable_billing`' + ], + modules: [...PresetB2bStorage.modules, 'billing_provider_module'], + extends: ['b2b:storage'] +}; diff --git a/packages/node-type-registry/src/module-presets/b2b-storage.ts b/packages/node-type-registry/src/module-presets/b2b-storage.ts index 509f343849..5e2815fd7d 100644 --- a/packages/node-type-registry/src/module-presets/b2b-storage.ts +++ b/packages/node-type-registry/src/module-presets/b2b-storage.ts @@ -21,7 +21,9 @@ export const PresetB2bStorage: ModulePreset = { 'Everything in `auth:hardened`, plus orgs, invites, capabilities, profiles and hierarchy at ' + 'both app and org membership scopes, an `events_module` at both scopes carrying the ' + '`humanity` trust ladder (so a member can earn `level.reachable` and a policy can gate on ' + - 'it), and `storage_module` for file uploads, exposed on the `storage` API. The storage ' + + 'it), `plans_module` + `billing_module` + `rate_limit_meters_module` (the chain the sync ' + + 'invocation verb requires to rate-limit calls), and `storage_module` for file uploads, ' + + 'exposed on the `storage` API. The storage ' + 'module creates `app_buckets` and `app_files` tables with full RLS: AuthzPublishable for public reads, ' + 'AuthzAppMembership for member access, AuthzDirectOwner for uploader-only modify/delete. ' + 'Entity-type provisioning with a non-empty `storage` array adds per-scope storage tables ' + @@ -74,6 +76,13 @@ export const PresetB2bStorage: ModulePreset = { ['profiles_module', { scope: 'app' }], ['profiles_module', { scope: 'org' }], ['hierarchy_module', { scope: 'org' }], + // Billing & plans: invocation_sync_verb fails closed without a provisioned + // rate_limit_meters_module whose check function is non-empty, and that + // function only exists once billing_module (which needs plans_module) is + // installed — so a B2B tenant could not generate a sync verb at all. + 'plans_module', + 'billing_module', + 'rate_limit_meters_module', ['invites_module', { scope: 'app' }], ['invites_module', { scope: 'org' }], // Binds the database to the typed catalog plane. Buckets are routable diff --git a/packages/node-type-registry/src/module-presets/dependencies.ts b/packages/node-type-registry/src/module-presets/dependencies.ts new file mode 100644 index 0000000000..d9846cb4f3 --- /dev/null +++ b/packages/node-type-registry/src/module-presets/dependencies.ts @@ -0,0 +1,524 @@ +/** + * What a module reads from its siblings, and how to hand `provision_database_modules` + * a module list that already contains them. + * + * Every relationship here mirrors a check in the backend: the module trigger or + * generator saying, at the point it fails, which sibling plane it was reading and + * at which scope. The backend's tests re-derive this table from those checks and + * fail when the two disagree, so the backend stays the source of truth and this + * file cannot drift into being its own invention. + * + * The scope is part of the dependency, not decoration: `user_auth_module` reads + * the *app* memberships plane wherever it is installed, while `invites_module` + * reads the memberships plane *in its own scope* — an org-scoped invites module + * with only an app-scoped memberships plane installed is missing a dependency + * even though `memberships_module` appears in the list. + */ + +import type { BaseModuleOptions, ModuleEntry } from './types'; + +/** + * Where a dependency has to be installed, relative to the module that reads it. + * + * - `same` — the dependent's own scope (`scope => NEW.scope` in SQL). The only + * direction that is ever legal implicitly: a plane is read in the scope that + * owns it, never borrowed from another one. + * - `app` / `org` / `platform` — a fixed scope named by the reader itself. + * - `unscoped` — the lookup filters on `database_id` alone, so any installed + * plane of that kind satisfies it. + * - `runtime` — the scope is computed at write time from data (a policy's + * `membership_type`, for instance), so it cannot be closed over statically. + * Recorded for documentation and excluded from the closure. + */ +export type DependencyScope = + | 'same' + | 'app' + | 'org' + | 'platform' + | 'unscoped' + | 'runtime'; + +/** + * When a dependency applies at all. A trigger that reads a sibling plane only + * under a condition does not make that plane a dependency of every install. + * + * - `entity_scope` — only when the dependent is installed at a scope that names + * an entity (an org's own plane, a user's own plane). Decided from the entity + * side: `entityScopes` below lists the scopes that name an entity, rather than + * mirroring the generators' internal non-entity union, which is documented as + * a provision-time implementation detail that must not become a TS constant. + * - `group_scope` — only when the dependent is a group plane nested under an org, + * which is decided from membership-type data at provision time and cannot be + * read off a module list. Recorded, never closed over. + * - `{ option }` — only when that option is truthy on the dependent's entry. + */ +export type DependencyCondition = + | 'entity_scope' + | 'group_scope' + | { option: string }; + +/** Scopes that name an entity, and so carry an owner a membership plane keys on. */ +export const entityScopes = ['org', 'user'] as const; + +/** One module reading one sibling plane. */ +export interface ModuleDependency { + /** Module that must be installed. */ + module: string; + /** Where it must be installed, relative to the reader. */ + scope: DependencyScope; + /** What the reader wants from it, in the reader's own words. */ + reason: string; + /** Options the auto-added entry carries, beyond `scope`. */ + options?: BaseModuleOptions & Record; + /** When the dependency applies; omitted → always. */ + when?: DependencyCondition; +} + +/** + * Module → the planes its triggers and generators read. + * + * Keyed by module name. A generator that is not itself a module (the group + * triggers `memberships_module` installs, the RLS parser) records its + * dependency under the module that owns it, because that is the entry a caller + * can act on. + */ +export const moduleDependencies: Record = { + billing_provider_module: [ + { + module: 'memberships_module', + scope: 'app', + reason: 'the app manage_billing check its provider key reader runs', + }, + { + module: 'internal_secrets_module', + scope: 'runtime', + reason: 'the store its provider key reader reads (database scope, else app)', + }, + ], + capabilities_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the actor column its grants carry' }, + { + module: 'memberships_module', + scope: 'same', + reason: 'the membership plane its permission bits are packed for', + }, + ], + connected_accounts_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the account owner' }, + ], + crypto_addresses_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the address owner' }, + ], + crypto_auth_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the signer it authenticates' }, + { module: 'user_state_module', scope: 'unscoped', reason: 'the state it flips on sign-in' }, + { module: 'sessions_module', scope: 'unscoped', reason: 'the session it mints' }, + { + module: 'crypto_addresses_module', + scope: 'unscoped', + reason: 'the addresses a signature is checked against', + }, + ], + devices_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the device owner' }], + email_sender_module: [ + { + module: 'internal_secrets_module', + scope: 'runtime', + reason: 'the database-scope credential store read when a platform email module supplies shared transport', + }, + ], + emails_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the address owner' }], + events_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the event actor' }], + hierarchy_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the actor a hierarchy edge is written by' }, + { + module: 'memberships_module', + scope: 'same', + reason: 'the membership plane a hierarchy climb resolves against', + }, + ], + identity_providers_module: [ + { module: 'sessions_module', scope: 'unscoped', reason: 'the session a federated sign-in mints' }, + { + module: 'internal_secrets_module', + scope: 'same', + reason: 'where a provider client secret is stored', + }, + ], + infra_config_module: [ + { + module: 'memberships_module', + scope: 'same', + when: 'entity_scope', + reason: 'the membership plane its config policies read', + }, + { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' }, + ], + infra_secrets_module: [ + { + module: 'memberships_module', + scope: 'same', + when: 'entity_scope', + reason: 'the membership plane its secret policies read', + }, + { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' }, + ], + internal_config_module: [ + { + module: 'memberships_module', + scope: 'same', + when: 'entity_scope', + reason: 'the membership plane its config policies read', + }, + ], + internal_secrets_module: [ + { + module: 'memberships_module', + scope: 'same', + when: 'entity_scope', + reason: 'the membership plane its secret policies read', + }, + ], + invites_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the inviting actor' }, + { + module: 'memberships_module', + scope: 'same', + reason: 'the membership plane an accepted invite writes into', + }, + { module: 'emails_module', scope: 'unscoped', reason: 'the address an invite is sent to' }, + ], + limits_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the actor a limit is spent by' }], + memberships_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the member' }, + { + module: 'membership_types_module', + scope: 'unscoped', + reason: 'the type a membership row carries', + }, + { + module: 'capabilities_module', + scope: 'same', + reason: 'the permission bits its grants and defaults are packed from', + }, + { + module: 'memberships_module', + scope: 'org', + when: 'group_scope', + reason: 'the org plane a group\u2019s ancestor chain terminates at', + }, + ], + notifications_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the notification recipient' }, + { + module: 'user_settings_module', + scope: 'unscoped', + when: { option: 'has_settings_extension' }, + reason: 'the settings table its settings extension reads', + }, + { + module: 'internal_secrets_module', + scope: 'app', + reason: 'where its delivery credentials are stored', + }, + ], + oauth_requests_module: [ + { + module: 'user_auth_module', + scope: 'unscoped', + reason: 'the auth surface link_identity is emitted into and the sessions its step-up reads', + }, + { + module: 'connected_accounts_module', + scope: 'unscoped', + reason: 'where a redeemed link ticket binds the identity', + }, + ], + phone_numbers_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the number owner' }], + // principals_module is not listed: the insert trigger provisions it. + principal_auth_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the human behind a principal' }, + { module: 'sessions_module', scope: 'unscoped', reason: 'the session a principal mints' }, + { module: 'user_auth_module', scope: 'unscoped', reason: 'the auth surface it extends' }, + ], + principals_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the human behind a principal' }, + { module: 'capabilities_module', scope: 'unscoped', reason: 'the bitlen its permission masks use' }, + { + module: 'memberships_module', + scope: 'unscoped', + reason: 'an sprt table to resolve a principal\u2019s bits at runtime', + }, + ], + profiles_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the profile subject' }, + { + module: 'membership_types_module', + scope: 'unscoped', + reason: 'the type a profile is scoped by', + }, + { + module: 'memberships_module', + scope: 'same', + reason: 'the membership plane its visibility policies read', + }, + ], + resource_module: [ + { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' }, + ], + function_deployment_module: [ + { module: 'namespace_module', scope: 'same', reason: 'the K8s namespace it deploys into' }, + ], + graph_module: [ + { + module: 'merkle_store_module', + scope: 'same', + reason: 'the store its graph revisions commit into', + options: { + prefix: 'function_graph', + public_schema_name: 'compute_public', + private_schema_name: 'compute_private', + api_name: 'compute', + capability_key: 'manage_graphs', + }, + }, + ], + rls_module: [ + { module: 'sessions_module', scope: 'unscoped', reason: 'the session its claims are read from' }, + { + module: 'memberships_module', + scope: 'runtime', + reason: 'the sprt table a policy\u2019s membership_type resolves to', + }, + { + module: 'hierarchy_module', + scope: 'runtime', + reason: 'the hierarchy sprt table an org-hierarchy policy reads', + }, + ], + session_secrets_module: [ + { module: 'sessions_module', scope: 'unscoped', reason: 'the sessions it signs' }, + ], + sessions_module: [{ module: 'users_module', scope: 'unscoped', reason: 'the session subject' }], + user_auth_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the account it authenticates' }, + { + module: 'memberships_module', + scope: 'app', + reason: 'the app membership a new account is granted', + }, + { module: 'emails_module', scope: 'unscoped', reason: 'the address sign-up verifies' }, + { module: 'user_state_module', scope: 'unscoped', reason: 'the state sign-in flips' }, + { + module: 'user_credentials_module', + scope: 'unscoped', + reason: 'where a password hash is stored', + }, + { module: 'sessions_module', scope: 'unscoped', reason: 'the session sign-in mints' }, + ], + user_settings_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the settings owner' }, + ], + user_settings_security_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the settings owner' }, + ], + webauthn_auth_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the account it authenticates' }, + { + module: 'webauthn_credentials_module', + scope: 'unscoped', + reason: 'the credentials an assertion is checked against', + }, + { module: 'sessions_module', scope: 'unscoped', reason: 'the session an assertion mints' }, + { module: 'session_secrets_module', scope: 'unscoped', reason: 'the challenge signing key' }, + { + module: 'memberships_module', + scope: 'app', + reason: 'the app membership whose disabled/banned standing a passkey sign-in checks', + }, + { module: 'user_auth_module', scope: 'unscoped', reason: 'the auth surface it extends' }, + ], + webauthn_credentials_module: [ + { module: 'users_module', scope: 'unscoped', reason: 'the credential owner' }, + ], +}; + +/** Options of a module entry, or `{}` for a bare name. */ +function entryOptions(entry: ModuleEntry): BaseModuleOptions & Record { + return typeof entry === 'string' ? {} : ((entry[1] ?? {}) as BaseModuleOptions & Record); +} + +/** Name of a module entry. */ +export function moduleEntryName(entry: ModuleEntry): string { + return typeof entry === 'string' ? entry : entry[0]; +} + +/** + * Does this dependency apply to this entry? An unmet condition is not a missing + * dependency — the reader never looks the plane up. + */ +function applies(dependency: ModuleDependency, entry: ModuleEntry): boolean { + const condition = dependency.when; + if (condition === undefined) return true; + if (condition === 'group_scope') return false; + if (condition === 'entity_scope') { + const scope = entryOptions(entry).scope as string | undefined; + return scope !== undefined && (entityScopes as readonly string[]).includes(scope); + } + return Boolean(entryOptions(entry)[condition.option]); +} + +/** + * The scope a dependency has to be satisfied at, or `null` when it cannot be + * closed over statically (`runtime`) — that dependency is a caller decision + * driven by data, and the database raises a named error if the plane is absent. + */ +function requiredScope( + dependency: ModuleDependency, + dependentScope: string | undefined, +): string | undefined | null { + switch (dependency.scope) { + case 'runtime': + return null; + case 'unscoped': + return undefined; + case 'same': + return dependentScope; + default: + return dependency.scope; + } +} + +/** Does `entries` already carry this module at this scope? */ +function isSatisfied( + entries: ModuleEntry[], + module: string, + scope: string | undefined, +): boolean { + return entries.some((entry) => { + if (moduleEntryName(entry) !== module) return false; + // An unscoped dependency reads whichever plane exists, so any entry answers it. + if (scope === undefined) return true; + return entryOptions(entry).scope === scope; + }); +} + +/** A dependency of a specific entry that the module list does not contain. */ +export interface MissingModuleDependency { + /** Module whose trigger or generator reads the missing plane. */ + dependent: string; + /** Scope the dependent is installed at, when it is a scoped module. */ + dependent_scope?: string; + /** Module that has to be installed. */ + required_module: string; + /** Scope it has to be installed at, when the dependency is scoped. */ + required_scope?: string; + /** What the dependent reads from it. */ + reason: string; + /** The module list entry that satisfies it — add this verbatim. */ + declare: ModuleEntry; +} + +function declarationFor( + dependency: ModuleDependency, + scope: string | undefined, +): ModuleEntry { + const options = { ...(dependency.options ?? {}), ...(scope ? { scope } : {}) }; + if (Object.keys(options).length === 0) return dependency.module; + return [dependency.module, options] as ModuleEntry; +} + +/** + * Every dependency of `modules` that `modules` does not satisfy, transitively: + * an added plane is itself a module with dependencies, so the walk runs to a + * fixpoint over the list as it grows. + * + * Nothing here crosses a database — a module list provisions one database, so + * every dependency is resolved inside it — and nothing crosses a scope except + * where the reader itself names the other scope (`user_auth_module` reading the + * app membership plane, a group trigger reading the org one). A `same`-scope + * dependency is only ever satisfied by a plane in the dependent's own scope, + * never by one that happens to exist elsewhere. + */ +export function findMissingModuleDependencies( + modules: ModuleEntry[], +): MissingModuleDependency[] { + const missing: MissingModuleDependency[] = []; + // Entries the closure has decided on so far: the caller's list plus what has + // already been reported missing, so a plane is reported once, not once per reader. + const known: ModuleEntry[] = [...modules]; + const pending: ModuleEntry[] = [...modules]; + + while (pending.length > 0) { + const entry = pending.shift() as ModuleEntry; + const name = moduleEntryName(entry); + const scope = entryOptions(entry).scope as string | undefined; + + for (const dependency of moduleDependencies[name] ?? []) { + if (!applies(dependency, entry)) continue; + const required = requiredScope(dependency, scope); + if (required === null) continue; + if (dependency.module === name && required === scope) continue; + if (isSatisfied(known, dependency.module, required)) continue; + + const declare = declarationFor(dependency, required); + missing.push({ + dependent: name, + ...(scope ? { dependent_scope: scope } : {}), + required_module: dependency.module, + ...(required ? { required_scope: required } : {}), + reason: dependency.reason, + declare, + }); + known.push(declare); + pending.push(declare); + } + } + + return missing; +} + +/** The same sentence the database raises, for a list that has not been provisioned yet. */ +export function describeMissingModuleDependency( + missing: MissingModuleDependency, +): string { + const at = missing.required_scope ? ` at scope '${missing.required_scope}'` : ''; + const from = missing.dependent_scope + ? `${missing.dependent} (scope '${missing.dependent_scope}')` + : missing.dependent; + return ( + `${from} reads ${missing.required_module}${at} (${missing.reason}), ` + + `which this module list does not install — add ${JSON.stringify(missing.declare)}` + ); +} + +/** + * `modules` plus the dependency closure it is missing. + * + * Caller entries are returned untouched and win every conflict: a plane the + * caller already declared keeps its prefix, storage key, schema names and + * feature flags, and only genuinely absent planes are appended. Appending + * rather than inserting is safe because `provision_database_modules` orders the + * install itself by module group, not by list position. + */ +export function withRequiredModules(modules: ModuleEntry[]): ModuleEntry[] { + return [ + ...modules, + ...findMissingModuleDependencies(modules).map((missing) => missing.declare), + ]; +} + +/** + * Throws unless `modules` is dependency-complete, naming every missing plane and + * the entry that satisfies it. For callers that want the list they wrote to be + * the list that installs — a preset under test, a fixture — rather than one + * silently grown by `withRequiredModules`. + */ +export function assertModuleDependencies(modules: ModuleEntry[]): void { + const missing = findMissingModuleDependencies(modules); + if (missing.length === 0) return; + throw new Error( + `module list is missing ${missing.length} dependenc${missing.length === 1 ? 'y' : 'ies'}:\n` + + missing.map((m) => ` - ${describeMissingModuleDependency(m)}`).join('\n'), + ); +} diff --git a/packages/node-type-registry/src/module-presets/index.ts b/packages/node-type-registry/src/module-presets/index.ts index 9841bd5e45..8c4b095ba0 100644 --- a/packages/node-type-registry/src/module-presets/index.ts +++ b/packages/node-type-registry/src/module-presets/index.ts @@ -1,3 +1,18 @@ +export type { + DependencyCondition, + DependencyScope, + MissingModuleDependency, + ModuleDependency, +} from './dependencies'; +export { + assertModuleDependencies, + describeMissingModuleDependency, + entityScopes, + findMissingModuleDependencies, + moduleDependencies, + moduleEntryName, + withRequiredModules, +} from './dependencies'; export type { AgentModuleOptions, BaseModuleOptions, @@ -15,23 +30,36 @@ export type { } from './types'; import { getModuleType } from '../module-types'; +import { PresetAuthByo } from './auth-byo'; import { PresetAuthHardened } from './auth-hardened'; +import { PresetB2bSaas } from './b2b-saas'; import { PresetB2bStorage } from './b2b-storage'; +import { withRequiredModules } from './dependencies'; import { PresetFull } from './full'; import { PresetMinimal } from './minimal'; import type { ModulePreset } from './types'; -export { PresetAuthHardened, PresetB2bStorage, PresetFull, PresetMinimal }; +export { + PresetAuthByo, + PresetAuthHardened, + PresetB2bSaas, + PresetB2bStorage, + PresetFull, + PresetMinimal, +}; /** - * Ordered list of all shipped module presets, from smallest to largest - * module footprint. Stable ordering — CLIs / UIs can present this directly. + * Ordered list of all shipped module presets. Registration order: new presets + * are appended, never inserted, because the backend seeds the presets in this + * order, and an insert in the middle would rewrite presets already applied. */ export const allModulePresets: ModulePreset[] = [ PresetMinimal, PresetAuthHardened, PresetB2bStorage, PresetFull, + PresetB2bSaas, + PresetAuthByo, ]; /** Look up a preset by name. Returns undefined if the name isn't known. */ @@ -43,12 +71,24 @@ function moduleName(entry: ModulePreset['modules'][number]): string { return typeof entry === 'string' ? entry : entry[0]; } +/** + * The modules a preset installs. + * + * `includeDependencies` appends the planes the listed modules read but the + * preset does not name — the same closure a provisioner would otherwise fail + * on, in the scope each dependent asked for. It is opt-in because the shipped + * presets are already dependency-complete (a test asserts that), so the closure + * only matters for a caller-assembled list. + */ export function resolvePresetModules( preset: ModulePreset, - options: { includeInternal?: boolean } = {}, + options: { includeInternal?: boolean; includeDependencies?: boolean } = {}, ): ModulePreset['modules'] { - if (options.includeInternal) return preset.modules; - return preset.modules.filter( + const modules = options.includeDependencies + ? withRequiredModules(preset.modules) + : preset.modules; + if (options.includeInternal) return modules; + return modules.filter( (entry) => !getModuleType(moduleName(entry))?.internal, ); } diff --git a/packages/node-type-registry/src/module-presets/types.ts b/packages/node-type-registry/src/module-presets/types.ts index e7a902d7f5..954a101053 100644 --- a/packages/node-type-registry/src/module-presets/types.ts +++ b/packages/node-type-registry/src/module-presets/types.ts @@ -35,6 +35,14 @@ export type BaseModuleOptions = { private_schema_name?: string; /** RLS policy overrides for the module's tables. */ policies?: unknown[]; + /** + * Which of the scope's storage planes this module binds to, for the modules + * that carry a typed bucket reference (site_surface, route, function). A scope + * has exactly one plane of every other kind, but may carry several storage + * planes, each with its own semantic `key` — so the binding is named rather + * than guessed. Defaults to 'default'. + */ + storage_key?: string; }; /** @@ -77,12 +85,19 @@ export type AgentModuleOptions = BaseModuleOptions & { has_plans?: boolean; has_resources?: boolean; has_agents?: boolean; + has_repository_resources?: boolean; has_runs?: boolean; resources?: unknown[]; }; /** Storage module feature flags. */ export type StorageModuleOptions = BaseModuleOptions & { + /** + * Semantic identity of this plane within its scope, and what a consuming + * module names in `storage_key`. Unique per (database, scope); `prefix` only + * names the generated tables. Defaults to 'default'. + */ + key?: string; has_versioning?: boolean; has_content_hash?: boolean; has_custom_keys?: boolean; @@ -113,6 +128,17 @@ export type TrustLadderRung = { limit?: string; /** Credits deposited into `limit`; defaults to 0. */ limit_amount?: number; + /** Counting window of `event`, an interval literal ('30 days'); omitted counts for life. */ + period_interval?: string; + /** How long a grant of `level` lasts before it lapses; omitted never lapses. */ + expires_interval?: string; + /** Event names whose recording for an actor revokes `level` and resets their progress toward it. */ + revoked_by?: string[]; + /** + * Permission names (this scope's own catalog) withheld from principals until + * they hold `level`. An unknown name fails the seed rather than un-gating. + */ + unlocks?: string[]; }; /** One baseline limit: a row in the tenant's default-limits table. */ @@ -141,11 +167,12 @@ export type LimitsModuleOptions = BaseModuleOptions & { * the content catalog — `'humanity'` for evidence that an account belongs to * someone (one reachable channel plus onboarding), `'metered'` where capacity * is rationed (reachable → accountable → established → trusted → vouched) — - * and an array is the caller's own ladder inline. App scope only — an entity ladder belongs to an - * organization that does not exist at provision time. + * and an array of rungs is the caller's own ladder inline. An array of slugs + * seeds several presets into one ladder (`['humanity', 'agent']`). At entity + * scope the same content is seeded per entity, on the entity's own insert. */ export type EventsModuleOptions = BaseModuleOptions & { - trust_ladder?: string | TrustLadderRung[]; + trust_ladder?: string | string[] | TrustLadderRung[]; }; /** Catalog module options (table-name overrides). */ diff --git a/packages/node-type-registry/src/module-types/index.ts b/packages/node-type-registry/src/module-types/index.ts index 2d970d1d0d..5b7d5d4cfb 100644 --- a/packages/node-type-registry/src/module-types/index.ts +++ b/packages/node-type-registry/src/module-types/index.ts @@ -81,6 +81,12 @@ export const allModuleTypes: ModuleTypeDefinition[] = [ display_name: 'Database Usage', description: 'Provisions database usage logging.' }, + { + name: 'refusal_log_module', + display_name: 'Refusal Log', + description: 'Provisions the platform-only admission-control refusal ledger and its daily rollup.', + internal: true + }, { name: 'devices_module', display_name: 'Devices', @@ -266,7 +272,12 @@ export const allModuleTypes: ModuleTypeDefinition[] = [ { name: 'principal_auth_module', display_name: 'Principal Auth', - description: 'Provisions principal authentication state.' + description: 'Provisions credentials for principals: API keys, child sessions and token exchange.' + }, + { + name: 'principals_module', + display_name: 'Principals', + description: 'Provisions principals as authorization data: scoped sub-identities, their capability masks and entity scope.' }, { name: 'profiles_module', diff --git a/packages/node-type-registry/src/process/chunks.ts b/packages/node-type-registry/src/process/chunks.ts index 12bd270a1a..e465edcb14 100644 --- a/packages/node-type-registry/src/process/chunks.ts +++ b/packages/node-type-registry/src/process/chunks.ts @@ -38,6 +38,15 @@ export const ProcessChunks: NodeTypeDefinition = { description: 'Name of the text content column in the chunks table', default: 'content' }, + source_fields: { + type: 'array', + items: { type: 'string', format: 'column-ref' }, + description: + 'Parent columns the chunks are cut from. When set, the enqueue ' + + 'triggers fire only once one of them is populated (INSERT) or ' + + 'changed (UPDATE), and the worker chunks exactly those columns. ' + + 'Omit to chunk every readable content column on every write.' + }, // ── Chunking strategy ────────────────────────────────────────── chunk_size: { diff --git a/packages/node-type-registry/src/process/custom.ts b/packages/node-type-registry/src/process/custom.ts new file mode 100644 index 0000000000..63fff8080c --- /dev/null +++ b/packages/node-type-registry/src/process/custom.ts @@ -0,0 +1,105 @@ +import { conditionDefs, triggerConditionsProperty } from '../conditions'; +import type { NodeTypeDefinition } from '../types'; + +/** + * Tenant-defined file processing node. + * + * The built-in Process* nodes are wired to platform tasks and platform + * writers. ProcessCustom wires a storage module's files table to a task the + * tenant registered itself (`register_function --scope database`): when a file + * reaches status = 'uploaded' the job is enqueued through the quota-gated + * function_invocations ledger, and the generated SECURITY DEFINER writer + * `_write_(file_id, result)` is the one way the tenant's + * function, over the pg-wire function lane, lands its result and moves the + * row uploaded → processed. The node provisions nothing else: the generator + * refuses when the task is not registered, when the table is not a storage + * files table, or when the module has no confirm-upload loop. + */ +export const ProcessCustom: NodeTypeDefinition = { + name: 'ProcessCustom', + slug: 'process_custom', + category: 'process', + display_name: 'Custom File Processing', + description: + 'Enqueues a tenant-registered task when a file on a storage files table reaches ' + + 'status = \'uploaded\' and generates the result writer ' + + 'the task calls back over the function lane. The task must already be registered ' + + 'for the database (register_function with scope database); the node is refused otherwise.', + parameter_schema: { + type: 'object', + $defs: conditionDefs, + required: ['task_identifier'], + properties: { + + // ── Job routing ─────────────────────────────────────────────── + task_identifier: { + type: 'string', + format: 'function-ref', + description: + 'Task identifier of the tenant-registered function (namespace:name). ' + + 'Must resolve through the function registry for this database at provisioning time.' + }, + + // ── Output field ────────────────────────────────────────────── + result_field: { + type: 'string', + format: 'column-ref', + description: + 'Optional jsonb field on the files table that receives the result the task ' + + 'hands to the generated writer. When omitted the writer only records the ' + + 'uploaded → processed transition.' + }, + + // ── MIME scoping ────────────────────────────────────────────── + mime_patterns: { + type: 'array', + items: { type: 'string' }, + description: + 'Optional MIME type LIKE patterns to match. Multiple patterns are OR\'d together. ' + + 'When omitted every uploaded file is processed.' + }, + trigger_conditions: triggerConditionsProperty, + + // ── Entity billing scope ────────────────────────────────────── + entity_field: { + type: 'string', + format: 'column-ref', + description: 'Column on the files table that holds (or references) the entity_id for billing scope. Forwarded to the composed JobTrigger.' + }, + entity_lookup: { + type: 'object', + description: 'FK lookup configuration for resolving entity_id through a related table. Forwarded to the composed JobTrigger.', + properties: { + obj_table: { type: 'string', description: 'Name of the related table to look up entity_id from' }, + obj_schema: { type: 'string', description: 'Schema of the related table (user-facing name, optional)' }, + obj_field: { type: 'string', format: 'column-ref', description: 'Column on the related table that holds the entity_id' } + }, + required: ['obj_table', 'obj_field'] + }, + + // ── Job options ─────────────────────────────────────────────── + queue_name: { + type: 'string', + description: 'Job queue name for the task', + default: 'process_custom' + }, + max_attempts: { + type: 'integer', + description: 'Maximum number of retry attempts', + default: 5 + }, + priority: { + type: 'integer', + description: 'Job priority (lower = higher priority)', + default: 0 + } + } + }, + tags: [ + 'custom', + 'files', + 'processing', + 'jobs', + 'functions' + ] +}; diff --git a/packages/node-type-registry/src/process/extraction.ts b/packages/node-type-registry/src/process/extraction.ts index a8b1da54ef..9c9b73e679 100644 --- a/packages/node-type-registry/src/process/extraction.ts +++ b/packages/node-type-registry/src/process/extraction.ts @@ -4,10 +4,12 @@ import type { NodeTypeDefinition } from '../types'; /** * File extraction processing node. * - * Composes a JobTrigger that fires when a file transitions to status = 'uploaded'. - * The trigger enqueues a - * text-extraction job that converts the file contents (PDF, DOCX, HTML, etc.) - * into plain text or markdown, storing the result in configurable output fields. + * Composes a JobTrigger that enqueues a text-extraction job converting the file + * contents (PDF, DOCX, HTML, etc.) into plain text or markdown, storing the + * result in configurable output fields. On a storage module's files table the + * trigger fires when the file transitions to status = 'uploaded'; on a business + * table with an upload/image column it fires on the configured events (INSERT + * by default, plus an UPDATE that changes the file when no events are given). * * The extraction worker is external (Knative function) — this node only creates * the trigger infrastructure and output fields. The worker calls back into the @@ -20,7 +22,8 @@ export const ProcessExtraction: NodeTypeDefinition = { display_name: 'File Extraction', description: 'Creates extraction output fields and a job trigger for file text extraction. ' + - 'Fires when a file is uploaded (status = \'uploaded\') or on INSERT. ' + + 'On a storage files table it fires when the file reaches status = \'uploaded\'; ' + + 'on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. ' + 'The external worker extracts text/metadata from the file (PDF, DOCX, HTML, etc.) ' + 'and writes the result back to the configured output fields. ' + 'Typically used upstream of ProcessFileEmbedding or ProcessChunks.', @@ -68,6 +71,38 @@ export const ProcessExtraction: NodeTypeDefinition = { default: ['application/pdf', 'text/%'] }, + routes: { + type: 'array', + items: { + type: 'object', + properties: { + mime_patterns: { + type: 'array', + items: { type: 'string' }, + minItems: 1, + description: 'MIME type LIKE patterns this route takes, e.g. [\'application/vnd.openxmlformats-officedocument.%\'].' + }, + task_identifier: { + type: 'string', + format: 'function-ref', + description: 'Job task identifier of the function that extracts these MIME types' + }, + extraction_model: { type: 'string', description: 'Extraction model for this route; the node\'s when omitted' }, + extraction_provider: { type: 'string', description: 'Extraction provider for this route; the node\'s when omitted' }, + queue_name: { type: 'string', description: 'Job queue name for this route; the node\'s when omitted' }, + max_attempts: { type: 'integer', description: 'Maximum retry attempts for this route; the node\'s when omitted' }, + priority: { type: 'integer', description: 'Job priority for this route; the node\'s when omitted' } + }, + required: ['mime_patterns', 'task_identifier'] + }, + description: + 'MIME types sent to another extraction function. A file runs the first route whose mime_patterns match it; ' + + 'the node\'s own mime_patterns and task_identifier take only the files no route matched, so one file never runs two functions. ' + + 'Every route writes the node\'s text_field and metadata_field, and shares its file_field, events, trigger_conditions and billing scope. ' + + 'A task is named once across the node and its routes (PROCESS_EXTRACTION_DUPLICATE_ROUTE_TASK). ' + + 'Example: [{"mime_patterns": ["application/vnd.openxmlformats-officedocument.%"], "task_identifier": "office:extract_text"}].' + }, + // ── Job routing ─────────────────────────────────────────────── task_identifier: { type: 'string', @@ -78,7 +113,10 @@ export const ProcessExtraction: NodeTypeDefinition = { events: { type: 'array', items: { type: 'string', enum: ['INSERT', 'UPDATE'] }, - description: 'Trigger events that fire the job', + description: + 'Trigger events that fire the job on a business table. Ignored on a storage ' + + 'files table, where the trigger is always the status transition to uploaded ' + + '(INSERT is rejected there: the row is still requested).', default: ['INSERT'] }, file_field: { @@ -89,7 +127,8 @@ export const ProcessExtraction: NodeTypeDefinition = { 'When set, the trigger reads the object key, MIME type and bucket id ' + 'out of that document (NEW. ->> \'key\', ...) instead of ' + 'requiring key/mime_type/bucket_id columns beside it, and the MIME ' + - 'patterns match against ->> \'mime\'.' + 'patterns match against ->> \'mime\'. ' + + 'The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and text_field (created as jsonb) and metadata_field hold one entry per element, as jsonb objects keyed by the element\'s object key.' }, payload_custom: { type: 'object', diff --git a/packages/node-type-registry/src/process/file-embedding.ts b/packages/node-type-registry/src/process/file-embedding.ts index d68386bae3..49b13466d7 100644 --- a/packages/node-type-registry/src/process/file-embedding.ts +++ b/packages/node-type-registry/src/process/file-embedding.ts @@ -10,7 +10,10 @@ export const ProcessFileEmbedding: NodeTypeDefinition = { 'Generic, MIME-scoped embedding node for file tables. Supports two modes: ' + 'direct (whole-file to single vector, e.g. CLIP for images) when extraction ' + 'is omitted, or extract (file to text to chunks to per-chunk vectors) when ' + - 'extraction config is provided. Composes SearchVector + JobTrigger + ' + + 'extraction config is provided; extract mode composes ProcessExtraction for the text ' + + '(its task, MIME rule, queue and, on a storage files table, its result writer). On a storage files table it fires when the file reaches status = \'uploaded\'; ' + + 'on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. ' + + 'Composes SearchVector + JobTrigger + ' + 'ProcessChunks (enabled by default in extract mode) internally. Multiple ' + 'instances can coexist on the same table with different MIME scopes, field ' + 'names, and embedding strategies.', @@ -70,8 +73,9 @@ export const ProcessFileEmbedding: NodeTypeDefinition = { items: { type: 'string' }, description: 'MIME type LIKE patterns to match. Multiple patterns are OR\'d together. ' + - 'Examples: [\'image/%\'], [\'application/pdf\', \'text/%\'], [\'audio/%\'].', - default: ['image/%'] + 'Examples: [\'image/%\'], [\'application/pdf\', \'text/%\'], [\'audio/%\']. ' + + 'Defaults to [\'image/%\'] in direct mode and to [\'application/pdf\', \'text/%\'] ' + + 'in extract mode.' }, // ── Job routing ──────────────────────────────────────────────── @@ -80,13 +84,16 @@ export const ProcessFileEmbedding: NodeTypeDefinition = { format: 'function-ref', description: 'Job task identifier for the worker. In direct mode this is the ' + - 'embedding worker; in extract mode this is the extraction worker.', - default: 'embedding:process_file_embedding' + 'embedding worker (default embedding:process_file_embedding); in extract mode ' + + 'this is the extraction worker (default document:extract_file_text).' }, events: { type: 'array', items: { type: 'string', enum: ['INSERT', 'UPDATE'] }, - description: 'Trigger events that fire the job', + description: + 'Trigger events that fire the job on a business table. Ignored on a storage ' + + 'files table, where the trigger is always the status transition to uploaded ' + + '(INSERT is rejected there: the row is still requested).', default: ['INSERT'] }, file_field: { @@ -97,7 +104,8 @@ export const ProcessFileEmbedding: NodeTypeDefinition = { 'When set, the trigger reads the object key, MIME type and bucket id ' + 'out of that document (NEW. ->> \'key\', ...) instead of ' + 'requiring key/mime_type/bucket_id columns beside it, and the MIME ' + - 'patterns match against ->> \'mime\'.' + 'patterns match against ->> \'mime\'. ' + + 'An array column (image[]/upload[]) is refused (PROCESS_FILE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element.' }, payload_custom: { type: 'object', @@ -175,10 +183,11 @@ export const ProcessFileEmbedding: NodeTypeDefinition = { extraction: { type: 'object', description: - 'Text extraction configuration. When present, the generator creates ' + - 'extraction output fields on the table and configures SearchVector with ' + - 'source_fields + stale tracking. When absent, the node operates in direct ' + - 'mode (single vector per file, no text extraction).', + 'Text extraction configuration. When present, the node composes ProcessExtraction ' + + '(output fields, MIME-conditional trigger on queue extraction with 5 attempts, and ' + + 'on a storage files table the _write_extraction writer) and configures ' + + 'SearchVector with the text field as source_fields + stale tracking. When absent, ' + + 'the node operates in direct mode (single vector per file, no text extraction).', properties: { text_field: { type: 'string', @@ -191,6 +200,20 @@ export const ProcessFileEmbedding: NodeTypeDefinition = { format: 'column-ref', description: 'JSONB field for extraction metadata (page count, language, etc.)', default: 'extracted_metadata' + }, + routes: { + type: 'array', + items: { + type: 'object', + properties: { + mime_patterns: { type: 'array', items: { type: 'string' }, minItems: 1 }, + task_identifier: { type: 'string', format: 'function-ref' } + }, + required: ['mime_patterns', 'task_identifier'] + }, + description: + 'MIME types sent to another extraction function, as ProcessExtraction.routes: ' + + 'the first matching route takes a file, and the node\'s own mime_patterns and task take the rest.' } } }, diff --git a/packages/node-type-registry/src/process/image-embedding.ts b/packages/node-type-registry/src/process/image-embedding.ts index 1456037f86..efed6fadc0 100644 --- a/packages/node-type-registry/src/process/image-embedding.ts +++ b/packages/node-type-registry/src/process/image-embedding.ts @@ -6,9 +6,13 @@ import type { NodeTypeDefinition } from '../types'; * * At the SQL layer, data_image_embedding delegates entirely to * data_file_embedding, merging image-specific defaults before forwarding. - * The parameter schema here is intentionally identical to ProcessFileEmbedding; - * only the defaults differ (dimensions: 512, task: embedding:process_image_embedding, - * mime_patterns: ['image/%']). + * The parameter schema is ProcessFileEmbedding's minus extraction/chunks — it + * is direct mode only until an OCR worker exists — and the defaults differ + * (dimensions: 512, mime_patterns: ['image/%']). The + * task is the same file-shaped record worker, embedding:process_file_embedding: + * the trigger payload is the file row's columns (file_id, key, mime_type, + * bucket_id), which embedding:process_image_embedding — the flow function that + * embeds an {image_url, alt_text} it is handed — does not accept. * * Kept as a separate node type for backward compatibility — existing * blueprints that reference ProcessImageEmbedding continue to work unchanged. @@ -21,8 +25,8 @@ export const ProcessImageEmbedding: NodeTypeDefinition = { description: 'Image-specific preset of ProcessFileEmbedding. Delegates to ProcessFileEmbedding ' + 'with image-oriented defaults: dimensions=512 (CLIP), mime_patterns=[\'image/%\'], ' + - 'task_identifier=\'embedding:process_image_embedding\', direct mode (no extraction). ' + - 'Accepts all ProcessFileEmbedding parameters — any overrides are forwarded through.', + 'task_identifier=\'embedding:process_file_embedding\', direct mode only: there is no ' + + 'image extraction (OCR) worker, so extraction is refused. Every other parameter is forwarded through.', parameter_schema: { type: 'object', $defs: conditionDefs, @@ -86,8 +90,12 @@ export const ProcessImageEmbedding: NodeTypeDefinition = { task_identifier: { type: 'string', format: 'function-ref', - description: 'Job task identifier for the image embedding worker', - default: 'embedding:process_image_embedding' + description: + 'Job task identifier for the image embedding worker. The payload is the file ' + + 'row (file_id, key, mime_type, bucket_id), so the task must be a record worker ' + + 'that reads the object itself — not embedding:process_image_embedding, which ' + + 'embeds an image_url it is handed.', + default: 'embedding:process_file_embedding' }, events: { type: 'array', @@ -103,7 +111,8 @@ export const ProcessImageEmbedding: NodeTypeDefinition = { 'When set, the trigger reads the object key, MIME type and bucket id ' + 'out of that document (NEW. ->> \'key\', ...) instead of ' + 'requiring key/mime_type/bucket_id columns beside it, and the MIME ' + - 'patterns match against ->> \'mime\'.' + 'patterns match against ->> \'mime\'. ' + + 'An array column (image[]/upload[]) is refused (PROCESS_IMAGE_EMBEDDING_ARRAY_FILE_FIELD_UNSUPPORTED): one vector column cannot hold a vector per element.' }, payload_custom: { type: 'object', @@ -143,53 +152,6 @@ export const ProcessImageEmbedding: NodeTypeDefinition = { obj_field: { type: 'string', format: 'column-ref', description: 'Column on the related table that holds the entity_id' } }, required: ['obj_table', 'obj_field'] - }, - - // ── Extraction config (optional — enables extract mode) ──────── - extraction: { - type: 'object', - description: - 'Text extraction configuration. Forwarded to ProcessFileEmbedding. ' + - 'When present, enables extract mode (e.g., OCR for images).', - properties: { - text_field: { - type: 'string', - format: 'column-ref', - description: 'Field to store extracted text', - default: 'extracted_text' - }, - metadata_field: { - type: 'string', - format: 'column-ref', - description: 'JSONB field for extraction metadata', - default: 'extracted_metadata' - } - } - }, - - // ── Chunking config (optional — forwarded to ProcessFileEmbedding) ─ - chunks: { - type: 'object', - description: - 'Chunking configuration. Forwarded to ProcessFileEmbedding. ' + - 'Only meaningful when extraction is also provided.', - properties: { - content_field_name: { - type: 'string', - format: 'column-ref', - default: 'content' - }, - chunk_size: { type: 'integer', default: 1000 }, - chunk_overlap: { type: 'integer', default: 200 }, - chunk_strategy: { - type: 'string', - enum: ['fixed', 'sentence', 'paragraph', 'semantic'], - default: 'paragraph' - }, - metadata_fields: { type: 'object' }, - enqueue_chunking_job: { type: 'boolean', default: true }, - chunking_task_name: { type: 'string', format: 'function-ref', default: 'embedding:chunk_record' } - } } } }, diff --git a/packages/node-type-registry/src/process/image-versions.ts b/packages/node-type-registry/src/process/image-versions.ts index a8707b0635..a77abbed94 100644 --- a/packages/node-type-registry/src/process/image-versions.ts +++ b/packages/node-type-registry/src/process/image-versions.ts @@ -4,15 +4,28 @@ import type { NodeTypeDefinition } from '../types'; /** * Image version processing node. * - * Composes a JobTrigger that fires when an image file transitions to - * status = 'uploaded'. - * The trigger enqueues an image-processing job that generates resized, - * cropped, or reformatted variants of the source image. + * Composes a JobTrigger for image variant generation. On a storage module's + * files table it also creates the jsonb column the variants manifest is + * written back to (`versions_field`, default `image_versions`); on a business + * table with an upload/image column the manifest is written inside that + * column's own document, as its `versions` member. On a storage module's files table the trigger fires when + * the file transitions to status = 'uploaded'; on a business table with an + * upload/image column it fires on the configured events (INSERT by default, + * plus an UPDATE that changes the file when no events are given). * - * The image processing worker is external (Knative function) — this node - * only creates the trigger infrastructure. The worker generates the variants - * and writes them back to the storage system as new file records linked to - * the source file. + * The trigger enqueues `image:process_image_versions`, which `functions/image` + * answers: it reads the source object from the row's own bucket, renders each + * version, writes the variants beside the source + * (`.versions/-.`) and lands the manifest — an + * array, narrowest first, of each variant's name, object key, format, + * dimensions and size — on the row. `versions` is optional: without it the + * worker resolves the ladder when the job runs (the `IMAGE_VERSIONS` config + * value, else thumbnail 160x160 cover and 320 / 640 / 1280 / 1920 wide, WebP), + * so nothing is stamped into the trigger. A version wider or taller than the + * source is skipped, never upscaled. SVG sources are left alone unless + * `mime_patterns` is given. On a storage module's files table the generator also emits + * `_write_image_versions`, the SECURITY DEFINER writer that lands the + * manifest and moves the file `uploaded → processed`. */ export const ProcessImageVersions: NodeTypeDefinition = { name: 'ProcessImageVersions', @@ -21,14 +34,18 @@ export const ProcessImageVersions: NodeTypeDefinition = { display_name: 'Image Versions', description: 'Creates a job trigger for image variant generation. ' + - 'Fires when an image file is uploaded (status = \'uploaded\') or on INSERT. ' + - 'The external worker generates resized, cropped, or reformatted versions ' + - '(thumbnails, previews, WebP conversions, etc.) and stores them as new ' + - 'file records linked to the source image.', + 'On a storage files table it fires when the file reaches status = \'uploaded\'; ' + + 'on a business table with a file column it fires on INSERT and on an UPDATE that changes the file; events, when given, replace that default. ' + + 'The image worker generates resized, cropped, or reformatted versions ' + + '(thumbnails, previews, WebP conversions, etc.), stores them beside the source object ' + + 'in the file\'s own bucket, and records each variant\'s name, key, format, dimensions and size: ' + + 'inside the file column\'s own document (its versions member) on a business table, ' + + 'in the manifest column on a storage files table. ' + + 'With no versions given the worker uses the default ladder (thumbnail, small, medium, large, xlarge), ' + + 'resolved when the job runs, and skips any version larger than the source.', parameter_schema: { type: 'object', $defs: conditionDefs, - required: ['versions'], properties: { // ── Version definitions ─────────────────────────────────────── @@ -72,15 +89,28 @@ export const ProcessImageVersions: NodeTypeDefinition = { description: 'Array of version definitions. Each version specifies dimensions, ' + 'format, and quality for a generated image variant. ' + - 'Required — the blueprint must explicitly define what variants to generate.', + 'Optional: when omitted the worker resolves the default ladder at job time ' + + '(thumbnail 160x160 cover, then small 320, medium 640, large 1280 and xlarge 1920 wide, WebP quality 80), ' + + 'so a later change to the default reaches tables already provisioned. ' + + 'A version larger than the source is skipped rather than upscaled.', minItems: 1 }, + // ── Output field ────────────────────────────────────────────── + versions_field: { + type: 'string', + format: 'column-ref', + description: + 'Files tables only: name of the jsonb column the variants manifest is written to. Created by the generator when absent; ' + + 'forwarded to the worker in the job payload. Rejected with file_field, where the manifest is written inside the file document.', + default: 'image_versions' + }, + // ── MIME scoping ────────────────────────────────────────────── mime_patterns: { type: 'array', items: { type: 'string' }, - description: 'MIME type LIKE patterns to match. Defaults to all image types.', + description: 'MIME type LIKE patterns to match. Defaults to all image types except image/svg+xml, which is not rasterized unless a pattern given here asks for it.', default: ['image/%'] }, @@ -94,7 +124,10 @@ export const ProcessImageVersions: NodeTypeDefinition = { events: { type: 'array', items: { type: 'string', enum: ['INSERT', 'UPDATE'] }, - description: 'Trigger events that fire the job', + description: + 'Trigger events that fire the job on a business table. Ignored on a storage ' + + 'files table, where the trigger is always the status transition to uploaded ' + + '(INSERT is rejected there: the row is still requested).', default: ['INSERT'] }, file_field: { @@ -105,7 +138,8 @@ export const ProcessImageVersions: NodeTypeDefinition = { 'When set, the trigger reads the object key, MIME type and bucket id ' + 'out of that document (NEW. ->> \'key\', ...) instead of ' + 'requiring key/mime_type/bucket_id columns beside it, and the MIME ' + - 'patterns match against ->> \'mime\'.' + 'patterns match against ->> \'mime\'. ' + + 'The column may be an array (image[]/upload[]): the lane then runs once per element whose key is new to the array, and each element carries its own manifest in its versions member.' }, payload_custom: { type: 'object', diff --git a/packages/node-type-registry/src/process/index.ts b/packages/node-type-registry/src/process/index.ts index 62205f71f9..581f59a9d8 100644 --- a/packages/node-type-registry/src/process/index.ts +++ b/packages/node-type-registry/src/process/index.ts @@ -1,4 +1,5 @@ export { ProcessChunks } from './chunks'; +export { ProcessCustom } from './custom'; export { ProcessExtraction } from './extraction'; export { ProcessFileEmbedding } from './file-embedding'; export { ProcessImageEmbedding } from './image-embedding'; diff --git a/packages/node-type-registry/src/relation/relation-belongs-to.ts b/packages/node-type-registry/src/relation/relation-belongs-to.ts index 5da29adaf2..ea201943f6 100644 --- a/packages/node-type-registry/src/relation/relation-belongs-to.ts +++ b/packages/node-type-registry/src/relation/relation-belongs-to.ts @@ -39,6 +39,14 @@ export const RelationBelongsTo: NodeTypeDefinition = { type: 'boolean', description: 'Whether the FK field is NOT NULL', default: true + }, + scope_fields: { + type: 'array', + items: { + type: 'string', + format: 'column-ref' + }, + description: 'Columns both tables carry that the referenced row must share with the referencing row (e.g. ["entity_id"], or ["project_id"] for a stage of the same project). Adds a hidden composite FK (field_name, ...scope_fields) -> target (id, ...scope_fields) plus the target unique key it needs, so a row cannot point at another scope\'s row even when it knows the id.' } }, required: [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca606f3e9a..ddbd73987b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -186,18 +186,28 @@ 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.8 - version: 4.9.8 + specifier: ^4.10.1 + version: 4.10.1 + publishDirectory: dist + + agentic/command: + dependencies: + '@agentic-kit/harness': + specifier: workspace:^ + version: link:../harness/dist + inquirerer: + specifier: ^4.10.1 + version: 4.10.1 + zod: + specifier: ^4.4.3 + version: 4.4.3 publishDirectory: dist agentic/db-tools: @@ -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.9.0 + version: 0.9.0 + publishDirectory: dist + examples/codegen-integration: dependencies: '@0no-co/graphql.web': @@ -2844,6 +2887,10 @@ importers: publishDirectory: dist packages/node-type-registry: + dependencies: + blocks-schema: + specifier: ^0.5.4 + version: 0.5.5 devDependencies: '@babel/generator': specifier: ^7.29.0 @@ -5547,6 +5594,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'} @@ -7167,6 +7226,9 @@ packages: appstash@0.8.2: resolution: {integrity: sha512-Lnq3NcsDE4fQA533gLSP+qZyv9ZzAu1nsIUzcG59yEM+pKH+gA5rCeWCtL/owp7IphryDb0cR4EsSsKFa5JxSw==} + appstash@0.9.0: + resolution: {integrity: sha512-FBv+u8qPDgnY24uZq9qr/lHHTb9AOwYMxHg5gmomg2v/ITRmrLZ9ZbwzpyOpTa72Je4FwNlOXRCvmby745Hjvw==} + aproba@2.0.0: resolution: {integrity: sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==} @@ -7280,6 +7342,10 @@ packages: bl@4.1.0: resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + blocks-schema@0.5.5: + resolution: {integrity: sha512-dvnFlKk4/ELpNgtmyh6C4XkkqaGbGHjZNo3HjzyPqXBiokikKO0zBQtBZiPsM1lqqfJ4sWE2VKMquImICbUdFg==} + engines: {node: '>=24.0.0'} + body-parser@2.2.1: resolution: {integrity: sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==} engines: {node: '>=18'} @@ -8045,6 +8111,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'} @@ -8696,6 +8770,9 @@ packages: resolution: {integrity: sha512-UjOaSel/iddGZJ5xP/Eixh6dY1XghiBw4XK13rCCIJcJfyhhoul/7KhLLUGtebEj6GDYM6Vnx/mVsjx2L/mFIA==} engines: {node: '>=12.0.0'} + inquirerer@4.10.1: + resolution: {integrity: sha512-kNI77JKGylrpeqtkzB0hgany2OVIXfJ2SycC5cb2QI4xtTgoZtRF4vJTwck4zTLl0gNHu/qRzZ8kg+jPZF2fXg==} + inquirerer@4.9.7: resolution: {integrity: sha512-3PgTWhyKjt42C45JlVKlDhM9NRgHEciZM40fqZUGIK5aAFKu3gR/4JnJN7n5nnOK3Cs/Xu0Y8nOWdEDGxy53rA==} @@ -9038,6 +9115,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==} @@ -9083,6 +9163,10 @@ packages: resolution: {integrity: sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + json-renderer@0.4.4: + resolution: {integrity: sha512-gk43N1+J0w95wERIQbkI9EE3tfRWEa4305xQYXD5AIAWTTuHc/JszSldnUJf1W9R0+Z75iweP/QcGpcjpDsSHA==} + engines: {node: '>=24.0.0'} + json-schema-to-ts@3.1.1: resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==} engines: {node: '>=16'} @@ -9995,6 +10079,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'} @@ -13336,6 +13424,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': @@ -14966,6 +15073,8 @@ snapshots: appstash@0.8.2: {} + appstash@0.9.0: {} + aproba@2.0.0: {} arg@4.1.3: {} @@ -15095,6 +15204,11 @@ snapshots: inherits: 2.0.4 readable-stream: 3.6.2 + blocks-schema@0.5.5: + dependencies: + json-renderer: 0.4.4 + zod: 4.4.3 + body-parser@2.2.1: dependencies: bytes: 3.1.2 @@ -15777,6 +15891,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 @@ -16760,6 +16880,14 @@ snapshots: transitivePeerDependencies: - '@types/node' + inquirerer@4.10.1: + dependencies: + deepmerge: 4.3.1 + find-and-require-package-json: 0.9.3 + minimist: 1.2.8 + string-width: 4.2.3 + yanse: 0.2.4 + inquirerer@4.9.7: dependencies: deepmerge: 4.3.1 @@ -17315,6 +17443,8 @@ snapshots: jiti@2.7.0: {} + jose@6.2.18: {} + js-tokens@4.0.0: {} js-yaml@3.14.2: @@ -17371,6 +17501,10 @@ snapshots: json-parse-even-better-errors@3.0.2: {} + json-renderer@0.4.4: + dependencies: + zod: 4.4.3 + json-schema-to-ts@3.1.1: dependencies: '@babel/runtime': 7.28.4 @@ -18443,6 +18577,8 @@ snapshots: pirates@4.0.7: {} + pkce-challenge@5.0.2: {} + pkg-dir@4.2.0: dependencies: find-up: 4.1.0