From 01ac05c20479991277ff24d66be6dad477c7e76f Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 06:03:19 +0200 Subject: [PATCH 01/35] test(cli): pin both configuration hashes to one golden corpus The CLI's valueHash and the platform's managedConfigurationHash are two copies of one identity: CLI plans and receipts compare against the native `hash` / `expectedHash` the platform computes. Before either moves, a golden corpus pins both to the same digests (numbers, -0, NaN, unicode, escapes, numeric and unsorted keys, nested values) and records where they part on purpose: null is a digest for the CLI and an absent resource for the platform, and a value JSON cannot hold (undefined) is refused by the CLI and written as null by the platform. The two older parity checks in managed-resources.test.ts move into the new suite unchanged. --- .../config/configuration-hash-parity.test.ts | 178 ++++++++++++++++++ .../src/lib/config/managed-resources.test.ts | 25 --- 2 files changed, 178 insertions(+), 25 deletions(-) create mode 100644 tools/cli/src/lib/config/configuration-hash-parity.test.ts diff --git a/tools/cli/src/lib/config/configuration-hash-parity.test.ts b/tools/cli/src/lib/config/configuration-hash-parity.test.ts new file mode 100644 index 0000000000..f0ff6218aa --- /dev/null +++ b/tools/cli/src/lib/config/configuration-hash-parity.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, test } from 'bun:test'; +import { readFile } from 'node:fs/promises'; + +import { managedConfigurationHash } from '../../../../../services/platform/backend/core/lib/config_store/value_hash'; +import { valueHash } from './releases/identity'; + +/** One corpus, one digest each. The CLI's plans, receipts and releases and + * the platform's native preconditions (`hash` / `expectedHash`) were recorded + * with these two functions, so every digest here is a promise: no refactor + * may move one of them. */ +const GOLDEN: readonly (readonly [string, unknown, string])[] = [ + [ + 'true', + true, + 'b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b', + ], + [ + 'false', + false, + 'fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa', + ], + [ + 'zero', + 0, + '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', + ], + [ + 'negative zero', + -0, + '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', + ], + [ + 'integer', + 42, + '73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049', + ], + [ + 'negative', + -7, + 'a770d3270c9dcdedf12ed9fd70444f7c8a95c26cae3cae9bd867499090a2f14b', + ], + [ + 'fraction', + 1.5, + '9f29a130438b81170b92a42650f9a94291ecad60bd47af2a3886e75f7f728725', + ], + [ + 'exponent', + 1e21, + '241c4643fa70b1dcde1205b71be4e3bebb17e9f880c8e1a33d0ead6c27271d3c', + ], + [ + 'tiny', + 1e-7, + '5b33e02f2c5103a05d32f6ba9cb058294452bfbf393967f68bb30c1bdcbbab22', + ], + [ + 'beyond the safe integers', + 2 ** 53 + 2, + '25aa68783313802627958889943e895749ac4c0c7469b2a305cd450a12120768', + ], + [ + 'not a number (serialized as null)', + Number.NaN, + '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', + ], + [ + 'empty string', + '', + '12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126', + ], + [ + 'unicode string', + ' café 😺 ', + '9bfcef4d1b3e38e1ce77febf76a0c69402483d4887dff28b8dd217c333bf4e36', + ], + [ + 'escapes', + 'line\nbreak "quoted" \\ 
 \u0000', + '76da2c85724e3ff3927a2d4a02792a2324cc8c77c240f9645b711f3dd851eb3e', + ], + [ + 'empty array', + [], + '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945', + ], + [ + 'empty object', + {}, + '44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a', + ], + [ + 'numeric keys and nested arrays', + { '10': 1, '2': ['x', { z: true, a: null }], '1': { '20': 2, '3': 3 } }, + '2edb082bd557ed6017442ce17de049016bc7697d1226f0e581be4673545c8953', + ], + [ + 'unsorted keys', + { b: 1, a: [3, { d: null, c: 'x' }] }, + 'b4a92c330fc01410911e683d5d03404eb28981a6e1d67f9cb1ae63ddc3d19947', + ], + [ + 'unicode and empty keys', + { é: 1, e: 2, Z: 3, '': 0 }, + '528bf91433a18ef395f2c7932427e6f6afa6cf4dd40e24af56640e70005d8fd9', + ], + [ + 'a policy', + { + enabled: true, + idleTimeoutMinutes: 45, + rules: [{ scope: 'org', maxTokens: 1000 }], + }, + '5c1093799a52bfe0671e5e3d7f3b204e7700ad17cd888115d4c2f075b00df2a1', + ], +]; + +/** `null` is the one JSON value the two functions answer differently on + * purpose: the platform's hash is a precondition, and a null precondition + * means "the resource is absent". */ +const NULL_DIGEST = + '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b'; + +describe('configuration hash parity', () => { + test.each(GOLDEN)( + '%s hashes to its golden digest', + (_name, value, digest) => { + expect(valueHash(value)).toBe(digest); + expect(managedConfigurationHash(value)).toBe(digest); + }, + ); + + test('key order never changes a digest', () => { + const forwards = { a: 1, b: { c: [1, 2], d: 'x' } }; + const backwards = { b: { d: 'x', c: [1, 2] }, a: 1 }; + expect(valueHash(backwards)).toBe(valueHash(forwards)); + expect(managedConfigurationHash(backwards)).toBe( + managedConfigurationHash(forwards), + ); + }); + + test('null is a digest for the CLI and an absent resource for the platform', () => { + expect(valueHash(null)).toBe(NULL_DIGEST); + expect(managedConfigurationHash(null)).toBeNull(); + }); + + test('they part only on what JSON cannot hold: the CLI refuses, the platform writes null', () => { + for (const [value, asNull] of [ + [undefined, null], + [{ a: undefined }, { a: null }], + [ + [1, undefined], + [1, null], + ], + ] as const) { + expect(() => valueHash(value)).toThrow('not JSON serializable'); + expect(managedConfigurationHash(value)).toBe( + value === undefined ? NULL_DIGEST : valueHash(asNull), + ); + } + }); + + test('CLI cache inputs include both native JSON identity modules used by the parity proof', async () => { + const turbo: unknown = JSON.parse( + await readFile(new URL('../../../turbo.json', import.meta.url), 'utf8'), + ); + expect(turbo).toMatchObject({ + tasks: { + test: { + inputs: expect.arrayContaining([ + '$TURBO_ROOT$/services/platform/backend/core/lib/config_store/value_hash.ts', + '$TURBO_ROOT$/services/platform/lib/shared/utils/stable-stringify.ts', + ]), + }, + }, + }); + }); +}); diff --git a/tools/cli/src/lib/config/managed-resources.test.ts b/tools/cli/src/lib/config/managed-resources.test.ts index 10c72e83c2..98c769b3cf 100644 --- a/tools/cli/src/lib/config/managed-resources.test.ts +++ b/tools/cli/src/lib/config/managed-resources.test.ts @@ -311,15 +311,6 @@ describe('managed native configuration', () => { }); }); -test('native and CLI value identity agree for JSON strings, numeric keys and nested arrays', () => { - for (const value of [ - '', - ' café 😺 ', - { '10': 1, '2': ['x', { z: true, a: null }], '1': { '20': 2, '3': 3 } }, - ]) - expect(managedConfigurationHash(value)).toBe(valueHash(value)); -}); - test('adopts a legacy agent text preimage without silently trimming its native hash', async () => { const config = { projectId: 'project-1', @@ -336,22 +327,6 @@ test('adopts a legacy agent text preimage without silently trimming its native h expect(result).toEqual({ config, revision: valueHash(config) }); }); -test('CLI cache inputs include both native JSON identity modules used by the parity proof', async () => { - const turbo: unknown = JSON.parse( - await readFile(new URL('../../../turbo.json', import.meta.url), 'utf8'), - ); - expect(turbo).toMatchObject({ - tasks: { - test: { - inputs: expect.arrayContaining([ - '$TURBO_ROOT$/services/platform/backend/core/lib/config_store/value_hash.ts', - '$TURBO_ROOT$/services/platform/lib/shared/utils/stable-stringify.ts', - ]), - }, - }, - }); -}); - describe('managed tool preimages', () => { const resource = { kind: 'agent-tools' as const, From 911502e7a4ea88c9fb32a03927f946845921ade8 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 06:07:42 +0200 Subject: [PATCH 02/35] refactor(shared): give the CLI and the platform one configuration hash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The platform's native configuration identity moves to @tale/shared: `configurationHash(value)` (SHA-256 of key-sorted JSON) beside the pure `stableStringify` it hashes. The platform's stable-stringify module now re-exports the shared serializer, and `managedConfigurationHash` wraps `configurationHash` (null still means an absent resource). The shared resource model and the MCP settings tools build on the same function. The golden corpus moves to the shared package; `configuration-hash.test.ts` holds the shared function to it, and the CLI's parity suite holds all three — the shared hash, the platform's wrapper and the CLI's own `valueHash` — to the same digests. The CLI keeps `valueHash` for its releases, plans and receipts: it refuses a value JSON cannot hold where the platform writes null, and a recorded CLI digest must never move. The engine purity guard now scans the shared serializer and allows its subpath; the platform's test inputs hash the file it reads. --- packages/shared/README.md | 6 + packages/shared/package.json | 2 + .../src/utils/configuration-hash.golden.ts | 128 ++++++++++++++++ .../src/utils/configuration-hash.test.ts | 50 +++++++ .../shared/src/utils/configuration-hash.ts | 16 ++ packages/shared/src/utils/stable-stringify.ts | 16 ++ .../core/lib/config_store/value_hash.ts | 8 +- .../lib/engine/selftest/purity.test.ts | 5 + .../lib/shared/utils/stable-stringify.ts | 16 +- .../tests/guards/turbo-inputs.guard.test.ts | 4 + services/platform/turbo.json | 1 + .../config/configuration-hash-parity.test.ts | 140 ++---------------- 12 files changed, 249 insertions(+), 143 deletions(-) create mode 100644 packages/shared/src/utils/configuration-hash.golden.ts create mode 100644 packages/shared/src/utils/configuration-hash.test.ts create mode 100644 packages/shared/src/utils/configuration-hash.ts create mode 100644 packages/shared/src/utils/stable-stringify.ts diff --git a/packages/shared/README.md b/packages/shared/README.md index fd5f255b15..de66358bb5 100644 --- a/packages/shared/README.md +++ b/packages/shared/README.md @@ -81,6 +81,12 @@ process and terminal dependencies out of frontend bundles. - **`@tale/shared/utils/hashing`** — `computeContentHash(string | Uint8Array)`, the SHA-256 hex digest the knowledge index dedups content by. +- **`@tale/shared/utils/stable-stringify`** — `stableStringify(value)`, JSON with every + object's keys sorted (a value JSON cannot hold reads as `null`). Pure: the automation + engine and the browser compare values with it. +- **`@tale/shared/utils/configuration-hash`** — `configurationHash(value)`, the SHA-256 of + that key-sorted JSON: a native configuration resource's `hash`, and the `expectedHash` + a write takes back. Server-only (Node's crypto); a golden corpus pins every digest. ## Development diff --git a/packages/shared/package.json b/packages/shared/package.json index 32e4b70c19..9e071b2497 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -17,6 +17,8 @@ "./tux": "./src/tux/index.ts", "./process": "./src/process/index.ts", "./utils/hashing": "./src/utils/hashing.ts", + "./utils/configuration-hash": "./src/utils/configuration-hash.ts", + "./utils/stable-stringify": "./src/utils/stable-stringify.ts", "./utils/site-urls": "./src/utils/site-urls.ts", "./schemas/branding": "./src/schemas/branding.ts", "./schemas/deployment": "./src/schemas/deployment.ts", diff --git a/packages/shared/src/utils/configuration-hash.golden.ts b/packages/shared/src/utils/configuration-hash.golden.ts new file mode 100644 index 0000000000..e9e80bf3dc --- /dev/null +++ b/packages/shared/src/utils/configuration-hash.golden.ts @@ -0,0 +1,128 @@ +/** + * The golden corpus of `configurationHash`: one value, one digest each. + * The digests were recorded from the two functions the hash replaced — the + * CLI's `valueHash` and the platform's `managedConfigurationHash` — which + * agreed on every one of them, and CLI plans, receipts and the platform's + * native preconditions (`hash` / `expectedHash`) were recorded with them. So + * every digest here is a promise: no refactor may move one. + * + * Test support only: `configuration-hash.test.ts` holds the shared function to + * it, and the CLI's parity suite holds its own `valueHash` and the platform's + * `managedConfigurationHash` to it. + */ +export const CONFIGURATION_HASH_GOLDEN: readonly (readonly [ + string, + unknown, + string, +])[] = [ + [ + 'true', + true, + 'b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b', + ], + [ + 'false', + false, + 'fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa', + ], + [ + 'zero', + 0, + '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', + ], + [ + 'negative zero', + -0, + '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', + ], + [ + 'integer', + 42, + '73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049', + ], + [ + 'negative', + -7, + 'a770d3270c9dcdedf12ed9fd70444f7c8a95c26cae3cae9bd867499090a2f14b', + ], + [ + 'fraction', + 1.5, + '9f29a130438b81170b92a42650f9a94291ecad60bd47af2a3886e75f7f728725', + ], + [ + 'exponent', + 1e21, + '241c4643fa70b1dcde1205b71be4e3bebb17e9f880c8e1a33d0ead6c27271d3c', + ], + [ + 'tiny', + 1e-7, + '5b33e02f2c5103a05d32f6ba9cb058294452bfbf393967f68bb30c1bdcbbab22', + ], + [ + 'beyond the safe integers', + 2 ** 53 + 2, + '25aa68783313802627958889943e895749ac4c0c7469b2a305cd450a12120768', + ], + [ + 'not a number (serialized as null)', + Number.NaN, + '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', + ], + [ + 'empty string', + '', + '12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126', + ], + [ + 'unicode string', + ' café 😺 ', + '9bfcef4d1b3e38e1ce77febf76a0c69402483d4887dff28b8dd217c333bf4e36', + ], + [ + 'escapes', + 'line\nbreak "quoted" \\ 
 \u0000', + '76da2c85724e3ff3927a2d4a02792a2324cc8c77c240f9645b711f3dd851eb3e', + ], + [ + 'empty array', + [], + '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945', + ], + [ + 'empty object', + {}, + '44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a', + ], + [ + 'numeric keys and nested arrays', + { '10': 1, '2': ['x', { z: true, a: null }], '1': { '20': 2, '3': 3 } }, + '2edb082bd557ed6017442ce17de049016bc7697d1226f0e581be4673545c8953', + ], + [ + 'unsorted keys', + { b: 1, a: [3, { d: null, c: 'x' }] }, + 'b4a92c330fc01410911e683d5d03404eb28981a6e1d67f9cb1ae63ddc3d19947', + ], + [ + 'unicode and empty keys', + { é: 1, e: 2, Z: 3, '': 0 }, + '528bf91433a18ef395f2c7932427e6f6afa6cf4dd40e24af56640e70005d8fd9', + ], + [ + 'a policy', + { + enabled: true, + idleTimeoutMinutes: 45, + rules: [{ scope: 'org', maxTokens: 1000 }], + }, + '5c1093799a52bfe0671e5e3d7f3b204e7700ad17cd888115d4c2f075b00df2a1', + ], +]; + +/** The digest of `null`. `configurationHash` and the CLI's `valueHash` answer + * it; the platform's `managedConfigurationHash(null)` answers null instead, + * because a null precondition means "the resource is absent". */ +export const NULL_DIGEST = + '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b'; diff --git a/packages/shared/src/utils/configuration-hash.test.ts b/packages/shared/src/utils/configuration-hash.test.ts new file mode 100644 index 0000000000..faffcf9d8b --- /dev/null +++ b/packages/shared/src/utils/configuration-hash.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; + +import { configurationHash } from './configuration-hash'; +import { + CONFIGURATION_HASH_GOLDEN, + NULL_DIGEST, +} from './configuration-hash.golden'; +import { computeContentHash } from './hashing'; +import { stableStringify } from './stable-stringify'; + +describe('configurationHash', () => { + it.each(CONFIGURATION_HASH_GOLDEN)( + '%s keeps its golden digest', + (_name, value, digest) => { + expect(configurationHash(value)).toBe(digest); + }, + ); + + it('is the SHA-256 of the key-sorted JSON', () => { + const value = { b: [true, null], a: { d: 1, c: 'x' } }; + expect(stableStringify(value)).toBe( + '{"a":{"c":"x","d":1},"b":[true,null]}', + ); + expect(configurationHash(value)).toBe( + computeContentHash('{"a":{"c":"x","d":1},"b":[true,null]}'), + ); + }); + + it('never depends on key order', () => { + expect(configurationHash({ a: 1, b: { c: 2, d: [3] } })).toBe( + configurationHash({ b: { d: [3], c: 2 }, a: 1 }), + ); + }); + + it('hashes null like any other value; absence is the caller’s convention', () => { + expect(configurationHash(null)).toBe(NULL_DIGEST); + }); + + it('writes what JSON cannot hold as null, the way the platform always has', () => { + expect(configurationHash(undefined)).toBe(NULL_DIGEST); + expect(configurationHash({ a: undefined })).toBe( + configurationHash({ a: null }), + ); + expect(configurationHash([1, undefined, () => 1])).toBe( + configurationHash([1, null, null]), + ); + // An undefined member is kept as null, so it is not the same as absent. + expect(configurationHash({ a: undefined })).not.toBe(configurationHash({})); + }); +}); diff --git a/packages/shared/src/utils/configuration-hash.ts b/packages/shared/src/utils/configuration-hash.ts new file mode 100644 index 0000000000..a501558bcb --- /dev/null +++ b/packages/shared/src/utils/configuration-hash.ts @@ -0,0 +1,16 @@ +import { computeContentHash } from './hashing'; +import { stableStringify } from './stable-stringify'; + +/** + * The identity of a native configuration value: the SHA-256 (hex) of its + * key-sorted JSON ({@link stableStringify}). The platform answers it as a + * resource's `hash` and takes it back as `expectedHash`, the compare-and-set + * precondition of every configuration write; the CLI's plans and the MCP + * settings tools compare against the same digest. + * + * Server-only (Node's crypto). A digest, once recorded, must never move: + * `configuration-hash.test.ts` pins a golden corpus. + */ +export function configurationHash(value: unknown): string { + return computeContentHash(stableStringify(value)); +} diff --git a/packages/shared/src/utils/stable-stringify.ts b/packages/shared/src/utils/stable-stringify.ts new file mode 100644 index 0000000000..01540aceae --- /dev/null +++ b/packages/shared/src/utils/stable-stringify.ts @@ -0,0 +1,16 @@ +/** Deep-equality serialization independent of key order: JSON with every + * object's keys sorted. A value JSON cannot hold (`undefined`, a function) + * serializes as `null`, wherever it sits. Pure — the automation engine and + * the browser use it too. */ +export function stableStringify(v: unknown): string { + if (Array.isArray(v)) return `[${v.map(stableStringify).join(',')}]`; + if (v && typeof v === 'object') { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed by the object check above + const record = v as Record; + return `{${Object.keys(record) + .sort() + .map((k) => `${JSON.stringify(k)}:${stableStringify(record[k])}`) + .join(',')}}`; + } + return JSON.stringify(v) ?? 'null'; +} diff --git a/services/platform/backend/core/lib/config_store/value_hash.ts b/services/platform/backend/core/lib/config_store/value_hash.ts index 7afdd8da7f..6b9d8ade8b 100644 --- a/services/platform/backend/core/lib/config_store/value_hash.ts +++ b/services/platform/backend/core/lib/config_store/value_hash.ts @@ -1,11 +1,7 @@ -import { createHash } from 'node:crypto'; - -import { stableStringify } from '../../../../lib/shared/utils/stable-stringify'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; /** Native JSON value identity shared by managed resource CAS and the CLI's * sorted-JSON configuration digest. Null denotes an absent native resource. */ export function managedConfigurationHash(config: unknown): string | null { - return config === null - ? null - : createHash('sha256').update(stableStringify(config)).digest('hex'); + return config === null ? null : configurationHash(config); } diff --git a/services/platform/lib/engine/selftest/purity.test.ts b/services/platform/lib/engine/selftest/purity.test.ts index b8ae2dc5a2..3bdadbb5da 100644 --- a/services/platform/lib/engine/selftest/purity.test.ts +++ b/services/platform/lib/engine/selftest/purity.test.ts @@ -29,6 +29,10 @@ const PURE_SHARED_HELPERS = [ '../../../../packages/shared/src/automation-name.ts', ), path.resolve(ENGINE_ROOT, '../shared/utils/stable-stringify.ts'), + path.resolve( + ENGINE_ROOT, + '../../../../packages/shared/src/utils/stable-stringify.ts', + ), ]; function sourceFiles(dir: string): string[] { @@ -84,6 +88,7 @@ describe('engine purity', () => { const allowedPackages = new Set([ 'ajv', '@tale/shared/automation-name', + '@tale/shared/utils/stable-stringify', 'acorn', 'estree', 'is-reference', diff --git a/services/platform/lib/shared/utils/stable-stringify.ts b/services/platform/lib/shared/utils/stable-stringify.ts index abf818c5a7..4ac0247277 100644 --- a/services/platform/lib/shared/utils/stable-stringify.ts +++ b/services/platform/lib/shared/utils/stable-stringify.ts @@ -1,13 +1,3 @@ -/** Deep-equality serialization independent of key order. */ -export function stableStringify(v: unknown): string { - if (Array.isArray(v)) return `[${v.map(stableStringify).join(',')}]`; - if (v && typeof v === 'object') { - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed by the object check above - const record = v as Record; - return `{${Object.keys(record) - .sort() - .map((k) => `${JSON.stringify(k)}:${stableStringify(record[k])}`) - .join(',')}}`; - } - return JSON.stringify(v) ?? 'null'; -} +/** The key-sorted JSON every platform reader compares by lives in + * `@tale/shared`, beside the configuration hash it feeds. */ +export { stableStringify } from '@tale/shared/utils/stable-stringify'; diff --git a/services/platform/tests/guards/turbo-inputs.guard.test.ts b/services/platform/tests/guards/turbo-inputs.guard.test.ts index 8dc145876e..be182a1bb7 100644 --- a/services/platform/tests/guards/turbo-inputs.guard.test.ts +++ b/services/platform/tests/guards/turbo-inputs.guard.test.ts @@ -134,6 +134,10 @@ const OUTSIDE_READS = [ path: 'packages/shared/src/automation-name.ts', readers: 'lib/engine/selftest/purity.test.ts scans the extracted grammar', }, + { + path: 'packages/shared/src/utils/stable-stringify.ts', + readers: 'lib/engine/selftest/purity.test.ts scans the stable serializer', + }, { // Not read as text: the suite runs the postgres.js these patches change // (the root `patchedDependencies`), so a patch edit alone must re-run it. diff --git a/services/platform/turbo.json b/services/platform/turbo.json index 0de4a02285..e63e26e6d0 100644 --- a/services/platform/turbo.json +++ b/services/platform/turbo.json @@ -36,6 +36,7 @@ "$TURBO_ROOT$/docs/en/platform/**", "$TURBO_ROOT$/knip.config.ts", "$TURBO_ROOT$/packages/shared/src/automation-name.ts", + "$TURBO_ROOT$/packages/shared/src/utils/stable-stringify.ts", "$TURBO_ROOT$/packages/ui/package.json", "$TURBO_ROOT$/packages/ui/src/**", "$TURBO_ROOT$/packages/ui/tailwind-preset.ts", diff --git a/tools/cli/src/lib/config/configuration-hash-parity.test.ts b/tools/cli/src/lib/config/configuration-hash-parity.test.ts index f0ff6218aa..eb40bf7294 100644 --- a/tools/cli/src/lib/config/configuration-hash-parity.test.ts +++ b/tools/cli/src/lib/config/configuration-hash-parity.test.ts @@ -1,146 +1,39 @@ import { describe, expect, test } from 'bun:test'; import { readFile } from 'node:fs/promises'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { + CONFIGURATION_HASH_GOLDEN as GOLDEN, + NULL_DIGEST, +} from '../../../../../packages/shared/src/utils/configuration-hash.golden'; import { managedConfigurationHash } from '../../../../../services/platform/backend/core/lib/config_store/value_hash'; import { valueHash } from './releases/identity'; -/** One corpus, one digest each. The CLI's plans, receipts and releases and - * the platform's native preconditions (`hash` / `expectedHash`) were recorded - * with these two functions, so every digest here is a promise: no refactor - * may move one of them. */ -const GOLDEN: readonly (readonly [string, unknown, string])[] = [ - [ - 'true', - true, - 'b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b', - ], - [ - 'false', - false, - 'fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa', - ], - [ - 'zero', - 0, - '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', - ], - [ - 'negative zero', - -0, - '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', - ], - [ - 'integer', - 42, - '73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049', - ], - [ - 'negative', - -7, - 'a770d3270c9dcdedf12ed9fd70444f7c8a95c26cae3cae9bd867499090a2f14b', - ], - [ - 'fraction', - 1.5, - '9f29a130438b81170b92a42650f9a94291ecad60bd47af2a3886e75f7f728725', - ], - [ - 'exponent', - 1e21, - '241c4643fa70b1dcde1205b71be4e3bebb17e9f880c8e1a33d0ead6c27271d3c', - ], - [ - 'tiny', - 1e-7, - '5b33e02f2c5103a05d32f6ba9cb058294452bfbf393967f68bb30c1bdcbbab22', - ], - [ - 'beyond the safe integers', - 2 ** 53 + 2, - '25aa68783313802627958889943e895749ac4c0c7469b2a305cd450a12120768', - ], - [ - 'not a number (serialized as null)', - Number.NaN, - '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', - ], - [ - 'empty string', - '', - '12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126', - ], - [ - 'unicode string', - ' café 😺 ', - '9bfcef4d1b3e38e1ce77febf76a0c69402483d4887dff28b8dd217c333bf4e36', - ], - [ - 'escapes', - 'line\nbreak "quoted" \\ 
 \u0000', - '76da2c85724e3ff3927a2d4a02792a2324cc8c77c240f9645b711f3dd851eb3e', - ], - [ - 'empty array', - [], - '4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945', - ], - [ - 'empty object', - {}, - '44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a', - ], - [ - 'numeric keys and nested arrays', - { '10': 1, '2': ['x', { z: true, a: null }], '1': { '20': 2, '3': 3 } }, - '2edb082bd557ed6017442ce17de049016bc7697d1226f0e581be4673545c8953', - ], - [ - 'unsorted keys', - { b: 1, a: [3, { d: null, c: 'x' }] }, - 'b4a92c330fc01410911e683d5d03404eb28981a6e1d67f9cb1ae63ddc3d19947', - ], - [ - 'unicode and empty keys', - { é: 1, e: 2, Z: 3, '': 0 }, - '528bf91433a18ef395f2c7932427e6f6afa6cf4dd40e24af56640e70005d8fd9', - ], - [ - 'a policy', - { - enabled: true, - idleTimeoutMinutes: 45, - rules: [{ scope: 'org', maxTokens: 1000 }], - }, - '5c1093799a52bfe0671e5e3d7f3b204e7700ad17cd888115d4c2f075b00df2a1', - ], -]; - -/** `null` is the one JSON value the two functions answer differently on - * purpose: the platform's hash is a precondition, and a null precondition - * means "the resource is absent". */ -const NULL_DIGEST = - '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b'; - +/** The CLI keeps its own digest (`valueHash`, which refuses a value JSON + * cannot hold) for its releases, plans and receipts; the platform and the + * shared resource model use `configurationHash`. Both must agree on every + * JSON value, or a CLI plan would stop matching the platform's `hash`. */ describe('configuration hash parity', () => { test.each(GOLDEN)( '%s hashes to its golden digest', (_name, value, digest) => { expect(valueHash(value)).toBe(digest); expect(managedConfigurationHash(value)).toBe(digest); + expect(configurationHash(value)).toBe(digest); }, ); test('key order never changes a digest', () => { const forwards = { a: 1, b: { c: [1, 2], d: 'x' } }; const backwards = { b: { d: 'x', c: [1, 2] }, a: 1 }; - expect(valueHash(backwards)).toBe(valueHash(forwards)); - expect(managedConfigurationHash(backwards)).toBe( - managedConfigurationHash(forwards), - ); + for (const hash of [valueHash, managedConfigurationHash, configurationHash]) + expect(hash(backwards)).toBe(hash(forwards)); }); test('null is a digest for the CLI and an absent resource for the platform', () => { expect(valueHash(null)).toBe(NULL_DIGEST); + expect(configurationHash(null)).toBe(NULL_DIGEST); expect(managedConfigurationHash(null)).toBeNull(); }); @@ -154,9 +47,8 @@ describe('configuration hash parity', () => { ], ] as const) { expect(() => valueHash(value)).toThrow('not JSON serializable'); - expect(managedConfigurationHash(value)).toBe( - value === undefined ? NULL_DIGEST : valueHash(asNull), - ); + expect(configurationHash(value)).toBe(valueHash(asNull)); + expect(managedConfigurationHash(value)).toBe(valueHash(asNull)); } }); From 1b7fc25c12f699ac467e1bf8569487990f2435f4 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:12:01 +0200 Subject: [PATCH 03/35] refactor(shared): share the native platform resource model The resource model that `tale config platform` and managed deployments declare moves out of the CLI into @tale/shared, so the MCP settings tools can build on the same objects: `@tale/shared/config/platform-resources` holds the resource union, each resource's identity, a declaration's cross-resource rules and the convergence test, comparing `configurationHash` digests (the platform's own identity, equal to the CLI's on every JSON value). It sits outside the browser-safe `schemas/` because it hashes with Node's crypto. The CLI keeps what is its own: `parsePlatformConfiguration` with its usage error, the target and the reviewed plan file. The schema and convergence cases move to the shared suite with the synthetic fixture; the CLI keeps its usage-error and deployment-spec cases. The shared schema already refuses a field parsing would discard, so the CLI's second check of it goes. --- packages/shared/README.md | 7 + packages/shared/package.json | 1 + .../src/config/platform-resources.fixture.ts | 7 +- .../src/config/platform-resources.test.ts | 382 +++++++++++++++++ .../shared/src/config/platform-resources.ts | 391 ++++++++++++++++++ .../tests/manual/reference/automation.md | 2 +- tools/cli/src/commands/config/platform.ts | 2 +- .../src/lib/config/managed-resources.test.ts | 11 +- tools/cli/src/lib/config/managed-resources.ts | 2 +- .../cli/src/lib/config/platform-apply.test.ts | 5 +- tools/cli/src/lib/config/platform-apply.ts | 14 +- .../cli/src/lib/config/platform-model.test.ts | 374 +---------------- tools/cli/src/lib/config/platform-model.ts | 385 +---------------- .../cli/src/lib/config/platform-resources.ts | 14 +- tools/cli/src/lib/deployment/apply.test.ts | 5 +- tools/cli/src/lib/deployment/configuration.ts | 6 +- tools/cli/src/lib/deployment/model.ts | 2 +- 17 files changed, 834 insertions(+), 776 deletions(-) rename tools/cli/src/lib/config/platform-fixture.ts => packages/shared/src/config/platform-resources.fixture.ts (91%) create mode 100644 packages/shared/src/config/platform-resources.test.ts create mode 100644 packages/shared/src/config/platform-resources.ts diff --git a/packages/shared/README.md b/packages/shared/README.md index de66358bb5..b742413b2b 100644 --- a/packages/shared/README.md +++ b/packages/shared/README.md @@ -26,6 +26,13 @@ Every subpath below is declared in `package.json` `exports`. projects. Platform forms/APIs and CLI validation import these same objects. - **`@tale/shared/schemas/configuration`** — opaque native configuration hash preconditions. A null hash means an absent resource. +- **`@tale/shared/config/platform-resources`** — the native platform resource + model that `tale config platform`, managed deployments and the MCP settings + tools share: `platformResourceSchema` (one entry per declarable kind), each + resource's identity (`resourceId`), a declaration's cross-resource rules + (`platformConfigurationSchema`) and when stored state already is what was + asked for (`resourceConverged`). Server-only: it compares + `configurationHash` digests, so it sits outside the browser-safe `schemas/`. - **`@tale/shared/schemas/{automation-pack,automation-settings,task-contract}`** — automation package declarations and limits, operator settings forms and task bindings. Catalog reads, ZIP decoding and engine validation stay in the platform. diff --git a/packages/shared/package.json b/packages/shared/package.json index 9e071b2497..9eb14f3370 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -26,6 +26,7 @@ "./schemas/knowledge": "./src/schemas/knowledge.ts", "./schemas/providers": "./src/schemas/providers.ts", "./schemas/configuration": "./src/schemas/configuration.ts", + "./config/platform-resources": "./src/config/platform-resources.ts", "./schemas/managed-configuration": "./src/schemas/managed-configuration.ts", "./schemas/connectors": "./src/schemas/connectors.ts", "./schemas/epoch-ms": "./src/schemas/epoch-ms.ts", diff --git a/tools/cli/src/lib/config/platform-fixture.ts b/packages/shared/src/config/platform-resources.fixture.ts similarity index 91% rename from tools/cli/src/lib/config/platform-fixture.ts rename to packages/shared/src/config/platform-resources.fixture.ts index f11beb8985..7ab3b3df05 100644 --- a/tools/cli/src/lib/config/platform-fixture.ts +++ b/packages/shared/src/config/platform-resources.fixture.ts @@ -1,7 +1,8 @@ -import { parsePlatformConfiguration } from './platform-model'; +import { platformConfigurationSchema } from './platform-resources'; /** Synthetic settings span ordinary policies and external providers. No model - * hardware, source checkout, organization or endpoint is shared by clients. */ + * hardware, source checkout, organization or endpoint is shared by clients. + * Test support for the shared model's suite and the CLI's plan/apply suites. */ export function platformConfigurationFixture() { const providers = ['reasoning', 'vision', 'embedding'].map((role) => ({ kind: 'provider' as const, @@ -30,7 +31,7 @@ export function platformConfigurationFixture() { }, ], })); - return parsePlatformConfiguration({ + return platformConfigurationSchema.parse({ schemaVersion: 1, resources: [ { kind: 'branding', config: { accentColor: '#336699' } }, diff --git a/packages/shared/src/config/platform-resources.test.ts b/packages/shared/src/config/platform-resources.test.ts new file mode 100644 index 0000000000..b1b12d86e0 --- /dev/null +++ b/packages/shared/src/config/platform-resources.test.ts @@ -0,0 +1,382 @@ +import { describe, expect, test } from 'vitest'; + +import { POLICY_SCHEMAS } from '../schemas/governance'; +import { + platformConfigurationSchema, + resourceConverged, + resourceId, +} from './platform-resources'; +import { platformConfigurationFixture } from './platform-resources.fixture'; + +describe('native configuration declaration', () => { + test('uses the same ordinary policy defaults as the platform without requiring providers', () => { + const configuration = platformConfigurationSchema.parse({ + schemaVersion: 1, + resources: [ + { kind: 'governance', key: 'password_policy', config: {} }, + { kind: 'branding', config: { accentColor: '#336699' } }, + ], + }); + expect(configuration.resources[0].config).toEqual( + POLICY_SCHEMAS.password_policy.parse({}), + ); + expect(configuration.resources.map(resourceId)).toEqual([ + 'governance/password_policy', + 'branding', + ]); + }); + + test.each([ + { schemaVersion: 2, resources: [] }, + { + schemaVersion: 1, + resources: [{ kind: 'file', path: '/etc/passwd', config: {} }], + }, + { + schemaVersion: 1, + resources: [{ kind: 'governance', key: 'retention_policy', config: {} }], + }, + { + schemaVersion: 1, + resources: [{ kind: 'governance', key: 'dsar_governance', config: {} }], + }, + { + schemaVersion: 1, + resources: [{ kind: 'governance', key: '../foreign', config: {} }], + }, + { + schemaVersion: 1, + resources: [ + { kind: 'governance', key: 'password_policy', config: { typo: true } }, + ], + }, + { + schemaVersion: 1, + resources: [{ kind: 'branding', config: { accentColour: '#336699' } }], + }, + { + schemaVersion: 1, + resources: [ + { kind: 'deployment', config: { version: 1, dataStores: {} } }, + ], + }, + ])('rejects unsupported native fields and special workflows: %j', (input) => { + expect(platformConfigurationSchema.safeParse(input).success).toBe(false); + }); + + test('rejects duplicate resources, foreign catalog models and inconsistent model policies', () => { + for (const change of [ + 'duplicate', + 'foreign-model', + 'vision-model', + 'embedding-endpoint', + ]) { + const config = platformConfigurationFixture(); + if (change === 'duplicate') config.resources.push(config.resources[0]); + if (change === 'foreign-model') { + const provider = config.resources.find( + (entry) => entry.kind === 'provider', + )!; + provider.expectedModels![0].provider = 'another-provider'; + } + if (change === 'vision-model') { + const vision = config.resources.find( + (entry) => + entry.kind === 'governance' && entry.key === 'vision_model', + )!; + vision.config = { providerSlug: 'private-vision', modelId: 'unlisted' }; + } + if (change === 'embedding-endpoint') { + const embedding = config.resources.find( + (entry) => entry.kind === 'knowledge-embedding', + )!; + embedding.config.baseUrl = 'https://other.example.invalid/v1'; + } + expect( + platformConfigurationSchema.safeParse(config).success, + change, + ).toBe(false); + } + }); + + test('accepts automatic transcription and validates pinned provider capabilities', () => { + const declaration = ( + apiFormat = 'openai', + tags = ['transcription'], + modelId = 'example-asr', + ) => ({ + schemaVersion: 1, + resources: [ + { + kind: 'provider', + config: { + name: 'example-audio', + displayName: 'Example audio', + apiFormat, + baseUrl: 'https://audio.example.invalid/v1', + catalog: { source: 'models-endpoint' }, + auth: [{ method: 'api-key' }], + }, + expectedModels: [ + { + id: 'example-asr', + provider: 'example-audio', + tags, + supportsTools: false, + supportsVision: false, + contextWindow: 448, + }, + ], + }, + { + kind: 'governance', + key: 'transcription_model', + config: { providerSlug: 'example-audio', modelId }, + }, + ], + }); + expect( + platformConfigurationSchema.safeParse({ + schemaVersion: 1, + resources: [ + { kind: 'governance', key: 'transcription_model', config: {} }, + ], + }).success, + ).toBe(true); + expect(platformConfigurationSchema.safeParse(declaration()).success).toBe( + true, + ); + expect( + platformConfigurationSchema.safeParse(declaration('anthropic')).success, + ).toBe(false); + expect( + platformConfigurationSchema.safeParse(declaration('openai', ['chat'])) + .success, + ).toBe(false); + expect( + platformConfigurationSchema.safeParse( + declaration('openai', ['transcription'], 'missing'), + ).success, + ).toBe(false); + }); + + test('accepts image generation off or automatic and validates a pinned image model', () => { + const declaration = ( + apiFormat = 'openai', + tags = ['image-generation'], + modelId = 'example-image', + ) => ({ + schemaVersion: 1, + resources: [ + { + kind: 'provider', + config: { + name: 'example-images', + displayName: 'Example images', + apiFormat, + baseUrl: 'https://images.example.invalid/v1', + catalog: { source: 'models-endpoint' }, + auth: [{ method: 'api-key' }], + }, + expectedModels: [ + { + id: 'example-image', + provider: 'example-images', + tags, + supportsTools: false, + supportsVision: true, + outputsMedia: true, + contextWindow: 32_000, + }, + ], + }, + { + kind: 'governance', + key: 'image_generation', + config: { enabled: true, providerSlug: 'example-images', modelId }, + }, + ], + }); + for (const config of [{ enabled: false }, { enabled: true }]) { + expect( + platformConfigurationSchema.safeParse({ + schemaVersion: 1, + resources: [{ kind: 'governance', key: 'image_generation', config }], + }).success, + ).toBe(true); + } + expect(platformConfigurationSchema.safeParse(declaration()).success).toBe( + true, + ); + expect( + platformConfigurationSchema.safeParse(declaration('anthropic')).success, + ).toBe(false); + expect( + platformConfigurationSchema.safeParse(declaration('openai', ['chat'])) + .success, + ).toBe(false); + expect( + platformConfigurationSchema.safeParse( + declaration('openai', ['image-generation'], 'missing'), + ).success, + ).toBe(false); + }); + + test('rejects raw credential secrets and unrelated environment variables', () => { + for (const changes of [ + { secret: 'must-never-appear' }, + { envName: 'BETTER_AUTH_SECRET' }, + { authMethod: 'api-key' }, + { status: 'disabled', isDefault: true }, + ]) { + const config = platformConfigurationFixture(); + const credential = config.resources.find( + (entry) => entry.kind === 'provider-credential', + )!; + Object.assign(credential.config, changes); + expect(platformConfigurationSchema.safeParse(config).success).toBe(false); + } + }); +}); + +describe('the embedding floor in a declaration', () => { + const embedding = () => + platformConfigurationFixture().resources.find( + (entry) => entry.kind === 'knowledge-embedding', + )!; + const declare = (config: object) => + platformConfigurationSchema.safeParse({ + schemaVersion: 1, + resources: [{ kind: 'knowledge-embedding', config }], + }); + + test('accepts a number, null (clear) and absence (keep); refuses anything else', () => { + expect( + declare({ ...embedding().config, minSimilarity: 0.55 }).success, + ).toBe(true); + expect( + declare({ ...embedding().config, minSimilarity: null }).success, + ).toBe(true); + expect(declare(embedding().config).success).toBe(true); + expect( + declare({ ...embedding().config, minSimilarity: '0.5' }).success, + ).toBe(false); + expect(declare({ ...embedding().config, minSimilarity: 1.5 }).success).toBe( + false, + ); + }); + + test('accepts the serving limits the same three ways, within the platform’s bounds', () => { + for (const fields of [ + { maxConcurrentRequests: 2, minTokensPerSecond: 750 }, + { maxConcurrentRequests: null, minTokensPerSecond: null }, + { minTokensPerSecond: 1349.5 }, + {}, + ]) + expect( + declare({ ...embedding().config, ...fields }).success, + JSON.stringify(fields), + ).toBe(true); + for (const fields of [ + { maxConcurrentRequests: 0 }, + { maxConcurrentRequests: 65 }, + { maxConcurrentRequests: 1.5 }, + { minTokensPerSecond: 0 }, + { minTokensPerSecond: '750' }, + { maxConcurrentRequest: 2 }, + ]) + expect( + declare({ ...embedding().config, ...fields }).success, + JSON.stringify(fields), + ).toBe(false); + }); + + test('converges per kept setting when a declaration states several', () => { + const resource = (fields: object) => + platformConfigurationSchema.parse({ + schemaVersion: 1, + resources: [ + { + kind: 'knowledge-embedding', + config: { ...embedding().config, ...fields }, + }, + ], + }).resources[0]; + const stored = (fields: object) => ({ ...embedding().config, ...fields }); + const limits = { maxConcurrentRequests: 2, minTokensPerSecond: 750 }; + + // Omitted settings accept whatever is stored; stated ones must match. + expect( + resourceConverged( + resource({ maxConcurrentRequests: 2 }), + stored({ ...limits, minSimilarity: 0.5 }), + ), + ).toBe(true); + expect( + resourceConverged( + resource(limits), + stored({ ...limits, minSimilarity: 0.5 }), + ), + ).toBe(true); + expect( + resourceConverged( + resource(limits), + stored({ maxConcurrentRequests: 2, minTokensPerSecond: 500 }), + ), + ).toBe(false); + expect( + resourceConverged(resource(limits), stored({ maxConcurrentRequests: 2 })), + ).toBe(false); + // Null converges only once that setting is gone, whatever else is kept. + expect( + resourceConverged( + resource({ minTokensPerSecond: null, minSimilarity: null }), + stored({ maxConcurrentRequests: 2 }), + ), + ).toBe(true); + expect( + resourceConverged(resource({ minTokensPerSecond: null }), stored(limits)), + ).toBe(false); + expect( + resourceConverged( + resource({ ...limits, minSimilarity: null }), + stored(limits), + ), + ).toBe(true); + }); + + test('converges on the platform’s own terms — omitted keeps, null clears, a number matches exactly', () => { + const resource = (minSimilarity?: number | null) => + platformConfigurationSchema.parse({ + schemaVersion: 1, + resources: [ + { + kind: 'knowledge-embedding', + config: { + ...embedding().config, + ...(minSimilarity === undefined ? {} : { minSimilarity }), + }, + }, + ], + }).resources[0]; + const stored = (minSimilarity?: number) => ({ + ...embedding().config, + ...(minSimilarity === undefined ? {} : { minSimilarity }), + }); + // Omitted: whatever is stored is fine. + expect(resourceConverged(resource(), stored())).toBe(true); + expect(resourceConverged(resource(), stored(0.55))).toBe(true); + // Null: converged only once nothing is stored. + expect(resourceConverged(resource(null), stored())).toBe(true); + expect(resourceConverged(resource(null), stored(0.55))).toBe(false); + // A number: exact. + expect(resourceConverged(resource(0.6), stored(0.6))).toBe(true); + expect(resourceConverged(resource(0.6), stored(0.55))).toBe(false); + expect(resourceConverged(resource(0.6), stored())).toBe(false); + // Nothing stored at all, and a different model: never converged. + expect(resourceConverged(resource(), null)).toBe(false); + expect( + resourceConverged(resource(), { ...stored(), model: 'Other-model' }), + ).toBe(false); + }); +}); diff --git a/packages/shared/src/config/platform-resources.ts b/packages/shared/src/config/platform-resources.ts new file mode 100644 index 0000000000..f0a37388cd --- /dev/null +++ b/packages/shared/src/config/platform-resources.ts @@ -0,0 +1,391 @@ +import { z } from 'zod'; + +import { brandingFormSchema } from '../schemas/branding'; +import { deploymentConfigSchema } from '../schemas/deployment'; +import { FILE_POLICY_TYPES, POLICY_SCHEMAS } from '../schemas/governance'; +import { + KNOWLEDGE_EMBEDDING_KEPT_KEYS, + knowledgeEmbeddingWriteSchema, +} from '../schemas/knowledge'; +import { managedPlatformResourceSchema } from '../schemas/managed-configuration'; +import { + modelCatalogFileSchema, + providerDefinitionSchema, + providerEnvironmentCredentialSchema, +} from '../schemas/providers'; +import { configurationHash } from '../utils/configuration-hash'; + +/** + * The native platform resource model: the configuration resources one + * declaration (`tale config platform`, a managed deployment) or one MCP + * settings change names, how each is identified, which cross-resource rules a + * declaration obeys, and when the stored state already IS what was asked for. + * The platform owns every field, default, permission, lock and side effect; + * this envelope only selects a native resource. + * + * Server-only: identity and convergence compare `configurationHash` digests + * (Node's crypto), which is why it lives outside the browser-safe `schemas/`. + */ + +// Adding a policy to the platform does not require a copy here: the key +// selects the platform's own schema. +const governance = z + .strictObject({ + kind: z.literal('governance'), + key: z + .enum(FILE_POLICY_TYPES) + .refine( + (key) => !['retention_policy', 'dsar_governance'].includes(key), + 'This policy requires its dedicated native workflow', + ), + config: z.unknown(), + }) + .transform((resource, context) => { + const parsed = POLICY_SCHEMAS[resource.key].safeParse(resource.config); + if (!parsed.success) { + context.addIssue({ + code: 'custom', + message: 'Invalid native policy configuration', + }); + return z.NEVER; + } + return { ...resource, config: parsed.data }; + }); + +export const platformResourceSchema = z.union([ + managedPlatformResourceSchema, + governance, + z.strictObject({ + kind: z.literal('branding'), + config: brandingFormSchema.strict(), + }), + z.strictObject({ + kind: z.literal('deployment'), + config: deploymentConfigSchema, + }), + z.strictObject({ + kind: z.literal('knowledge-embedding'), + // The platform keeps a stored similarity floor or serving limit + // (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, + // `maxTokensPerMinute`, `maxRequestsPerMinute`) when + // a save omits it and clears it only on an explicit null (the Settings + // form never carries them) — so the declaration speaks the same three + // ways: a value sets it, `null` clears it, omitted leaves what is stored. + config: knowledgeEmbeddingWriteSchema.strict(), + }), + z.strictObject({ + kind: z.literal('provider'), + config: providerDefinitionSchema, + expectedModels: modelCatalogFileSchema + .refine((models) => models.length <= 200) + .optional(), + }), + z.strictObject({ + kind: z.literal('provider-credential'), + config: providerEnvironmentCredentialSchema, + }), +]); +export type PlatformResource = z.infer; + +export function resourceId(resource: PlatformResource): string { + switch (resource.kind) { + case 'project-instructions': + return `project-instructions/${resource.config.projectId}`; + case 'agent-instructions': + case 'agent-tools': + return `${resource.kind}/${resource.config.projectId}/${resource.config.agentId}`; + case 'task-instructions': + return `task-instructions/${resource.config.projectId}/${resource.config.taskId}`; + case 'automation-definition': + case 'automation-deployment': + case 'automation-schedule': + return `${resource.kind}/${resource.config.projectId}/${resource.config.name}`; + case 'governance': + return `governance/${resource.key}`; + case 'provider': + return `provider/${resource.config.name}`; + case 'provider-credential': + return `provider-credential/${resource.config.providerSlug}/${encodeURIComponent(resource.config.name)}`; + default: + return resource.kind; + } +} + +const declarationSchema = z + .strictObject({ + schemaVersion: z.literal(1), + resources: z.array(platformResourceSchema).min(1).max(128), + }) + .superRefine((configuration, context) => { + const ids = configuration.resources.map(resourceId); + const fail = (message: string) => + context.addIssue({ code: 'custom', message }); + if (new Set(ids).size !== ids.length) + fail('Duplicate native configuration resource'); + for (const resource of configuration.resources) { + if ( + resource.kind !== 'automation-deployment' && + resource.kind !== 'automation-schedule' + ) + continue; + const definition = configuration.resources.find( + (candidate) => + candidate.kind === 'automation-definition' && + candidate.config.name === resource.config.name && + candidate.config.projectId === resource.config.projectId, + ); + if ( + !definition || + (resource.kind === 'automation-deployment' && + configurationHash(definition.config) !== + resource.config.definitionSha256) + ) + fail( + 'Managed automation deployment requires its exact declared definition', + ); + if ( + resource.kind === 'automation-schedule' && + !configuration.resources.some( + (candidate) => + candidate.kind === 'automation-deployment' && + candidate.config.name === resource.config.name && + candidate.config.projectId === resource.config.projectId, + ) + ) + fail('Managed schedule requires its declared automation deployment'); + } + const managedNames = configuration.resources + .filter((resource) => resource.kind === 'automation-definition') + .map((resource) => resource.config.name); + if (new Set(managedNames).size !== managedNames.length) + fail( + 'An organization-wide automation cannot have two managed project owners', + ); + const providers = configuration.resources.filter( + (resource) => resource.kind === 'provider', + ); + const defaults = configuration.resources + .filter((resource) => resource.kind === 'provider-credential') + .filter( + (resource) => + resource.config.isDefault && resource.config.status === 'active', + ); + if ( + configuration.resources.some( + (resource) => + resource.kind === 'provider-credential' && + resource.config.isDefault && + resource.config.status !== 'active', + ) + ) + fail('A default credential must be active'); + if ( + new Set(defaults.map((resource) => resource.config.providerSlug)).size !== + defaults.length + ) + fail('A provider cannot have two declared default credentials'); + for (const provider of providers) + if ( + provider.expectedModels?.some( + (model) => model.provider !== provider.config.name, + ) + ) + fail('Expected catalog belongs to another provider'); + for (const resource of configuration.resources) { + if (resource.kind === 'knowledge-embedding') { + const provider = providers.find( + (entry) => entry.config.name === resource.config.providerSlug, + ); + if ( + provider && + (provider.config.embedding !== 'supported' || + (provider.config.baseUrl && + resource.config.baseUrl !== provider.config.baseUrl) || + (provider.expectedModels && + !provider.expectedModels.some( + (model) => + model.id === resource.config.model && + model.tags.includes('embedding'), + ))) + ) + fail( + 'Embedding selection differs from its declared provider and catalog', + ); + } + if (resource.kind === 'governance' && resource.key === 'vision_model') { + const vision = POLICY_SCHEMAS.vision_model.parse(resource.config); + const provider = providers.find( + (entry) => entry.config.name === vision.providerSlug, + ); + if ( + provider?.expectedModels && + !provider.expectedModels.some( + (model) => model.id === vision.modelId && model.supportsVision, + ) + ) + fail('Vision selection differs from its declared catalog'); + } + if ( + resource.kind === 'governance' && + resource.key === 'transcription_model' + ) { + const transcription = POLICY_SCHEMAS.transcription_model.parse( + resource.config, + ); + const provider = providers.find( + (entry) => entry.config.name === transcription.providerSlug, + ); + if ( + provider && + (provider.config.apiFormat !== 'openai' || + (provider.expectedModels && + !provider.expectedModels.some( + (model) => + model.id === transcription.modelId && + model.tags.includes('transcription'), + ))) + ) + fail( + 'Transcription selection differs from its declared provider and catalog', + ); + } + if ( + resource.kind === 'governance' && + resource.key === 'image_generation' + ) { + const image = POLICY_SCHEMAS.image_generation.parse(resource.config); + const provider = providers.find( + (entry) => entry.config.name === image.providerSlug, + ); + // The same admission a turn applies: an OpenAI-format provider, and + // a pinned model its declared catalog lists as an image generator. + if ( + provider && + (provider.config.apiFormat !== 'openai' || + (provider.expectedModels && + !provider.expectedModels.some( + (model) => + model.id === image.modelId && + model.tags.includes('image-generation'), + ))) + ) + fail( + 'Image generation selection differs from its declared provider and catalog', + ); + } + } + }); +export type PlatformConfiguration = z.infer; + +/** Normalization may add native defaults, but must not hide misspelled fields. */ +function discardedKeys(input: unknown, parsed: unknown): boolean { + if (Array.isArray(input)) + return ( + !Array.isArray(parsed) || + input.some((entry, i) => discardedKeys(entry, parsed[i])) + ); + if (input && typeof input === 'object') { + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) + return true; + return Object.entries(input).some( + ([key, value]) => + !Object.hasOwn(parsed, key) || + discardedKeys(value, Reflect.get(parsed, key)), + ); + } + return false; +} + +export const platformConfigurationSchema = z + .unknown() + .transform((input, context) => { + const parsed = declarationSchema.safeParse(input); + if (!parsed.success || discardedKeys(input, parsed.data)) { + context.addIssue({ + code: 'custom', + message: 'Unsupported resources or invalid native configuration fields', + }); + return z.NEVER; + } + return parsed.data; + }); + +export const sameConfiguration = (left: unknown, right: unknown) => + configurationHash(left) === configurationHash(right); + +function isObject(value: unknown): value is object { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +const keptSettings: readonly string[] = KNOWLEDGE_EMBEDDING_KEPT_KEYS; + +/** An embedding config without the settings a write keeps when it omits + * them: what remains names the model — provider, credential, tag, width and + * endpoint. */ +function embeddingModelOf(value: object): Record { + return Object.fromEntries( + Object.entries(value).filter(([key]) => !keptSettings.includes(key)), + ); +} + +/** Whether a declared embedding names the model already stored, so that it + * changes at most the kept settings — the similarity floor and the serving + * limits, none of which touches the vector space. */ +export function sameEmbeddingModel(declared: object, current: unknown) { + return ( + isObject(current) && + configurationHash(embeddingModelOf(declared)) === + configurationHash(embeddingModelOf(current)) + ); +} + +/** + * Whether the native state already IS what the declaration asks for — the + * one comparison plan, apply and readback all use, so a resource whose + * write semantics are not "replace the whole object" converges on the + * platform's own terms rather than never at all. + * + * Every resource compares whole, except the embedding's kept settings + * (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, + * `maxTokensPerMinute`, `maxRequestsPerMinute`): the + * platform keeps a stored one when the write omits it and clears it on an + * explicit null, so a declaration that omits one converges with ANY stored + * value, one that declares `null` converges only once none is stored, and a + * declared value must match exactly — each setting on its own. + */ +export function resourceConverged( + resource: PlatformResource, + current: unknown, +): boolean { + return resourceConvergedWithHash( + resource, + current, + configurationHash(resource.config), + ); +} + +/** A retained plan holds the declaration hash, not its original secret-free + * object. Compare that hash with precisely the declarations native readback + * satisfies, including the kept settings' preserve/clear semantics. */ +export function resourceConvergedWithHash( + resource: PlatformResource, + current: unknown, + desiredSha256: string, +): boolean { + if (resource.kind !== 'knowledge-embedding' || !isObject(current)) + return configurationHash(current) === desiredSha256; + // Every declaration this state satisfies: each kept setting either + // omitted (whatever is stored stays) or stated as what is stored — `null` + // when nothing is. + let readings = [embeddingModelOf(current)]; + for (const key of keptSettings) { + const stored: unknown = Reflect.get(current, key); + readings = readings.flatMap((reading) => [ + reading, + { ...reading, [key]: stored ?? null }, + ]); + } + return readings.some( + (reading) => configurationHash(reading) === desiredSha256, + ); +} diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 6c66e97a51..64fcd50a04 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -912,7 +912,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [video-links](../suites/video-links.md) | `VID-B1`–`VID-B3` | 🔶 partial | `backend/core/video_links/ytdlp.test.ts` (stderr classifier, env-flag builders, log sanitizer); the live job-row/log behaviour is manual | | [video-links](../suites/video-links.md) | `VID-B5` (the component and door halves): a refused Remove brings the chip back and toasts the reason — a video-link code's own sentence, else the refusal's words, a lost connection or an ended session, else that the video is still attached — and a later Remove succeeds; a refused Try again, in the composer or a queued message's row, toasts the same way and keeps the failed chip; over the Hono routes a disabled member's cancel and retry answer 403 `ORG_FORBIDDEN` and leave the job queued, and a held worker result after a successful cancel lands nothing | 🔶 component + real Postgres | `app/features/chat/hooks/use-chat-video-links.test.tsx`, `app/features/chat/components/deferred-send-tray.test.tsx`, `backend/integration-check.ts` (`checkVideoLinkComposerChips`, run by `backend:integration`); the toast's placement and announcement stay manual | | [knowledge](../suites/knowledge.md) | A file's whole-document preparation (secret scan, PII policy, chunking, content hash, repeat map) runs once across every indexing slice: a multi-slice document is prepared once, reports progress per slice and completes only after the last slice lands; a preparation refusal records `failed` without embedding | ✅ automated | `backend/core/knowledge/indexing.test.ts`, the `knowledge indexing drains every slice (multi-slice doc completes)` lane in `backend:integration` | -| [knowledge](../suites/knowledge.md) | Embedding pacing from `embedding.json` (`maxConcurrentRequests`, `minTokensPerSecond`): one in-flight bound per organization, endpoint and model, shared by every embedder in the process (arrival order with a search query ahead of waiting batches, 3 when unset, never above the lowest bound a live request was made under); a failed, timed-out or abandoned request frees its slot; the first failed batch of a call stops its other batches (running cancelled, queued unsent) and stays the error the caller sees; a timed-out or abandoned request is not sent again, other retries back off and honour `Retry-After` up to a minute; the per-request timeout covers queue wait plus compute from a conservative token estimate, under a ceiling of 15 min for a batch and 5 min for a search query (the whole search, slot wait included, ends as a classifiable timeout), never under 60 s; the search ceiling stays at most half the chat generation watchdog window; an indexing run stops at the job budget without a `failed` write and its retry resumes; the settings form keeps the limits and only `null` clears them; the CLI declares them, converges per setting, and a limits-only change skips the empty-corpus refusal | ✅ automated | `backend/core/knowledge/embedding.test.ts`, `backend/core/knowledge/indexing.test.ts`, `backend/domains/knowledge/service.status-codes.test.ts`, `backend/jobs/runner.test.ts`, `backend/domains/knowledge/admin.test.ts`, `backend/domains/configuration-writes.test.ts`, `backend/domains/chat/watchdogs.test.ts`, `packages/shared/src/schemas/knowledge.test.ts`, `tools/cli/src/lib/config/platform-model.test.ts`, `tools/cli/src/lib/config/platform-apply.test.ts`; the load a real self-hosted server takes stays a deployment check | +| [knowledge](../suites/knowledge.md) | Embedding pacing from `embedding.json` (`maxConcurrentRequests`, `minTokensPerSecond`): one in-flight bound per organization, endpoint and model, shared by every embedder in the process (arrival order with a search query ahead of waiting batches, 3 when unset, never above the lowest bound a live request was made under); a failed, timed-out or abandoned request frees its slot; the first failed batch of a call stops its other batches (running cancelled, queued unsent) and stays the error the caller sees; a timed-out or abandoned request is not sent again, other retries back off and honour `Retry-After` up to a minute; the per-request timeout covers queue wait plus compute from a conservative token estimate, under a ceiling of 15 min for a batch and 5 min for a search query (the whole search, slot wait included, ends as a classifiable timeout), never under 60 s; the search ceiling stays at most half the chat generation watchdog window; an indexing run stops at the job budget without a `failed` write and its retry resumes; the settings form keeps the limits and only `null` clears them; the CLI declares them, converges per setting, and a limits-only change skips the empty-corpus refusal | ✅ automated | `backend/core/knowledge/embedding.test.ts`, `backend/core/knowledge/indexing.test.ts`, `backend/domains/knowledge/service.status-codes.test.ts`, `backend/jobs/runner.test.ts`, `backend/domains/knowledge/admin.test.ts`, `backend/domains/configuration-writes.test.ts`, `backend/domains/chat/watchdogs.test.ts`, `packages/shared/src/schemas/knowledge.test.ts`, `packages/shared/src/config/platform-resources.test.ts`, `tools/cli/src/lib/config/platform-apply.test.ts`; the load a real self-hosted server takes stays a deployment check | | [responsive](../suites/responsive.md) | `RESP-P3` (mobile shell skeleton) — the capsule placeholder is the live `BottomTabBar`'s exact size and position at phone widths, draws no text, the dashboard layout keeps it while access resolves, and the Safari toolbar clearance is marked before paint by the same checks `useDisplayMode` uses | 🔶 component + browser | `packages/ui/src/components/navigation/bottom-tab-bar.test.tsx`, `packages/ui/src/components/navigation/bottom-tab-bar.browser.test.tsx`, `services/platform/app/components/layout/boot-safari-toolbar-script.test.ts`, `services/platform/app/components/layout/boot-shell-render.test.tsx`; the reload on a real phone remains manual | | [automations](../suites/automations.md) | A Claude Code automation `agent` turn on a connector that declares a native Anthropic harness endpoint (DeepSeek) rides the connector's `…__anthropic` gateway record on the kick's exec model and scheduled start, the start's key mint and the answered-ask resume; a serving without the lane keeps the OpenAI record end to end | ✅ automated | `backend/core/automations/agent_host.anthropic_lane.test.ts`, `backend/core/lib/providers/agent_serving.test.ts`, `backend/core/node_only/sandbox/gateway_provisioning.test.ts`, `backend/core/node_only/sandbox/llm_gateway_admin.test.ts`; the vendor endpoint's own behaviour (thinking replay, dropped document blocks) remains a live-run check | | [automations](../suites/automations.md) / [tasks](../suites/tasks.md) | A managed agent turn that the gateway refuses mid-turn with 402 (its key's budget, sized from the org spend cap, is spent) settles as `budget_exceeded` with a reason naming the exhausted allowance, and neither lane's auto-retry resumes it. | ✅ automated | `backend/core/automations/agent_host.retry_resume.test.ts`, `backend/core/tasks/agent_run_host.budget_exceeded.test.ts`, `backend/core/chat/external_turn_shared.test.ts` | diff --git a/tools/cli/src/commands/config/platform.ts b/tools/cli/src/commands/config/platform.ts index 583bbb366b..d1729eb610 100644 --- a/tools/cli/src/commands/config/platform.ts +++ b/tools/cli/src/commands/config/platform.ts @@ -1,6 +1,7 @@ import { realpath } from 'node:fs/promises'; import { basename, dirname, resolve } from 'node:path'; +import { resourceId } from '@tale/shared/config/platform-resources'; import { Command } from 'commander'; import { @@ -12,7 +13,6 @@ import { connectPlatformConfiguration } from '../../lib/config/platform-client'; import { configurationPlanSchema, parsePlatformConfiguration, - resourceId, } from '../../lib/config/platform-model'; import { valueHash } from '../../lib/config/releases/identity'; import { boundedJson, writePrivateJson } from '../../lib/state/private-files'; diff --git a/tools/cli/src/lib/config/managed-resources.test.ts b/tools/cli/src/lib/config/managed-resources.test.ts index 98c769b3cf..536be0f288 100644 --- a/tools/cli/src/lib/config/managed-resources.test.ts +++ b/tools/cli/src/lib/config/managed-resources.test.ts @@ -3,6 +3,11 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { + resourceId, + type PlatformResource, +} from '@tale/shared/config/platform-resources'; + import { managedConfigurationHash } from '../../../../../services/platform/backend/core/lib/config_store/value_hash'; import { readManagedResource } from './managed-resources'; import { @@ -10,11 +15,7 @@ import { planPlatformConfiguration, } from './platform-apply'; import type { PlatformConfigurationClient } from './platform-client'; -import { - parsePlatformConfiguration, - resourceId, - type PlatformResource, -} from './platform-model'; +import { parsePlatformConfiguration } from './platform-model'; import { valueHash } from './releases/identity'; const roots: string[] = []; diff --git a/tools/cli/src/lib/config/managed-resources.ts b/tools/cli/src/lib/config/managed-resources.ts index 7524064927..5099963aba 100644 --- a/tools/cli/src/lib/config/managed-resources.ts +++ b/tools/cli/src/lib/config/managed-resources.ts @@ -1,3 +1,4 @@ +import type { PlatformResource } from '@tale/shared/config/platform-resources'; import { expectedConfigurationHashSchema } from '@tale/shared/schemas/configuration'; import { managedPlatformResourceSchema, @@ -7,7 +8,6 @@ import { z } from 'zod'; import { preconditionError } from '../../utils/fail'; import type { PlatformConfigurationClient } from './platform-client'; -import type { PlatformResource } from './platform-model'; import { valueHash } from './releases/identity'; export function isManagedResource( diff --git a/tools/cli/src/lib/config/platform-apply.test.ts b/tools/cli/src/lib/config/platform-apply.test.ts index 98480eb2d3..bd6f0f35d9 100644 --- a/tools/cli/src/lib/config/platform-apply.test.ts +++ b/tools/cli/src/lib/config/platform-apply.test.ts @@ -10,8 +10,10 @@ import { import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; +import { resourceId } from '@tale/shared/config/platform-resources'; import { KNOWLEDGE_EMBEDDING_KEPT_KEYS } from '@tale/shared/schemas/knowledge'; +import { platformConfigurationFixture } from '../../../../../packages/shared/src/config/platform-resources.fixture'; import { preconditionError } from '../../utils/fail'; import { writeDeploymentBundle } from '../deployment/bundle'; import { @@ -26,8 +28,7 @@ import { readPlatformConfiguration, } from './platform-apply'; import type { PlatformConfigurationClient } from './platform-client'; -import { platformConfigurationFixture } from './platform-fixture'; -import { parsePlatformConfiguration, resourceId } from './platform-model'; +import { parsePlatformConfiguration } from './platform-model'; import { valueHash } from './releases/identity'; const directories: string[] = []; diff --git a/tools/cli/src/lib/config/platform-apply.ts b/tools/cli/src/lib/config/platform-apply.ts index d9b1168f35..f6dd81ec0c 100644 --- a/tools/cli/src/lib/config/platform-apply.ts +++ b/tools/cli/src/lib/config/platform-apply.ts @@ -1,3 +1,11 @@ +import { + resourceConverged, + resourceConvergedWithHash, + resourceId, + sameConfiguration, + type PlatformConfiguration, + type PlatformResource, +} from '@tale/shared/config/platform-resources'; import { z } from 'zod'; import { CliError, preconditionError } from '../../utils/fail'; @@ -6,13 +14,7 @@ import type { PlatformConfigurationClient } from './platform-client'; import { configurationPlanSchema, parsePlatformConfiguration, - resourceConverged, - resourceConvergedWithHash, - resourceId, - sameConfiguration, type ConfigurationPlan, - type PlatformConfiguration, - type PlatformResource, } from './platform-model'; import { checkResourceChange, diff --git a/tools/cli/src/lib/config/platform-model.test.ts b/tools/cli/src/lib/config/platform-model.test.ts index 2868593146..1d18465ee0 100644 --- a/tools/cli/src/lib/config/platform-model.test.ts +++ b/tools/cli/src/lib/config/platform-model.test.ts @@ -2,253 +2,31 @@ import { describe, expect, test } from 'bun:test'; import { tmpdir } from 'node:os'; import { resolve } from 'node:path'; -import { POLICY_SCHEMAS } from '@tale/shared/schemas/governance'; - +import { platformConfigurationFixture } from '../../../../../packages/shared/src/config/platform-resources.fixture'; import { deploymentSpecSchema } from '../deployment/model'; -import { platformConfigurationFixture } from './platform-fixture'; -import { - parsePlatformConfiguration, - platformConfigurationSchema, - resourceConverged, - resourceId, -} from './platform-model'; +import { parsePlatformConfiguration } from './platform-model'; +// The resource model's own cases (kinds, defaults, cross-resource rules, +// convergence) live beside it in @tale/shared/config/platform-resources. describe('native configuration declaration', () => { - test('uses the same ordinary policy defaults as the platform without requiring providers', () => { - const configuration = parsePlatformConfiguration({ - schemaVersion: 1, - resources: [ - { kind: 'governance', key: 'password_policy', config: {} }, - { kind: 'branding', config: { accentColor: '#336699' } }, - ], - }); - expect(configuration.resources[0]!.config).toEqual( - POLICY_SCHEMAS.password_policy.parse({}), - ); - expect(configuration.resources.map(resourceId)).toEqual([ - 'governance/password_policy', - 'branding', - ]); - }); - test.each([ - { schemaVersion: 2, resources: [] }, - { - schemaVersion: 1, - resources: [{ kind: 'file', path: '/etc/passwd', config: {} }], - }, { schemaVersion: 1, resources: [{ kind: 'governance', key: 'retention_policy', config: {} }], }, - { - schemaVersion: 1, - resources: [{ kind: 'governance', key: 'dsar_governance', config: {} }], - }, - { - schemaVersion: 1, - resources: [{ kind: 'governance', key: '../foreign', config: {} }], - }, - { - schemaVersion: 1, - resources: [ - { kind: 'governance', key: 'password_policy', config: { typo: true } }, - ], - }, { schemaVersion: 1, resources: [{ kind: 'branding', config: { accentColour: '#336699' } }], }, - { - schemaVersion: 1, - resources: [ - { kind: 'deployment', config: { version: 1, dataStores: {} } }, - ], - }, ])( - 'rejects unsupported native fields and special workflows before I/O: %j', + 'refuses an unsupported declaration as a usage error before I/O: %j', (input) => { - expect(platformConfigurationSchema.safeParse(input).success).toBe(false); expect(() => parsePlatformConfiguration(input)).toThrow( 'unsupported resources', ); }, ); - test('rejects duplicate resources, foreign catalog models and inconsistent model policies', () => { - for (const change of [ - 'duplicate', - 'foreign-model', - 'vision-model', - 'embedding-endpoint', - ]) { - const config = platformConfigurationFixture(); - if (change === 'duplicate') config.resources.push(config.resources[0]!); - if (change === 'foreign-model') { - const provider = config.resources.find( - (entry) => entry.kind === 'provider', - )!; - provider.expectedModels![0]!.provider = 'another-provider'; - } - if (change === 'vision-model') { - const vision = config.resources.find( - (entry) => - entry.kind === 'governance' && entry.key === 'vision_model', - )!; - vision.config = { providerSlug: 'private-vision', modelId: 'unlisted' }; - } - if (change === 'embedding-endpoint') { - const embedding = config.resources.find( - (entry) => entry.kind === 'knowledge-embedding', - )!; - embedding.config.baseUrl = 'https://other.example.invalid/v1'; - } - expect( - platformConfigurationSchema.safeParse(config).success, - change, - ).toBe(false); - } - }); - - test('accepts automatic transcription and validates pinned provider capabilities', () => { - const declaration = ( - apiFormat = 'openai', - tags = ['transcription'], - modelId = 'example-asr', - ) => ({ - schemaVersion: 1, - resources: [ - { - kind: 'provider', - config: { - name: 'example-audio', - displayName: 'Example audio', - apiFormat, - baseUrl: 'https://audio.example.invalid/v1', - catalog: { source: 'models-endpoint' }, - auth: [{ method: 'api-key' }], - }, - expectedModels: [ - { - id: 'example-asr', - provider: 'example-audio', - tags, - supportsTools: false, - supportsVision: false, - contextWindow: 448, - }, - ], - }, - { - kind: 'governance', - key: 'transcription_model', - config: { providerSlug: 'example-audio', modelId }, - }, - ], - }); - expect( - platformConfigurationSchema.safeParse({ - schemaVersion: 1, - resources: [ - { kind: 'governance', key: 'transcription_model', config: {} }, - ], - }).success, - ).toBe(true); - expect(platformConfigurationSchema.safeParse(declaration()).success).toBe( - true, - ); - expect( - platformConfigurationSchema.safeParse(declaration('anthropic')).success, - ).toBe(false); - expect( - platformConfigurationSchema.safeParse(declaration('openai', ['chat'])) - .success, - ).toBe(false); - expect( - platformConfigurationSchema.safeParse( - declaration('openai', ['transcription'], 'missing'), - ).success, - ).toBe(false); - }); - - test('accepts image generation off or automatic and validates a pinned image model', () => { - const declaration = ( - apiFormat = 'openai', - tags = ['image-generation'], - modelId = 'example-image', - ) => ({ - schemaVersion: 1, - resources: [ - { - kind: 'provider', - config: { - name: 'example-images', - displayName: 'Example images', - apiFormat, - baseUrl: 'https://images.example.invalid/v1', - catalog: { source: 'models-endpoint' }, - auth: [{ method: 'api-key' }], - }, - expectedModels: [ - { - id: 'example-image', - provider: 'example-images', - tags, - supportsTools: false, - supportsVision: true, - outputsMedia: true, - contextWindow: 32_000, - }, - ], - }, - { - kind: 'governance', - key: 'image_generation', - config: { enabled: true, providerSlug: 'example-images', modelId }, - }, - ], - }); - for (const config of [{ enabled: false }, { enabled: true }]) { - expect( - platformConfigurationSchema.safeParse({ - schemaVersion: 1, - resources: [{ kind: 'governance', key: 'image_generation', config }], - }).success, - ).toBe(true); - } - expect(platformConfigurationSchema.safeParse(declaration()).success).toBe( - true, - ); - expect( - platformConfigurationSchema.safeParse(declaration('anthropic')).success, - ).toBe(false); - expect( - platformConfigurationSchema.safeParse(declaration('openai', ['chat'])) - .success, - ).toBe(false); - expect( - platformConfigurationSchema.safeParse( - declaration('openai', ['image-generation'], 'missing'), - ).success, - ).toBe(false); - }); - - test('rejects raw credential secrets and unrelated environment variables', () => { - for (const changes of [ - { secret: 'must-never-appear' }, - { envName: 'BETTER_AUTH_SECRET' }, - { authMethod: 'api-key' }, - { status: 'disabled', isDefault: true }, - ]) { - const config = platformConfigurationFixture(); - const credential = config.resources.find( - (entry) => entry.kind === 'provider-credential', - )!; - Object.assign(credential.config, changes); - expect(platformConfigurationSchema.safeParse(config).success).toBe(false); - } - }); - test('deployment configuration needs a native organization and explicit provider env references', () => { const spec = { schemaVersion: 1, @@ -295,145 +73,3 @@ describe('native configuration declaration', () => { ).toBe(false); }); }); - -describe('the embedding floor in a declaration', () => { - const embedding = () => - platformConfigurationFixture().resources.find( - (entry) => entry.kind === 'knowledge-embedding', - )!; - const declare = (config: object) => - platformConfigurationSchema.safeParse({ - schemaVersion: 1, - resources: [{ kind: 'knowledge-embedding', config }], - }); - - test('accepts a number, null (clear) and absence (keep); refuses anything else', () => { - expect( - declare({ ...embedding().config, minSimilarity: 0.55 }).success, - ).toBe(true); - expect( - declare({ ...embedding().config, minSimilarity: null }).success, - ).toBe(true); - expect(declare(embedding().config).success).toBe(true); - expect( - declare({ ...embedding().config, minSimilarity: '0.5' }).success, - ).toBe(false); - expect(declare({ ...embedding().config, minSimilarity: 1.5 }).success).toBe( - false, - ); - }); - - test('accepts the serving limits the same three ways, within the platform’s bounds', () => { - for (const fields of [ - { maxConcurrentRequests: 2, minTokensPerSecond: 750 }, - { maxConcurrentRequests: null, minTokensPerSecond: null }, - { minTokensPerSecond: 1349.5 }, - {}, - ]) - expect( - declare({ ...embedding().config, ...fields }).success, - JSON.stringify(fields), - ).toBe(true); - for (const fields of [ - { maxConcurrentRequests: 0 }, - { maxConcurrentRequests: 65 }, - { maxConcurrentRequests: 1.5 }, - { minTokensPerSecond: 0 }, - { minTokensPerSecond: '750' }, - { maxConcurrentRequest: 2 }, - ]) - expect( - declare({ ...embedding().config, ...fields }).success, - JSON.stringify(fields), - ).toBe(false); - }); - - test('converges per kept setting when a declaration states several', () => { - const resource = (fields: object) => - parsePlatformConfiguration({ - schemaVersion: 1, - resources: [ - { - kind: 'knowledge-embedding', - config: { ...embedding().config, ...fields }, - }, - ], - }).resources[0]!; - const stored = (fields: object) => ({ ...embedding().config, ...fields }); - const limits = { maxConcurrentRequests: 2, minTokensPerSecond: 750 }; - - // Omitted settings accept whatever is stored; stated ones must match. - expect( - resourceConverged( - resource({ maxConcurrentRequests: 2 }), - stored({ ...limits, minSimilarity: 0.5 }), - ), - ).toBe(true); - expect( - resourceConverged( - resource(limits), - stored({ ...limits, minSimilarity: 0.5 }), - ), - ).toBe(true); - expect( - resourceConverged( - resource(limits), - stored({ maxConcurrentRequests: 2, minTokensPerSecond: 500 }), - ), - ).toBe(false); - expect( - resourceConverged(resource(limits), stored({ maxConcurrentRequests: 2 })), - ).toBe(false); - // Null converges only once that setting is gone, whatever else is kept. - expect( - resourceConverged( - resource({ minTokensPerSecond: null, minSimilarity: null }), - stored({ maxConcurrentRequests: 2 }), - ), - ).toBe(true); - expect( - resourceConverged(resource({ minTokensPerSecond: null }), stored(limits)), - ).toBe(false); - expect( - resourceConverged( - resource({ ...limits, minSimilarity: null }), - stored(limits), - ), - ).toBe(true); - }); - - test('converges on the platform’s own terms — omitted keeps, null clears, a number matches exactly', () => { - const resource = (minSimilarity?: number | null) => - parsePlatformConfiguration({ - schemaVersion: 1, - resources: [ - { - kind: 'knowledge-embedding', - config: { - ...embedding().config, - ...(minSimilarity === undefined ? {} : { minSimilarity }), - }, - }, - ], - }).resources[0]!; - const stored = (minSimilarity?: number) => ({ - ...embedding().config, - ...(minSimilarity === undefined ? {} : { minSimilarity }), - }); - // Omitted: whatever is stored is fine. - expect(resourceConverged(resource(), stored())).toBe(true); - expect(resourceConverged(resource(), stored(0.55))).toBe(true); - // Null: converged only once nothing is stored. - expect(resourceConverged(resource(null), stored())).toBe(true); - expect(resourceConverged(resource(null), stored(0.55))).toBe(false); - // A number: exact. - expect(resourceConverged(resource(0.6), stored(0.6))).toBe(true); - expect(resourceConverged(resource(0.6), stored(0.55))).toBe(false); - expect(resourceConverged(resource(0.6), stored())).toBe(false); - // Nothing stored at all, and a different model: never converged. - expect(resourceConverged(resource(), null)).toBe(false); - expect( - resourceConverged(resource(), { ...stored(), model: 'Other-model' }), - ).toBe(false); - }); -}); diff --git a/tools/cli/src/lib/config/platform-model.ts b/tools/cli/src/lib/config/platform-model.ts index 1d5dbddabb..ef437e959c 100644 --- a/tools/cli/src/lib/config/platform-model.ts +++ b/tools/cli/src/lib/config/platform-model.ts @@ -1,312 +1,22 @@ -import { brandingFormSchema } from '@tale/shared/schemas/branding'; -import { deploymentConfigSchema } from '@tale/shared/schemas/deployment'; import { - FILE_POLICY_TYPES, - POLICY_SCHEMAS, -} from '@tale/shared/schemas/governance'; -import { - KNOWLEDGE_EMBEDDING_KEPT_KEYS, - knowledgeEmbeddingWriteSchema, -} from '@tale/shared/schemas/knowledge'; -import { managedPlatformResourceSchema } from '@tale/shared/schemas/managed-configuration'; -import { - modelCatalogFileSchema, - providerDefinitionSchema, - providerEnvironmentCredentialSchema, -} from '@tale/shared/schemas/providers'; + platformConfigurationSchema, + type PlatformConfiguration, +} from '@tale/shared/config/platform-resources'; import { z } from 'zod'; import { usageError } from '../../utils/fail'; -import { valueHash } from './releases/identity'; import { sha } from './releases/model'; -// The platform owns the fields and defaults. This envelope only selects a -// native resource; adding a policy to the platform does not require a CLI copy. -const governance = z - .strictObject({ - kind: z.literal('governance'), - key: z - .enum(FILE_POLICY_TYPES) - .refine( - (key) => !['retention_policy', 'dsar_governance'].includes(key), - 'This policy requires its dedicated native workflow', - ), - config: z.unknown(), - }) - .transform((resource, context) => { - const parsed = POLICY_SCHEMAS[resource.key].safeParse(resource.config); - if (!parsed.success) { - context.addIssue({ - code: 'custom', - message: 'Invalid native policy configuration', - }); - return z.NEVER; - } - return { ...resource, config: parsed.data }; - }); - -export const platformResourceSchema = z.union([ - managedPlatformResourceSchema, - governance, - z.strictObject({ - kind: z.literal('branding'), - config: brandingFormSchema.strict(), - }), - z.strictObject({ - kind: z.literal('deployment'), - config: deploymentConfigSchema, - }), - z.strictObject({ - kind: z.literal('knowledge-embedding'), - // The platform keeps a stored similarity floor or serving limit - // (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, - // `maxTokensPerMinute`, `maxRequestsPerMinute`) when - // a save omits it and clears it only on an explicit null (the Settings - // form never carries them) — so the declaration speaks the same three - // ways: a value sets it, `null` clears it, omitted leaves what is stored. - config: knowledgeEmbeddingWriteSchema.strict(), - }), - z.strictObject({ - kind: z.literal('provider'), - config: providerDefinitionSchema, - expectedModels: modelCatalogFileSchema - .refine((models) => models.length <= 200) - .optional(), - }), - z.strictObject({ - kind: z.literal('provider-credential'), - config: providerEnvironmentCredentialSchema, - }), -]); -export type PlatformResource = z.infer; - -export function resourceId(resource: PlatformResource): string { - switch (resource.kind) { - case 'project-instructions': - return `project-instructions/${resource.config.projectId}`; - case 'agent-instructions': - case 'agent-tools': - return `${resource.kind}/${resource.config.projectId}/${resource.config.agentId}`; - case 'task-instructions': - return `task-instructions/${resource.config.projectId}/${resource.config.taskId}`; - case 'automation-definition': - case 'automation-deployment': - case 'automation-schedule': - return `${resource.kind}/${resource.config.projectId}/${resource.config.name}`; - case 'governance': - return `governance/${resource.key}`; - case 'provider': - return `provider/${resource.config.name}`; - case 'provider-credential': - return `provider-credential/${resource.config.providerSlug}/${encodeURIComponent(resource.config.name)}`; - default: - return resource.kind; - } -} - -const declarationSchema = z - .strictObject({ - schemaVersion: z.literal(1), - resources: z.array(platformResourceSchema).min(1).max(128), - }) - .superRefine((configuration, context) => { - const ids = configuration.resources.map(resourceId); - const fail = (message: string) => - context.addIssue({ code: 'custom', message }); - if (new Set(ids).size !== ids.length) - fail('Duplicate native configuration resource'); - for (const resource of configuration.resources) { - if ( - resource.kind !== 'automation-deployment' && - resource.kind !== 'automation-schedule' - ) - continue; - const definition = configuration.resources.find( - (candidate) => - candidate.kind === 'automation-definition' && - candidate.config.name === resource.config.name && - candidate.config.projectId === resource.config.projectId, - ); - if ( - !definition || - (resource.kind === 'automation-deployment' && - valueHash(definition.config) !== resource.config.definitionSha256) - ) - fail( - 'Managed automation deployment requires its exact declared definition', - ); - if ( - resource.kind === 'automation-schedule' && - !configuration.resources.some( - (candidate) => - candidate.kind === 'automation-deployment' && - candidate.config.name === resource.config.name && - candidate.config.projectId === resource.config.projectId, - ) - ) - fail('Managed schedule requires its declared automation deployment'); - } - const managedNames = configuration.resources - .filter((resource) => resource.kind === 'automation-definition') - .map((resource) => resource.config.name); - if (new Set(managedNames).size !== managedNames.length) - fail( - 'An organization-wide automation cannot have two managed project owners', - ); - const providers = configuration.resources.filter( - (resource) => resource.kind === 'provider', - ); - const defaults = configuration.resources - .filter((resource) => resource.kind === 'provider-credential') - .filter( - (resource) => - resource.config.isDefault && resource.config.status === 'active', - ); - if ( - configuration.resources.some( - (resource) => - resource.kind === 'provider-credential' && - resource.config.isDefault && - resource.config.status !== 'active', - ) - ) - fail('A default credential must be active'); - if ( - new Set(defaults.map((resource) => resource.config.providerSlug)).size !== - defaults.length - ) - fail('A provider cannot have two declared default credentials'); - for (const provider of providers) - if ( - provider.expectedModels?.some( - (model) => model.provider !== provider.config.name, - ) - ) - fail('Expected catalog belongs to another provider'); - for (const resource of configuration.resources) { - if (resource.kind === 'knowledge-embedding') { - const provider = providers.find( - (entry) => entry.config.name === resource.config.providerSlug, - ); - if ( - provider && - (provider.config.embedding !== 'supported' || - (provider.config.baseUrl && - resource.config.baseUrl !== provider.config.baseUrl) || - (provider.expectedModels && - !provider.expectedModels.some( - (model) => - model.id === resource.config.model && - model.tags.includes('embedding'), - ))) - ) - fail( - 'Embedding selection differs from its declared provider and catalog', - ); - } - if (resource.kind === 'governance' && resource.key === 'vision_model') { - const vision = POLICY_SCHEMAS.vision_model.parse(resource.config); - const provider = providers.find( - (entry) => entry.config.name === vision.providerSlug, - ); - if ( - provider?.expectedModels && - !provider.expectedModels.some( - (model) => model.id === vision.modelId && model.supportsVision, - ) - ) - fail('Vision selection differs from its declared catalog'); - } - if ( - resource.kind === 'governance' && - resource.key === 'transcription_model' - ) { - const transcription = POLICY_SCHEMAS.transcription_model.parse( - resource.config, - ); - const provider = providers.find( - (entry) => entry.config.name === transcription.providerSlug, - ); - if ( - provider && - (provider.config.apiFormat !== 'openai' || - (provider.expectedModels && - !provider.expectedModels.some( - (model) => - model.id === transcription.modelId && - model.tags.includes('transcription'), - ))) - ) - fail( - 'Transcription selection differs from its declared provider and catalog', - ); - } - if ( - resource.kind === 'governance' && - resource.key === 'image_generation' - ) { - const image = POLICY_SCHEMAS.image_generation.parse(resource.config); - const provider = providers.find( - (entry) => entry.config.name === image.providerSlug, - ); - // The same admission a turn applies: an OpenAI-format provider, and - // a pinned model its declared catalog lists as an image generator. - if ( - provider && - (provider.config.apiFormat !== 'openai' || - (provider.expectedModels && - !provider.expectedModels.some( - (model) => - model.id === image.modelId && - model.tags.includes('image-generation'), - ))) - ) - fail( - 'Image generation selection differs from its declared provider and catalog', - ); - } - } - }); -export type PlatformConfiguration = z.infer; - -/** Normalization may add native defaults, but must not hide misspelled fields. */ -function discardedKeys(input: unknown, parsed: unknown): boolean { - if (Array.isArray(input)) - return ( - !Array.isArray(parsed) || - input.some((entry, i) => discardedKeys(entry, parsed[i])) - ); - if (input && typeof input === 'object') { - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) - return true; - return Object.entries(input).some( - ([key, value]) => - !Object.hasOwn(parsed, key) || - discardedKeys(value, Reflect.get(parsed, key)), - ); - } - return false; -} - -export const platformConfigurationSchema = z - .unknown() - .transform((input, context) => { - const parsed = declarationSchema.safeParse(input); - if (!parsed.success || discardedKeys(input, parsed.data)) { - context.addIssue({ - code: 'custom', - message: 'Unsupported resources or invalid native configuration fields', - }); - return z.NEVER; - } - return parsed.data; - }); - +/** The native resource model (schema, identity, declaration rules, + * convergence) is shared with the platform in + * `@tale/shared/config/platform-resources`; what stays here is the CLI's own: + * its usage error and the plan file it saves for review. */ export function parsePlatformConfiguration( input: unknown, ): PlatformConfiguration { + // The shared schema already refuses a field that parsing would discard. const parsed = platformConfigurationSchema.safeParse(input); - if (!parsed.success || discardedKeys(input, parsed.data)) + if (!parsed.success) throw usageError( 'Platform configuration contains unsupported resources or invalid native fields.', ); @@ -342,80 +52,3 @@ export const configurationPlanSchema = z.strictObject({ .max(128), }); export type ConfigurationPlan = z.infer; -export const sameConfiguration = (left: unknown, right: unknown) => - valueHash(left) === valueHash(right); - -function isObject(value: unknown): value is object { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} - -const keptSettings: readonly string[] = KNOWLEDGE_EMBEDDING_KEPT_KEYS; - -/** An embedding config without the settings a write keeps when it omits - * them: what remains names the model — provider, credential, tag, width and - * endpoint. */ -function embeddingModelOf(value: object): Record { - return Object.fromEntries( - Object.entries(value).filter(([key]) => !keptSettings.includes(key)), - ); -} - -/** Whether a declared embedding names the model already stored, so that it - * changes at most the kept settings — the similarity floor and the serving - * limits, none of which touches the vector space. */ -export function sameEmbeddingModel(declared: object, current: unknown) { - return ( - isObject(current) && - valueHash(embeddingModelOf(declared)) === - valueHash(embeddingModelOf(current)) - ); -} - -/** - * Whether the native state already IS what the declaration asks for — the - * one comparison plan, apply and readback all use, so a resource whose - * write semantics are not "replace the whole object" converges on the - * platform's own terms rather than never at all. - * - * Every resource compares whole, except the embedding's kept settings - * (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, - * `maxTokensPerMinute`, `maxRequestsPerMinute`): the - * platform keeps a stored one when the write omits it and clears it on an - * explicit null, so a declaration that omits one converges with ANY stored - * value, one that declares `null` converges only once none is stored, and a - * declared value must match exactly — each setting on its own. - */ -export function resourceConverged( - resource: PlatformResource, - current: unknown, -): boolean { - return resourceConvergedWithHash( - resource, - current, - valueHash(resource.config), - ); -} - -/** A retained plan holds the declaration hash, not its original secret-free - * object. Compare that hash with precisely the declarations native readback - * satisfies, including the kept settings' preserve/clear semantics. */ -export function resourceConvergedWithHash( - resource: PlatformResource, - current: unknown, - desiredSha256: string, -): boolean { - if (resource.kind !== 'knowledge-embedding' || !isObject(current)) - return valueHash(current) === desiredSha256; - // Every declaration this state satisfies: each kept setting either - // omitted (whatever is stored stays) or stated as what is stored — `null` - // when nothing is. - let readings = [embeddingModelOf(current)]; - for (const key of keptSettings) { - const stored: unknown = Reflect.get(current, key); - readings = readings.flatMap((reading) => [ - reading, - { ...reading, [key]: stored ?? null }, - ]); - } - return readings.some((reading) => valueHash(reading) === desiredSha256); -} diff --git a/tools/cli/src/lib/config/platform-resources.ts b/tools/cli/src/lib/config/platform-resources.ts index dc76f46da2..f68fa8f058 100644 --- a/tools/cli/src/lib/config/platform-resources.ts +++ b/tools/cli/src/lib/config/platform-resources.ts @@ -1,3 +1,10 @@ +import { + resourceConverged, + resourceId, + sameConfiguration, + sameEmbeddingModel, + type PlatformResource, +} from '@tale/shared/config/platform-resources'; import { brandingFormSchema } from '@tale/shared/schemas/branding'; import { expectedConfigurationHashSchema } from '@tale/shared/schemas/configuration'; import { deploymentConfigSchema } from '@tale/shared/schemas/deployment'; @@ -18,13 +25,6 @@ import { writeManagedResource, } from './managed-resources'; import type { PlatformConfigurationClient } from './platform-client'; -import { - resourceConverged, - resourceId, - sameConfiguration, - sameEmbeddingModel, - type PlatformResource, -} from './platform-model'; export interface ResourceObservation { config: unknown; diff --git a/tools/cli/src/lib/deployment/apply.test.ts b/tools/cli/src/lib/deployment/apply.test.ts index d3be09a13c..31908feb66 100644 --- a/tools/cli/src/lib/deployment/apply.test.ts +++ b/tools/cli/src/lib/deployment/apply.test.ts @@ -10,10 +10,11 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { relative } from 'node:path'; +import { resourceId } from '@tale/shared/config/platform-resources'; + +import { platformConfigurationFixture } from '../../../../../packages/shared/src/config/platform-resources.fixture'; import { CliError, ExitCode } from '../../utils/fail'; import * as logger from '../../utils/logger'; -import { platformConfigurationFixture } from '../config/platform-fixture'; -import { resourceId } from '../config/platform-model'; import { sha256, valueHash, loadClient } from '../config/releases/identity'; import { loadRelease } from '../config/releases/manifest'; import { commandFixture } from '../config/releases/tests/command-fixture'; diff --git a/tools/cli/src/lib/deployment/configuration.ts b/tools/cli/src/lib/deployment/configuration.ts index 0c6847a497..2fa2b538c4 100644 --- a/tools/cli/src/lib/deployment/configuration.ts +++ b/tools/cli/src/lib/deployment/configuration.ts @@ -1,6 +1,10 @@ import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; +import { + resourceId, + type PlatformConfiguration, +} from '@tale/shared/config/platform-resources'; import { z } from 'zod'; import { preconditionError, externalDepError } from '../../utils/fail'; @@ -13,8 +17,6 @@ import { configurationClient } from '../config/platform-client'; import { configurationPlanSchema, configurationTargetSchema, - resourceId, - type PlatformConfiguration, } from '../config/platform-model'; import { sha256, valueHash } from '../config/releases/identity'; import { sha } from '../config/releases/model'; diff --git a/tools/cli/src/lib/deployment/model.ts b/tools/cli/src/lib/deployment/model.ts index dc0159af10..0acf30062d 100644 --- a/tools/cli/src/lib/deployment/model.ts +++ b/tools/cli/src/lib/deployment/model.ts @@ -1,12 +1,12 @@ import { isAbsolute, resolve } from 'node:path'; +import { platformConfigurationSchema } from '@tale/shared/config/platform-resources'; import { PROJECT_NAME_MAX } from '@tale/shared/schemas/projects'; import { isValidProjectKey } from '@tale/shared/utils/project-key'; import { z } from 'zod'; import { preconditionError } from '../../utils/fail'; import { validateAdditionalSiteUrls } from '../config/ensure-env'; -import { platformConfigurationSchema } from '../config/platform-model'; import { gitSha, owner, From e19d0328aab0952aa6189316cd2ac2c571f45c4e Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:16:50 +0200 Subject: [PATCH 04/35] feat(shared): describe the settings kinds a coding agent can change `@tale/shared/schemas/settings-kinds` describes, once for the platform, the docs and the CLI, the settings the MCP settings tools take: one descriptor per kind with its scope, the Settings pages where a person makes the same change, its operations and one-shot acts, the pointers of its secret values, its base risk, its place in the apply order and an agent-facing description. It starts with the kinds a declaration already names (providers and their environment credentials, governance policies, the knowledge embedding, branding, the deployment and a project's managed instructions and tools); the automation kinds stay with the automation tools, each with the reason. It also names every page of Settings by its path, the join key the platform's coverage guard holds to the settings rail, and the effects a planned change can carry with the risk each adds. The suite holds the kinds marked cli to the CLI's resource union, both at compile time and as parsed, so the CLI never declares a kind the platform does not describe; orders, areas and secret pointers are checked as well. --- packages/shared/README.md | 6 + packages/shared/package.json | 1 + .../shared/src/schemas/settings-kinds.test.ts | 156 +++++++++ packages/shared/src/schemas/settings-kinds.ts | 323 ++++++++++++++++++ 4 files changed, 486 insertions(+) create mode 100644 packages/shared/src/schemas/settings-kinds.test.ts create mode 100644 packages/shared/src/schemas/settings-kinds.ts diff --git a/packages/shared/README.md b/packages/shared/README.md index b742413b2b..b3955ee5fb 100644 --- a/packages/shared/README.md +++ b/packages/shared/README.md @@ -33,6 +33,12 @@ Every subpath below is declared in `package.json` `exports`. (`platformConfigurationSchema`) and when stored state already is what was asked for (`resourceConverged`). Server-only: it compares `configurationHash` digests, so it sits outside the browser-safe `schemas/`. +- **`@tale/shared/schemas/settings-kinds`** — the settings a coding agent reads + and changes through the MCP settings tools: one descriptor per kind + (`SETTINGS_KINDS`: scope, the Settings pages it covers, operations, secret + paths, risk, apply order, description), the declarable kinds those tools + leave to the automation tools, every page of Settings (`SETTINGS_AREAS`) and + the effects a planned change can carry (`SETTINGS_EFFECTS`). - **`@tale/shared/schemas/{automation-pack,automation-settings,task-contract}`** — automation package declarations and limits, operator settings forms and task bindings. Catalog reads, ZIP decoding and engine validation stay in the platform. diff --git a/packages/shared/package.json b/packages/shared/package.json index 9eb14f3370..de9bacfef0 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -27,6 +27,7 @@ "./schemas/providers": "./src/schemas/providers.ts", "./schemas/configuration": "./src/schemas/configuration.ts", "./config/platform-resources": "./src/config/platform-resources.ts", + "./schemas/settings-kinds": "./src/schemas/settings-kinds.ts", "./schemas/managed-configuration": "./src/schemas/managed-configuration.ts", "./schemas/connectors": "./src/schemas/connectors.ts", "./schemas/epoch-ms": "./src/schemas/epoch-ms.ts", diff --git a/packages/shared/src/schemas/settings-kinds.test.ts b/packages/shared/src/schemas/settings-kinds.test.ts new file mode 100644 index 0000000000..4f1923da3c --- /dev/null +++ b/packages/shared/src/schemas/settings-kinds.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, test } from 'vitest'; +import { z } from 'zod'; + +import { + platformResourceSchema, + type PlatformResource, +} from '../config/platform-resources'; +import { + isSettingsKind, + isSettingsPointer, + SETTINGS_AREAS, + SETTINGS_EFFECTS, + SETTINGS_KINDS, + SETTINGS_KINDS_NOT_OVER_MCP, + settingsKindDescriptor, + type SettingsKindDescriptor, +} from './settings-kinds'; + +/** The descriptors as any reader sees them, not as their literal types. */ +const DESCRIPTORS: readonly SettingsKindDescriptor[] = SETTINGS_KINDS; + +/** Every kind the CLI's resource union takes, as a compile-time list: a kind + * added to the union without a line here fails the type check. */ +const DECLARABLE: Record = { + 'project-instructions': true, + 'agent-instructions': true, + 'agent-tools': true, + 'task-instructions': true, + 'automation-definition': true, + 'automation-deployment': true, + 'automation-schedule': true, + governance: true, + branding: true, + deployment: true, + 'knowledge-embedding': true, + provider: true, + 'provider-credential': true, +}; + +/** The same set read from the schema at run time: every `kind` constant of + * the union, however deep its members nest. */ +function parsedKinds(): string[] { + const kinds: string[] = []; + const visit = (node: unknown): void => { + if (typeof node !== 'object' || node === null) return; + const kind: unknown = Reflect.get( + Reflect.get(Reflect.get(node, 'properties') ?? {}, 'kind') ?? {}, + 'const', + ); + if (typeof kind === 'string') kinds.push(kind); + for (const key of ['anyOf', 'oneOf']) { + const members: unknown = Reflect.get(node, key); + if (Array.isArray(members)) members.forEach(visit); + } + }; + visit( + z.toJSONSchema(platformResourceSchema, { + io: 'input', + unrepresentable: 'any', + }), + ); + return kinds; +} + +describe('the settings kinds', () => { + test('the CLI declares exactly the kinds marked cli, taken over MCP or not', () => { + const marked = [ + ...SETTINGS_KINDS.filter((descriptor) => descriptor.cli), + ...SETTINGS_KINDS_NOT_OVER_MCP.filter((entry) => entry.cli), + ] + .map((entry) => entry.kind) + .sort(); + expect(parsedKinds().sort()).toEqual(marked); + expect(Object.keys(DECLARABLE).sort()).toEqual(marked); + }); + + test('a kind the MCP tools do not take says why, and is not also taken', () => { + const taken = new Set(SETTINGS_KINDS.map((entry) => entry.kind)); + for (const entry of SETTINGS_KINDS_NOT_OVER_MCP) { + expect(taken.has(entry.kind), entry.kind).toBe(false); + expect(entry.reason, entry.kind).toMatch(/^\S.*\.$/); + } + }); + + test('each kind is described once, with an order of its own', () => { + const kinds = SETTINGS_KINDS.map((entry) => entry.kind); + expect(new Set(kinds).size).toBe(kinds.length); + const orders = SETTINGS_KINDS.map((entry) => entry.order); + expect(new Set(orders).size).toBe(orders.length); + // The list reads in the order changes apply. + expect([...orders].sort((a, b) => a - b)).toEqual(orders); + }); + + test('what a resource refers to applies before it', () => { + const order = (kind: Parameters[0]) => + settingsKindDescriptor(kind).order; + // A credential names its provider; a model policy and the embedding + // name a provider and are served through its credential. + expect(order('provider')).toBeLessThan(order('provider-credential')); + expect(order('provider-credential')).toBeLessThan(order('governance')); + expect(order('provider-credential')).toBeLessThan( + order('knowledge-embedding'), + ); + }); + + test('each kind names pages of Settings, real operations and pointers below its config', () => { + const areas = new Set(SETTINGS_AREAS); + expect(areas.size).toBe(SETTINGS_AREAS.length); + for (const descriptor of DESCRIPTORS) { + for (const area of descriptor.areas) { + expect(areas.has(area), `${descriptor.kind}: ${area}`).toBe(true); + } + expect(descriptor.ops.length, descriptor.kind).toBeGreaterThan(0); + for (const act of descriptor.acts) { + expect(act, descriptor.kind).toMatch(/^[a-z]+(?:-[a-z]+)*$/); + } + for (const pointer of descriptor.secretPaths) { + expect( + isSettingsPointer(pointer), + `${descriptor.kind}: ${pointer}`, + ).toBe(true); + } + expect(descriptor.description, descriptor.kind).toMatch(/^\S.*\.$/); + } + }); + + test('a secret path is an RFC 6901 pointer below the config, * for any member', () => { + // `/` names the member whose key is the empty string, as RFC 6901 reads it. + for (const pointer of [ + '/secret', + '/endpoint/headers/*', + '/a~1b', + '/a~0', + '/0', + '/', + ]) + expect(isSettingsPointer(pointer), pointer).toBe(true); + // The whole config, a bare name and a broken escape are not. + for (const pointer of ['', 'secret', 'a/b', '/a~2', '/a~']) + expect(isSettingsPointer(pointer), pointer).toBe(false); + }); + + test('every effect raises a change to high or critical', () => { + for (const [effect, risk] of Object.entries(SETTINGS_EFFECTS)) { + expect(['high', 'critical'], effect).toContain(risk); + expect(effect).toMatch(/^[a-z]+(?:-[a-z]+)*$/); + } + }); + + test('names a kind only when the MCP tools take it', () => { + expect(isSettingsKind('governance')).toBe(true); + expect(isSettingsKind('automation-definition')).toBe(false); + expect(isSettingsKind('file')).toBe(false); + expect(settingsKindDescriptor('branding').scope).toBe('organization'); + }); +}); diff --git a/packages/shared/src/schemas/settings-kinds.ts b/packages/shared/src/schemas/settings-kinds.ts new file mode 100644 index 0000000000..98c4d7bab0 --- /dev/null +++ b/packages/shared/src/schemas/settings-kinds.ts @@ -0,0 +1,323 @@ +/** + * The settings a coding agent reads and changes through Tale's MCP settings + * tools, described once for every reader: the platform's settings registry + * routes a change by its kind and applies changes in each kind's `order`, + * the endpoint's reference teaches each kind from its `description`, and the + * coverage guard joins every page of Settings to the kinds that cover it + * through `areas`. The CLI declares the kinds marked `cli`; the guard in + * `settings-kinds.test.ts` holds them to the native resource model the CLI + * parses, so the CLI never accepts a kind the platform does not describe. + * + * Pure data: the browser reads it as well as the server. + */ + +/** + * Every page of Settings, by its path under + * `/dashboard//settings/`; a section with tabs is named by each + * of its tabs. The platform's coverage guard holds this list equal to the + * settings rail, so a page cannot be added without its story here. + */ +export const SETTINGS_AREAS = [ + 'account', + 'personalization', + 'notifications', + 'usage', + 'organization', + 'teams', + 'members', + 'providers', + 'connectors', + 'skills', + 'branding', + 'sandboxes', + 'governance/content-models', + 'governance/policies-limits', + 'governance/security-monitoring', + 'governance/competences', + 'governance/guardrails', + 'governance/logs', + 'governance/legal-hold', + 'governance/data-subject-requests', + 'governance/trash', + 'metrics/usage', + 'metrics/feedback', + 'metrics/chat-health', + 'metrics/external-turns', + 'metrics/automations', + 'metrics/projects', + 'api/rest', + 'api/models', + 'api/mcp', + 'api/webdav', + 'enterprise-sso', + 'data-residency', +] as const; +export type SettingsArea = (typeof SETTINGS_AREAS)[number]; + +/** Whose setting it is: the organization's, one person's, the deployment's + * (every organization on it), or one project's. */ +export type SettingsScope = 'organization' | 'user' | 'instance' | 'project'; + +/** What a change does to one resource: `set` replaces it whole (creating it + * when absent), `delete` removes it. One-shot actions are the kind's `acts`. */ +export type SettingsOp = 'set' | 'delete'; + +export type SettingsRisk = 'low' | 'high' | 'critical'; + +/** + * What a planned change does beyond replacing a value, each with the risk it + * carries. A change's risk is the highest of its kind's `baseRisk` and its + * effects'. The codes are a stable vocabulary: the agent reads them in a + * plan, and Tale shows them, translated, to the person who finishes a + * change. + */ +export const SETTINGS_EFFECTS = { + 'signs-out-members': 'critical', + 'may-lock-out-members': 'critical', + 'removes-human-approval': 'critical', + 'changes-serving-account': 'high', + 'breaks-dependents': 'high', + 'requires-empty-corpus': 'critical', + 're-embeds-documents': 'critical', + 'restart-required': 'critical', + 'sends-email': 'high', + 'revokes-access': 'high', + irreversible: 'critical', + 'erases-personal-data': 'critical', + 'staged-cooldown': 'critical', + 'reaches-vendor': 'high', + 'ends-running-work': 'high', +} as const satisfies Record>; +export type SettingsEffect = keyof typeof SETTINGS_EFFECTS; + +export interface SettingsKindDescriptor { + readonly kind: string; + readonly scope: SettingsScope; + /** The pages of Settings where a person makes the same change — the + * coverage guard's join key, and where Tale sends a person to finish one. + * Empty for a kind no Settings page edits (a project's own pages do). */ + readonly areas: readonly SettingsArea[]; + /** Whether `tale config platform` and managed deployments declare it. */ + readonly cli: boolean; + readonly ops: readonly SettingsOp[]; + /** One-shot actions on an existing resource, each named in kebab case. */ + readonly acts: readonly string[]; + /** RFC 6901 pointers into the resource's config whose value is a secret: + * masked on every read, refused on every write. A `*` token stands for + * any member or index. */ + readonly secretPaths: readonly string[]; + readonly baseRisk: SettingsRisk; + /** Where its changes run among a batch's: a lower order applies first, + * so what a resource refers to exists before it. Unique per kind. */ + readonly order: number; + /** What it is, in agent-facing English: the settings reference + * (`tale://docs/settings`) is built from it. */ + readonly description: string; +} + +/** + * The kinds the MCP settings tools take, in apply order. A resource's `id` + * is its identity within its kind, as a declaration names it; a kind with + * one resource per organization or deployment has none. + */ +export const SETTINGS_KINDS = [ + { + kind: 'provider', + scope: 'organization', + areas: ['providers'], + cli: true, + ops: ['set', 'delete'], + acts: ['refresh-catalogs'], + secretPaths: [], + baseRisk: 'high', + order: 10, + description: + 'An AI provider: its endpoint, API format, model catalog source and the ways its credentials may authenticate. id is the provider name.', + }, + { + kind: 'provider-credential', + scope: 'organization', + areas: ['providers'], + cli: true, + ops: ['set', 'delete'], + acts: [], + secretPaths: [], + baseRisk: 'high', + order: 20, + description: + "A credential a provider's requests authenticate with, read from an environment variable of the deployment (authMethod env): its models, its status and whether it is the provider's default. id is /, the name URI-encoded. An API key or a subscription is entered in Tale, never here.", + }, + { + kind: 'governance', + scope: 'organization', + areas: [ + 'governance/content-models', + 'governance/policies-limits', + 'governance/security-monitoring', + 'governance/guardrails', + 'sandboxes', + 'api/models', + 'enterprise-sso', + ], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'high', + order: 30, + description: + 'One organization policy, named by its key (the id), e.g. password_policy, budgets or default_models: models and model access, budgets and limits, sign-in and session security, guardrails, sandbox quotas. The retention policy and the data subject request policy change only through their own staged workflows in Tale.', + }, + { + kind: 'knowledge-embedding', + scope: 'organization', + areas: ['data-residency'], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'critical', + order: 40, + description: + "The model that turns the organization's documents and crawled pages into vectors. Changing the model needs an empty knowledge base; its similarity floor and serving limits change at any time. One per organization.", + }, + { + kind: 'branding', + scope: 'organization', + areas: ['branding'], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'low', + order: 50, + description: + "The organization's accent colour and the file names of its logo and favicons; the images themselves are uploaded in Tale. One per organization.", + }, + { + kind: 'project-instructions', + scope: 'project', + areas: [], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'high', + order: 60, + description: + "A project's standing instructions, which every agent working in it follows. id is the project id.", + }, + { + kind: 'agent-instructions', + scope: 'project', + areas: [], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'high', + order: 61, + description: "A project agent's instructions. id is /.", + }, + { + kind: 'agent-tools', + scope: 'project', + areas: [], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'high', + order: 62, + description: + 'The tools a project agent may use. id is /.', + }, + { + kind: 'task-instructions', + scope: 'project', + areas: [], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'high', + order: 63, + description: + "A standing task's description, which its agent works from. id is /.", + }, + { + kind: 'deployment', + scope: 'instance', + areas: [], + cli: true, + ops: ['set'], + acts: [], + secretPaths: [], + baseRisk: 'critical', + order: 70, + description: + "This Tale deployment's own settings, shared by every organization on it, such as the sandbox runtime. Only the people its operator allows may change them, and some take effect after a restart. One per deployment.", + }, +] as const satisfies readonly SettingsKindDescriptor[]; + +export type SettingsKind = (typeof SETTINGS_KINDS)[number]['kind']; + +/** + * Kinds a declaration names that the MCP settings tools do not take, each + * with the reason: the automation tools make the same change with richer + * feedback, and one concept has one way in. + */ +export const SETTINGS_KINDS_NOT_OVER_MCP = [ + { + kind: 'automation-definition', + cli: true, + reason: + 'save_automation saves the document as a new version, with its validation, tests and warnings.', + }, + { + kind: 'automation-deployment', + cli: true, + reason: + 'deploy_automation puts a saved version live, behind its tests and the version it expects to replace.', + }, + { + kind: 'automation-schedule', + cli: true, + reason: + 'set_trigger binds what starts an automation, a schedule among them.', + }, +] as const satisfies ReadonlyArray<{ + kind: string; + cli: boolean; + reason: string; +}>; + +const BY_KIND: ReadonlyMap = new Map( + SETTINGS_KINDS.map((descriptor) => [descriptor.kind, descriptor]), +); + +/** Whether the MCP settings tools take this kind. */ +export function isSettingsKind(name: string): name is SettingsKind { + return BY_KIND.has(name); +} + +/** The descriptor of a kind the MCP settings tools take. */ +export function settingsKindDescriptor( + kind: SettingsKind, +): SettingsKindDescriptor { + const descriptor = BY_KIND.get(kind); + if (descriptor === undefined) { + throw new Error(`No settings kind "${kind}"`); + } + return descriptor; +} + +/** One reference token of a pointer: any character but `~` and `/`, or + * those two escaped (`~0`, `~1`). */ +const POINTER = /^(?:\/(?:[^~/]|~[01])*)+$/; + +/** Whether a `secretPaths` entry is a well-formed RFC 6901 pointer below the + * config (never the whole config, which would leave nothing to read). */ +export function isSettingsPointer(pointer: string): boolean { + return POINTER.test(pointer); +} From 1862b7dc58dbf74c4488deed97e3e2b924ce2977 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:25:41 +0200 Subject: [PATCH 05/35] refactor(platform): lift the engine's credential detector into lib/shared The detector behind `SECRET_IN_DOCUMENT` (known credential shapes, and an opaque word under a member named like a credential) moves out of the engine's document validator into `lib/shared/secret-scan.ts`, so the MCP settings tools can refuse a key pasted into a setting the same way the engine refuses one pasted into an automation. `findSecrets` answers every hit with its dotted path, its pointer and the kind of credential, never the value; the validator still reports the first five. The module is pure, and the engine purity guard scans it and allows it as a sanctioned helper. No behaviour changes: the validator's own suites pass unchanged, and the new suite pins each shape, the member-name rule, the locations and that no hit carries a value. --- .../lib/engine/core/validate/document.ts | 66 +------------ .../lib/engine/selftest/purity.test.ts | 8 +- .../platform/lib/shared/secret-scan.test.ts | 80 ++++++++++++++++ services/platform/lib/shared/secret-scan.ts | 95 +++++++++++++++++++ 4 files changed, 182 insertions(+), 67 deletions(-) create mode 100644 services/platform/lib/shared/secret-scan.test.ts create mode 100644 services/platform/lib/shared/secret-scan.ts diff --git a/services/platform/lib/engine/core/validate/document.ts b/services/platform/lib/engine/core/validate/document.ts index 067092791f..8c79120133 100644 --- a/services/platform/lib/engine/core/validate/document.ts +++ b/services/platform/lib/engine/core/validate/document.ts @@ -11,6 +11,7 @@ import type { ValidateFunction } from 'ajv'; +import { findSecrets } from '../../../shared/secret-scan'; import { isRecord } from '../../../utils/type-utils'; import { err, warn } from '../errors'; import { ptr } from '../syntax/pointer'; @@ -29,22 +30,6 @@ const TOP_FIELDS = [ 'ui', ]; -const SECRET_PATTERNS: ReadonlyArray = [ - [/\bsk-[A-Za-z0-9_-]{16,}/, 'API key (sk-…)'], - [/\bAKIA[0-9A-Z]{12,}/, 'AWS access key'], - [/\bxox[bap]-[A-Za-z0-9-]{10,}/, 'Slack token'], - [/\bghp_[A-Za-z0-9]{20,}/, 'GitHub token'], - [/-----BEGIN [A-Z ]*PRIVATE KEY-----/, 'private key material'], - [/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/, 'bearer token'], -]; - -/** Key names that mark their value as a credential when it looks opaque. */ -const CREDENTIAL_KEY_RE = - /^(?:api[_-]?key|apikey|secret|token|access[_-]?key|password|passwd|authorization|auth[_-]?token)$/i; - -/** A long single opaque word — no spaces, no template braces. */ -const OPAQUE_VALUE_RE = /^[A-Za-z0-9+/=_.-]{16,}$/; - export function validateDocument( doc: Record, issues: Issue[], @@ -244,54 +229,7 @@ function checkTestInput( } function scanForSecrets(doc: Record, issues: Issue[]): void { - const hits: Array<{ path: string; pointer: string; label: string }> = []; - - const scanString = ( - value: string, - path: string, - pointer: string, - key?: string, - ): void => { - for (const [re, label] of SECRET_PATTERNS) { - if (re.test(value)) { - hits.push({ path, pointer, label }); - return; - } - } - if ( - key !== undefined && - CREDENTIAL_KEY_RE.test(key) && - OPAQUE_VALUE_RE.test(value) - ) { - hits.push({ - path, - pointer, - label: `credential-looking value under "${key}"`, - }); - } - }; - - const walk = ( - value: unknown, - path: string, - pointer: string, - key?: string, - ): void => { - if (typeof value === 'string') { - scanString(value, path, pointer, key); - } else if (Array.isArray(value)) { - for (const [i, item] of value.entries()) { - walk(item, `${path}[${i}]`, pointer + ptr(i)); - } - } else if (isRecord(value)) { - for (const [k, item] of Object.entries(value)) { - walk(item, path === '' ? k : `${path}.${k}`, pointer + ptr(k), k); - } - } - }; - walk(doc, '', ''); - - for (const { path, pointer, label } of hits.slice(0, 5)) { + for (const { path, pointer, label } of findSecrets(doc).slice(0, 5)) { issues.push( err( 'SECRET_IN_DOCUMENT', diff --git a/services/platform/lib/engine/selftest/purity.test.ts b/services/platform/lib/engine/selftest/purity.test.ts index 3bdadbb5da..f23585236c 100644 --- a/services/platform/lib/engine/selftest/purity.test.ts +++ b/services/platform/lib/engine/selftest/purity.test.ts @@ -29,6 +29,7 @@ const PURE_SHARED_HELPERS = [ '../../../../packages/shared/src/automation-name.ts', ), path.resolve(ENGINE_ROOT, '../shared/utils/stable-stringify.ts'), + path.resolve(ENGINE_ROOT, '../shared/secret-scan.ts'), path.resolve( ENGINE_ROOT, '../../../../packages/shared/src/utils/stable-stringify.ts', @@ -82,9 +83,9 @@ describe('engine purity', () => { it('pure layers reach outside the engine only for sanctioned pure helpers', () => { // ajv (schema validation), the parser stack (acorn, its ESTree types, // periscopic scopes, the zimmerframe walker, is-reference), the shared - // safe YAML loader, type guards, name grammar and stable serializer are - // runtime-neutral; everything else outside the engine tree is a layering - // violation. + // safe YAML loader, type guards, name grammar, stable serializer and + // credential detector are runtime-neutral; everything else outside the + // engine tree is a layering violation. const allowedPackages = new Set([ 'ajv', '@tale/shared/automation-name', @@ -99,6 +100,7 @@ describe('engine purity', () => { path.join('lib', 'shared', 'config', 'yaml'), path.join('lib', 'utils', 'type-utils'), path.join('lib', 'shared', 'utils', 'stable-stringify'), + path.join('lib', 'shared', 'secret-scan'), ]; const offenders: string[] = []; for (const f of files) { diff --git a/services/platform/lib/shared/secret-scan.test.ts b/services/platform/lib/shared/secret-scan.test.ts new file mode 100644 index 0000000000..514f16e237 --- /dev/null +++ b/services/platform/lib/shared/secret-scan.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; + +import { findSecrets } from './secret-scan'; + +/** Obviously fake credentials, one per shape the detector knows (the key + * header is assembled so no scanner reads this file as holding one). */ +const FAKE = { + openai: 'sk-000000000000000000000000', + aws: 'AKIA0000000000000000', + slack: 'xoxb-0000000000-0000000000', + github: 'ghp_000000000000000000000000', + key: ['-----BEGIN', 'RSA PRIVATE KEY-----'].join(' '), + bearer: 'Bearer 000000000000000000000000', +}; + +describe('findSecrets', () => { + it('names the kind of every known credential shape, wherever it sits in a string', () => { + expect( + Object.values(FAKE).map((value) => findSecrets(`note: ${value} end`)), + ).toEqual([ + [{ path: '', pointer: '', label: 'API key (sk-…)' }], + [{ path: '', pointer: '', label: 'AWS access key' }], + [{ path: '', pointer: '', label: 'Slack token' }], + [{ path: '', pointer: '', label: 'GitHub token' }], + [{ path: '', pointer: '', label: 'private key material' }], + [{ path: '', pointer: '', label: 'bearer token' }], + ]); + }); + + it('reads an opaque word as a credential only under a member named like one', () => { + const opaque = 'Zm9vYmFyYmF6cXV4cXV1eA'; + expect(findSecrets({ apiKey: opaque, password: opaque })).toEqual([ + { + path: 'apiKey', + pointer: '/apiKey', + label: 'credential-looking value under "apiKey"', + }, + { + path: 'password', + pointer: '/password', + label: 'credential-looking value under "password"', + }, + ]); + // The same word under another name, in a list, or with spaces is not. + expect( + findSecrets({ + description: opaque, + token: [opaque], + secret: 'two words here and more', + authorization: 'Bearer {{secret.moderation}}', + }), + ).toEqual([]); + }); + + it('locates a hit by dotted path and by escaped pointer', () => { + expect( + findSecrets({ + nodes: [{ config: { 'a/b~c': FAKE.github } }], + }), + ).toEqual([ + { + path: 'nodes[0].config.a/b~c', + pointer: '/nodes/0/config/a~1b~0c', + label: 'GitHub token', + }, + ]); + }); + + it('never carries the value it found', () => { + const hits = findSecrets({ a: FAKE.openai, b: [FAKE.aws] }); + expect(hits).toHaveLength(2); + expect(JSON.stringify(hits)).not.toContain(FAKE.openai); + expect(JSON.stringify(hits)).not.toContain(FAKE.aws); + }); + + it('counts one hit per string, and none in a value with no strings', () => { + expect(findSecrets(`${FAKE.openai} ${FAKE.bearer}`)).toHaveLength(1); + expect(findSecrets({ n: 1, ok: true, none: null })).toEqual([]); + }); +}); diff --git a/services/platform/lib/shared/secret-scan.ts b/services/platform/lib/shared/secret-scan.ts new file mode 100644 index 0000000000..87881d5554 --- /dev/null +++ b/services/platform/lib/shared/secret-scan.ts @@ -0,0 +1,95 @@ +/** + * Credentials pasted where none belongs: the one detector the automation + * engine refuses a document with (`SECRET_IN_DOCUMENT`) and the MCP settings + * tools refuse a change with (`SECRET_ARGUMENT_REFUSED`), so a key a person + * or an agent pastes into a field is caught the same way on both doors. + * + * Pure and runtime-neutral (the engine's purity guard scans it): no I/O, no + * host APIs. A hit names the KIND of credential and where it sits, never + * the value. + */ + +import { isRecord } from '../utils/type-utils'; + +/** Shapes that are a credential wherever they appear, with the label a + * refusal names. */ +const SECRET_PATTERNS: ReadonlyArray = [ + [/\bsk-[A-Za-z0-9_-]{16,}/, 'API key (sk-…)'], + [/\bAKIA[0-9A-Z]{12,}/, 'AWS access key'], + [/\bxox[bap]-[A-Za-z0-9-]{10,}/, 'Slack token'], + [/\bghp_[A-Za-z0-9]{20,}/, 'GitHub token'], + [/-----BEGIN [A-Z ]*PRIVATE KEY-----/, 'private key material'], + [/\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/, 'bearer token'], +]; + +/** Key names that mark their value as a credential when it looks opaque. */ +const CREDENTIAL_KEY_RE = + /^(?:api[_-]?key|apikey|secret|token|access[_-]?key|password|passwd|authorization|auth[_-]?token)$/i; + +/** A long single opaque word — no spaces, no template braces. */ +const OPAQUE_VALUE_RE = /^[A-Za-z0-9+/=_.-]{16,}$/; + +/** One credential found in a value: where it sits, as a dotted path + * (`nodes[2].config.apiKey`, `''` for the value itself) and as an RFC 6901 + * pointer, and what kind of credential it looks like. */ +export interface SecretHit { + readonly path: string; + readonly pointer: string; + readonly label: string; +} + +/** Escape one RFC 6901 reference token. */ +function token(part: string | number): string { + return `/${String(part).replaceAll('~', '~0').replaceAll('/', '~1')}`; +} + +/** The credential a string looks like, if any: one of the known shapes, or + * an opaque word under a key that names a credential. */ +function credentialLabel(value: string, key?: string): string | null { + for (const [pattern, label] of SECRET_PATTERNS) { + if (pattern.test(value)) return label; + } + if ( + key !== undefined && + CREDENTIAL_KEY_RE.test(key) && + OPAQUE_VALUE_RE.test(value) + ) { + return `credential-looking value under "${key}"`; + } + return null; +} + +/** + * Every credential-looking string in a JSON value, in document order: each + * string is checked against the known shapes, and an opaque word also by + * the name of the member it sits under. A string holds at most one hit. + */ +export function findSecrets(value: unknown): SecretHit[] { + const hits: SecretHit[] = []; + const walk = ( + current: unknown, + path: string, + pointer: string, + key?: string, + ): void => { + if (typeof current === 'string') { + const label = credentialLabel(current, key); + if (label !== null) hits.push({ path, pointer, label }); + } else if (Array.isArray(current)) { + for (const [index, item] of current.entries()) { + walk(item, `${path}[${index}]`, pointer + token(index)); + } + } else if (isRecord(current)) { + for (const [name, item] of Object.entries(current)) { + walk( + item, + path === '' ? name : `${path}.${name}`, + pointer + token(name), + name, + ); + } + } + }; + walk(value, '', ''); + return hits; +} From 807d8f6ed44c35c71e557984cd411ea68d6fff84 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:27:56 +0200 Subject: [PATCH 06/35] refactor(platform): read thrown refusals in one MCP module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit How an MCP surface turns what a domain writer threw into the refusal an agent reads — a spent budget as RATE_LIMITED with the wait, a coded AppError in its own words, a domain error with its code, hint and data, anything else left to be answered as a fault — moves out of the tool call into `backend/domains/mcp/refusals.ts`, so the settings tools read their writers' refusals by the same rule. No behaviour changes. --- .../platform/backend/domains/mcp/refusals.ts | 64 +++++++++++++++++++ .../platform/backend/domains/mcp/tools.ts | 58 +---------------- 2 files changed, 66 insertions(+), 56 deletions(-) create mode 100644 services/platform/backend/domains/mcp/refusals.ts diff --git a/services/platform/backend/domains/mcp/refusals.ts b/services/platform/backend/domains/mcp/refusals.ts new file mode 100644 index 0000000000..2a37ad7199 --- /dev/null +++ b/services/platform/backend/domains/mcp/refusals.ts @@ -0,0 +1,64 @@ +/** + * A refusal as a coding agent reads it, and how one is read from what a + * surface threw: every MCP surface that runs a domain writer — the tool + * call itself (`tools.ts`), the settings tools — turns a thrown refusal + * into the same `{error, code, hint?, data?}` the agent branches on, and + * leaves anything else to be answered as a fault. + */ + +import { isCodedRefusal } from '../../../lib/engine/api/refusal'; +import { isRecord } from '../../../lib/utils/type-utils'; +import { codedAppError } from '../../lib/app-error-response'; +import { rateLimitExceededCause } from '../../lib/rate-limit-response'; + +/** A refusal as the agent reads it. */ +export interface McpRefusal { + error: string; + code: string; + hint?: string; + data?: Record; +} + +function plainData(value: unknown): Record | undefined { + return isRecord(value) ? value : undefined; +} + +/** + * A thrown refusal as data, or null when what was thrown is a fault. A + * refusal keeps its code and its own sentence: a spent budget is + * `RATE_LIMITED` with the wait; a coded `AppError` gives its `data.message` + * (its `message` serializes the whole payload, which never reaches an + * agent); a domain error (`AutomationError`, `ConfigurationError`, + * `ActorAuthError`, …) gives its code, sentence, hint and data. + */ +export function refusalFromThrown(error: unknown): McpRefusal | null { + const limited = rateLimitExceededCause(error); + if (limited !== null) { + return { + error: `this key holder's budget for the call is spent; retry in ${Math.max(1, Math.ceil(limited.retryAfter / 1000))} s`, + code: 'RATE_LIMITED', + hint: 'wait data.retryAfterMs, then call again', + data: { retryAfterMs: limited.retryAfter }, + }; + } + const coded = codedAppError(error); + if (coded !== null) { + return { + error: coded.message, + code: coded.code, + ...(coded.data === undefined ? {} : { data: coded.data }), + }; + } + // One rule with the engine's dispatch (`lib/engine/api/refusal.ts`): a + // stable code and a 4xx status, or a class that refuses without one. + if (!isCodedRefusal(error)) return null; + const { code } = error; + const hint: unknown = Reflect.get(error, 'hint'); + const data = plainData(Reflect.get(error, 'data')); + return { + error: error.message, + code, + ...(typeof hint === 'string' && hint !== '' ? { hint } : {}), + ...(data === undefined ? {} : { data }), + }; +} diff --git a/services/platform/backend/domains/mcp/tools.ts b/services/platform/backend/domains/mcp/tools.ts index 0ca91710d2..80156ae4f3 100644 --- a/services/platform/backend/domains/mcp/tools.ts +++ b/services/platform/backend/domains/mcp/tools.ts @@ -16,17 +16,15 @@ import type { z } from 'zod'; -import { isCodedRefusal } from '../../../lib/engine/api/refusal'; import { type McpToolListing, toolListing } from '../../../lib/mcp/listing'; import { MCP_TOOLS, type McpToolSpec } from '../../../lib/mcp/tools'; import { defineAbilityFor } from '../../../lib/permissions/ability'; import { reportError } from '../../error-reporting'; -import { codedAppError } from '../../lib/app-error-response'; -import { rateLimitExceededCause } from '../../lib/rate-limit-response'; import { runInRequestChannel } from '../../lib/request-channel'; import { houseIssueMessage } from '../../rest/shared'; import type { McpCallOutcome } from './activity'; import type { McpCaller } from './caller'; +import { refusalFromThrown } from './refusals'; /** The whole inventory, in the advertised order. */ export function listTools(): McpToolListing[] { @@ -111,59 +109,7 @@ function invalidArguments( }; } -// ------------------------------------------------------------ refusals - -/** A refusal as the agent reads it. */ -interface Refusal { - error: string; - code: string; - hint?: string; - data?: Record; -} - -function plainData(value: unknown): Record | undefined { - return isRecord(value) ? value : undefined; -} - -/** - * A thrown refusal as data, or null when what was thrown is a fault. A - * refusal keeps its code and its own sentence: a spent budget is - * `RATE_LIMITED` with the wait; a coded `AppError` gives its `data.message` - * (its `message` serializes the whole payload, which never reaches an - * agent); a domain error (`AutomationError`, `ConfigurationError`, - * `ActorAuthError`, …) gives its code, sentence, hint and data. - */ -function refusalFromThrown(error: unknown): Refusal | null { - const limited = rateLimitExceededCause(error); - if (limited !== null) { - return { - error: `this key holder's budget for the call is spent; retry in ${Math.max(1, Math.ceil(limited.retryAfter / 1000))} s`, - code: 'RATE_LIMITED', - hint: 'wait data.retryAfterMs, then call again', - data: { retryAfterMs: limited.retryAfter }, - }; - } - const coded = codedAppError(error); - if (coded !== null) { - return { - error: coded.message, - code: coded.code, - ...(coded.data === undefined ? {} : { data: coded.data }), - }; - } - // One rule with the engine's dispatch (`lib/engine/api/refusal.ts`): a - // stable code and a 4xx status, or a class that refuses without one. - if (!isCodedRefusal(error)) return null; - const { code } = error; - const hint: unknown = Reflect.get(error, 'hint'); - const data = plainData(Reflect.get(error, 'data')); - return { - error: error.message, - code, - ...(typeof hint === 'string' && hint !== '' ? { hint } : {}), - ...(data === undefined ? {} : { data }), - }; -} +// ------------------------------------------------------------ faults /** What an agent hears of a fault: that it happened and the request id to * quote — nothing of the error itself, which may name internals. */ From e66e14fcf278ee4fe543b1735ec7d1c6145acc4e Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:35:02 +0200 Subject: [PATCH 07/35] feat(platform): plan and apply settings through one kind registry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The core of the MCP settings tools, in `backend/domains/mcp/settings/`: a registry of one handler per settings kind, each reading through its kind's native read path and writing through its native writer, and the generic layer every kind shares. - get: without kinds, the catalog (each kind's scope, operations, acts, risk, Settings pages, whether this deployment serves it and what the caller's role may do); with kinds, each readable resource with its key and native hash, secrets masked; a refused read is answered beside the others, never as an empty list. - plan: each change against a fresh read — create, update, delete, act or unchanged — with a member-by-member diff (masked), its effects and its risk (the highest of the kind's base risk and its effects'), or the refusal; a resource changed twice in one call is refused the second time. Planning never writes. - apply: compare-and-set is mandatory — every changed resource names the hash it expects (null for a create), checked before anything is read; every change is planned again and every hash compared before the first write, so a refusal or a moved resource applies nothing (SETTINGS_STALE with the current hash). Changes then run in their kinds' order, each writer re-checking its hash under its own lock; the first failure stops the rest and the answer lists what landed, what failed and what was skipped. A writer that loses the race reads as SETTINGS_STALE; one that breaks answers only the request id. - secrets: a secret reads as {masked, preview}; a change may send that masked value back to keep what is stored, and nothing else in a secret's place; every string it sends goes through the credential detector (SECRET_ARGUMENT_REFUSED names where, never the value). No kind is registered yet: each arrives with its handler beside its writer. The suites drive the layer through an in-memory registry whose writers check hashes the way the native ones do. --- .../backend/domains/mcp/settings/apply.ts | 250 ++++++ .../backend/domains/mcp/settings/diff.test.ts | 55 ++ .../backend/domains/mcp/settings/diff.ts | 68 ++ .../backend/domains/mcp/settings/get.ts | 104 +++ .../backend/domains/mcp/settings/plan.ts | 355 ++++++++ .../backend/domains/mcp/settings/registry.ts | 132 +++ .../domains/mcp/settings/secrets.test.ts | 173 ++++ .../backend/domains/mcp/settings/secrets.ts | 240 ++++++ .../domains/mcp/settings/settings.test.ts | 809 ++++++++++++++++++ 9 files changed, 2186 insertions(+) create mode 100644 services/platform/backend/domains/mcp/settings/apply.ts create mode 100644 services/platform/backend/domains/mcp/settings/diff.test.ts create mode 100644 services/platform/backend/domains/mcp/settings/diff.ts create mode 100644 services/platform/backend/domains/mcp/settings/get.ts create mode 100644 services/platform/backend/domains/mcp/settings/plan.ts create mode 100644 services/platform/backend/domains/mcp/settings/registry.ts create mode 100644 services/platform/backend/domains/mcp/settings/secrets.test.ts create mode 100644 services/platform/backend/domains/mcp/settings/secrets.ts create mode 100644 services/platform/backend/domains/mcp/settings/settings.test.ts diff --git a/services/platform/backend/domains/mcp/settings/apply.ts b/services/platform/backend/domains/mcp/settings/apply.ts new file mode 100644 index 0000000000..9d47a17dde --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/apply.ts @@ -0,0 +1,250 @@ +/** + * Applying settings changes over MCP: compare-and-set on every one, all of + * it checked before the first write, then each change through its kind's + * native writer, in its kind's order. + * + * Every change names the hash it expects (`expected`, keyed by the + * resource's address; null for one it creates). Before anything is + * written, every change is planned again against a fresh read: a refusal, + * or a resource whose hash is no longer the expected one, applies nothing. + * Then the changes run in their kinds' order, so what a resource refers to + * exists first; each writer re-checks its hash under its own lock. A + * failure stops there: the answer says what landed, what failed and what + * was skipped. No writer can undo another's change, so nothing that landed + * is rolled back — the same as a declaration the CLI applies. + */ + +import { reportError } from '../../../error-reporting.ts'; +import { currentRequestChannel } from '../../../lib/request-channel.ts'; +import { type McpRefusal, refusalFromThrown } from '../refusals.ts'; +import { + addressOf, + type PreparedChange, + prepareChanges, + type SettingsAction, +} from './plan.ts'; +import type { + SettingsChange, + SettingsContext, + SettingsRegistry, +} from './registry.ts'; + +/** One change that landed — or that already was so (`unchanged`). */ +interface AppliedChange { + readonly kind: string; + readonly id: string | null; + readonly key: string; + readonly action: SettingsAction; + /** The resource's hash now; null once it is removed. */ + readonly hash: string | null; +} + +/** One change that never ran. */ +interface SkippedChange { + readonly kind: string; + readonly id: string | null; + readonly key: string; +} + +/** The code every configuration writer raises, under its lock, when the + * hash a change expects is no longer the stored one (`assertExpectedHash`). */ +const WRITER_STALE = 'CONFIG_VERSION_CONFLICT'; + +/** One problem with `expected`, as an argument refusal lists it. */ +interface ExpectedIssue { + readonly path: string; + readonly code: string; + readonly message: string; +} + +function invalidExpected( + issues: readonly ExpectedIssue[], +): Record { + const sorted = [...issues].sort((a, b) => + a.path === b.path ? 0 : a.path < b.path ? -1 : 1, + ); + const [first] = sorted; + const more = sorted.length > 1 ? ` (and ${sorted.length - 1} more)` : ''; + return { + error: `invalid arguments for apply_settings: "${first?.path ?? 'expected'}" ${first?.message ?? 'does not match the changes'}${more}`, + code: 'INVALID_ARGUMENTS', + hint: 'expected names every changed resource by its key, with the hash get_settings or plan_settings answered (null for one you create), and nothing else', + data: { issues: sorted }, + }; +} + +/** The refusal of a change whose resource moved since it was read. */ +function stale(key: string, currentHash: string | null): McpRefusal { + return { + error: `${key} changed since it was read: its hash is no longer the one expected`, + code: 'SETTINGS_STALE', + hint: 'read it again with get_settings, plan the change against what is stored now, and apply with that hash', + data: { currentHash }, + }; +} + +function entryOf(prepared: PreparedChange): SkippedChange { + const { kind, id, key } = prepared.planned; + return { kind, id, key }; +} + +/** The answer of an apply that stopped at `at`. */ +function stopped( + refusal: McpRefusal, + at: PreparedChange, + applied: readonly AppliedChange[], + skipped: readonly PreparedChange[], +): Record { + const currentHash = refusal.data?.currentHash; + return { + error: refusal.error, + code: refusal.code, + ...(refusal.hint === undefined ? {} : { hint: refusal.hint }), + ...(refusal.data === undefined ? {} : { data: refusal.data }), + applied, + failed: { + ...entryOf(at), + code: refusal.code, + error: refusal.error, + ...(refusal.hint === undefined ? {} : { hint: refusal.hint }), + ...(currentHash === undefined ? {} : { currentHash }), + }, + skipped: skipped.map(entryOf), + }; +} + +/** What an agent hears of a writer that failed unexpectedly: that it did, + * and the request id to quote — nothing of the error itself. */ +function fault(ctx: SettingsContext, at: PreparedChange): McpRefusal { + const requestId = + currentRequestChannel()?.requestId ?? ctx.caller.requestId ?? null; + return { + error: `changing ${at.planned.key} failed unexpectedly`, + code: 'INTERNAL_ERROR', + hint: 'read what landed with get_settings before trying again; if it keeps failing, give data.requestId to whoever runs this Tale', + data: { requestId }, + }; +} + +/** The hash stored now, or null when it cannot be read. */ +async function hashNow( + ctx: SettingsContext, + prepared: PreparedChange, +): Promise { + if (prepared.ready === undefined) return null; + try { + const current = await prepared.ready.handler.read(ctx, prepared.planned.id); + return current?.hash ?? null; + } catch (error) { + console.warn( + `[mcp] settings: could not read ${prepared.planned.key} after a stale write:`, + error, + ); + return null; + } +} + +/** What `apply_settings` answers. */ +export async function applySettings( + ctx: SettingsContext, + registry: SettingsRegistry, + changes: readonly SettingsChange[], + expected: Readonly>, +): Promise> { + // The arguments first: every change's resource has an expected hash, and + // nothing else does. Nothing is read until they agree. + const keys = changes.map((change) => addressOf(registry, change).key); + const issues: ExpectedIssue[] = []; + for (const [index, key] of keys.entries()) { + if (!Object.hasOwn(expected, key)) { + issues.push({ + path: `expected.${key}`, + code: 'missing', + message: `names no hash for changes.${index}: the one get_settings answered, or null for a resource you create`, + }); + } + } + const named = new Set(keys); + for (const key of Object.keys(expected)) { + if (!named.has(key)) { + issues.push({ + path: `expected.${key}`, + code: 'unrecognized_key', + message: 'names a resource no change in this call changes', + }); + } + } + if (issues.length > 0) return invalidExpected(issues); + + // Then every change against a fresh read, before any write. + const prepared = await prepareChanges(ctx, registry, changes); + for (const entry of prepared) { + const { refusal } = entry.planned; + if (refusal !== undefined) { + return stopped( + refusal, + entry, + [], + prepared.filter((other) => other !== entry), + ); + } + } + for (const entry of prepared) { + const currentHash = entry.planned.currentHash ?? null; + if (expected[entry.planned.key] !== currentHash) { + return stopped( + stale(entry.planned.key, currentHash), + entry, + [], + prepared.filter((other) => other !== entry), + ); + } + } + + // Then each through its writer, in its kind's order. + const ordered = [...prepared].sort( + (a, b) => a.order - b.order || a.index - b.index, + ); + const applied: AppliedChange[] = []; + for (const [position, entry] of ordered.entries()) { + const { planned, ready } = entry; + if (ready === undefined || planned.action === undefined) continue; + if (planned.action === 'unchanged') { + applied.push({ + ...entryOf(entry), + action: 'unchanged', + hash: planned.currentHash ?? null, + }); + continue; + } + try { + const { hash } = await ready.handler.apply( + ctx, + ready.change, + expected[planned.key] ?? null, + ); + applied.push({ ...entryOf(entry), action: planned.action, hash }); + } catch (error) { + const rest = ordered.slice(position + 1); + const refusal = refusalFromThrown(error); + if (refusal === null) { + console.error( + `[mcp] settings: writing ${planned.key} failed unexpectedly:`, + error, + ); + reportError(error, { tags: { 'mcp.settings.kind': planned.kind } }); + return stopped(fault(ctx, entry), entry, applied, rest); + } + if (refusal.code === WRITER_STALE) { + return stopped( + stale(planned.key, await hashNow(ctx, entry)), + entry, + applied, + rest, + ); + } + return stopped(refusal, entry, applied, rest); + } + } + return { applied, skipped: [] }; +} diff --git a/services/platform/backend/domains/mcp/settings/diff.test.ts b/services/platform/backend/domains/mcp/settings/diff.test.ts new file mode 100644 index 0000000000..720834c88c --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/diff.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; + +import { diffConfigs } from './diff'; + +describe('what a change replaces', () => { + it('lists each member that differs, before and after, in key order', () => { + expect( + diffConfigs( + { minLength: 8, rules: { digits: true, symbols: false }, keep: 1 }, + { minLength: 12, rules: { digits: true, symbols: true }, keep: 1 }, + ), + ).toEqual({ + diff: [ + { path: '/minLength', before: 8, after: 12 }, + { path: '/rules/symbols', before: false, after: true }, + ], + truncated: false, + }); + }); + + it('leaves out the side a member is missing from', () => { + expect(diffConfigs({ a: 1 }, { b: 2 }).diff).toEqual([ + { path: '/a', before: 1 }, + { path: '/b', after: 2 }, + ]); + }); + + it('compares a list whole, and escapes a member name in its pointer', () => { + expect(diffConfigs({ 'a/b': [1, 2] }, { 'a/b': [1, 3] }).diff).toEqual([ + { path: '/a~1b', before: [1, 2], after: [1, 3] }, + ]); + }); + + it('answers nothing for equal configs, whatever their key order', () => { + expect( + diffConfigs({ a: 1, b: { c: 2, d: 3 } }, { b: { d: 3, c: 2 }, a: 1 }), + ).toEqual({ diff: [], truncated: false }); + }); + + it('replaces a removed resource whole', () => { + expect(diffConfigs({ a: 1 }, null).diff).toEqual([ + { path: '', before: { a: 1 }, after: null }, + ]); + }); + + it('lists at most 200 members and says when it cut', () => { + const wide = (value: number) => + Object.fromEntries( + Array.from({ length: 250 }, (_, index) => [`k${index}`, value]), + ); + const { diff, truncated } = diffConfigs(wide(1), wide(2)); + expect(diff).toHaveLength(200); + expect(truncated).toBe(true); + }); +}); diff --git a/services/platform/backend/domains/mcp/settings/diff.ts b/services/platform/backend/domains/mcp/settings/diff.ts new file mode 100644 index 0000000000..fe75208e53 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/diff.ts @@ -0,0 +1,68 @@ +/** + * What a change replaces, member by member, as a plan shows it: each leaf + * that differs with what it holds before and after. Objects are walked; + * anything else — a list included — is compared whole. Both sides arrive + * masked, so a diff never shows a secret. + */ + +import { stableStringify } from '@tale/shared/utils/stable-stringify'; + +import { isRecord } from '../../../../lib/utils/type-utils.ts'; + +/** One member a change replaces: where (an RFC 6901 pointer into the + * config, `''` for all of it), and what it holds before and after — a side + * left out has no such member. */ +export interface SettingsDiffEntry { + readonly path: string; + readonly before?: unknown; + readonly after?: unknown; +} + +/** How many members one plan lists for one change: a reader's page, never + * a catalog replaced whole spelled out entry by entry. */ +const MAX_ENTRIES = 200; + +function token(name: string): string { + return `/${name.replaceAll('~', '~0').replaceAll('/', '~1')}`; +} + +function same(left: unknown, right: unknown): boolean { + return stableStringify(left) === stableStringify(right); +} + +/** The members `after` replaces in `before`, in key order, at most + * {@link MAX_ENTRIES}; `truncated` says more were left out. */ +export function diffConfigs( + before: unknown, + after: unknown, +): { diff: SettingsDiffEntry[]; truncated: boolean } { + const diff: SettingsDiffEntry[] = []; + let truncated = false; + const push = (entry: SettingsDiffEntry): void => { + if (diff.length < MAX_ENTRIES) diff.push(entry); + else truncated = true; + }; + const walk = (left: unknown, right: unknown, path: string): void => { + if (same(left, right)) return; + if (isRecord(left) && isRecord(right)) { + const names = [ + ...new Set([...Object.keys(left), ...Object.keys(right)]), + ].sort(); + for (const name of names) { + const inLeft = Object.hasOwn(left, name); + const inRight = Object.hasOwn(right, name); + if (inLeft && inRight) { + walk(left[name], right[name], path + token(name)); + } else if (inLeft) { + push({ path: path + token(name), before: left[name] }); + } else { + push({ path: path + token(name), after: right[name] }); + } + } + return; + } + push({ path, before: left, after: right }); + }; + walk(before, after, ''); + return { diff, truncated }; +} diff --git a/services/platform/backend/domains/mcp/settings/get.ts b/services/platform/backend/domains/mcp/settings/get.ts new file mode 100644 index 0000000000..1ae846990c --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/get.ts @@ -0,0 +1,104 @@ +/** + * Reading settings over MCP. Without kinds, the catalog: every kind with + * what it is, its operations and acts, its risk, where a person changes it + * in Settings, whether this deployment serves it, and whether the caller's + * role may read and change it. With kinds, each resource the caller may + * read through the kind's native read path, its secrets masked, with the + * hash a change names as expected. A kind whose read is refused answers + * the refusal beside the others, never an empty list in its place. + */ + +import { + SETTINGS_KINDS, + settingsKindDescriptor, + type SettingsKind, +} from '@tale/shared/schemas/settings-kinds'; + +import { type McpRefusal, refusalFromThrown } from '../refusals.ts'; +import { unavailable } from './plan.ts'; +import { + type SettingsContext, + type SettingsRegistry, + settingsKey, +} from './registry.ts'; +import { maskSecrets } from './secrets.ts'; + +/** What `get_settings` reads. `ids` and `cursor` go with one kind. */ +export interface SettingsQuery { + readonly kinds?: readonly SettingsKind[]; + readonly ids?: readonly string[]; + readonly cursor?: string; +} + +const CATALOG_HINT = + 'get_settings with kinds reads their resources and hashes; plan_settings shows what a change would do, and apply_settings makes it'; + +const RESOURCES_HINT = + 'change one with plan_settings, show the plan to the person, then apply_settings naming each key with the hash read here'; + +/** What `get_settings` answers. */ +export async function getSettings( + ctx: SettingsContext, + registry: SettingsRegistry, + query: SettingsQuery, +): Promise> { + if (query.kinds === undefined) { + return { + kinds: SETTINGS_KINDS.map((descriptor) => { + const handler = registry[descriptor.kind]; + const access = handler?.access(ctx.caller) ?? { + read: false, + write: false, + }; + return { + kind: descriptor.kind, + scope: descriptor.scope, + description: descriptor.description, + ops: descriptor.ops, + acts: descriptor.acts, + baseRisk: descriptor.baseRisk, + areas: descriptor.areas, + available: handler !== undefined, + read: access.read, + write: access.write, + }; + }), + resources: [], + refused: [], + nextCursor: null, + hint: CATALOG_HINT, + }; + } + const resources: Record[] = []; + const refused: Array<{ kind: SettingsKind } & McpRefusal> = []; + let nextCursor: string | null = null; + for (const kind of new Set(query.kinds)) { + const handler = registry[kind]; + if (handler === undefined) { + refused.push({ kind, ...unavailable(kind) }); + continue; + } + const { secretPaths } = settingsKindDescriptor(kind); + try { + const page = await handler.list(ctx, { + ...(query.ids === undefined ? {} : { ids: query.ids }), + ...(query.cursor === undefined ? {} : { cursor: query.cursor }), + }); + for (const item of page.items) { + resources.push({ + kind, + id: item.id, + key: settingsKey(kind, item.id), + hash: item.hash, + config: maskSecrets(item.config, secretPaths), + }); + } + nextCursor = page.nextCursor ?? nextCursor; + } catch (error) { + const refusal = refusalFromThrown(error); + if (refusal === null) throw error; + refused.push({ kind, ...refusal }); + } + } + return { resources, refused, nextCursor, hint: RESOURCES_HINT }; +} diff --git a/services/platform/backend/domains/mcp/settings/plan.ts b/services/platform/backend/domains/mcp/settings/plan.ts new file mode 100644 index 0000000000..9d1ba27a23 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/plan.ts @@ -0,0 +1,355 @@ +/** + * A plan of settings changes: for each, what it would do to what is stored + * now — create, update, delete, act, or nothing — member by member, with + * the effects and the risk a person should weigh, or why it is refused. + * Planning reads and never writes, so a client can show the plan to the + * person before anything changes; applying plans again against fresh + * reads before its first write. + */ + +import { + SETTINGS_EFFECTS, + settingsKindDescriptor, + type SettingsEffect, + type SettingsKind, + type SettingsRisk, +} from '@tale/shared/schemas/settings-kinds'; + +import { isRecord } from '../../../../lib/utils/type-utils.ts'; +import { type McpRefusal, refusalFromThrown } from '../refusals.ts'; +import { diffConfigs, type SettingsDiffEntry } from './diff.ts'; +import { + type HandlerPlan, + type SettingsChange, + type SettingsContext, + type SettingsKindHandler, + type SettingsOperation, + type SettingsRegistry, + type SettingsResource, + settingsKey, +} from './registry.ts'; +import { + maskSecrets, + restoreMaskedSecrets, + secretArgumentRefusal, +} from './secrets.ts'; + +/** What applying a change does: `unchanged` writes nothing. */ +export type SettingsAction = + | 'create' + | 'update' + | 'delete' + | 'act' + | 'unchanged'; + +/** One change as a plan answers it. */ +export interface PlannedChange { + readonly kind: SettingsKind; + /** The resource's id within its kind (null for a single resource, or + * when the change named none). */ + readonly id: string | null; + /** The resource's address — `expected` names it by this key. */ + readonly key: string; + readonly op: SettingsOperation; + readonly act?: string; + /** Absent when the change is refused. */ + readonly action?: SettingsAction; + /** The hash stored now (null: no such resource) — what applying the + * change must name as expected. Absent when it could not be read. */ + readonly currentHash?: string | null; + readonly diff: readonly SettingsDiffEntry[]; + readonly diffTruncated?: true; + readonly effects: readonly SettingsEffect[]; + readonly risk: SettingsRisk; + readonly refusal?: McpRefusal; +} + +/** A planned change with what applying it needs. */ +export interface PreparedChange { + readonly planned: PlannedChange; + /** Its place in the call. */ + readonly index: number; + /** Where its kind applies among the call's changes. */ + readonly order: number; + /** Present when the change is not refused. */ + readonly ready?: { + readonly handler: SettingsKindHandler; + /** The change as its writer receives it: masked values put back. */ + readonly change: SettingsChange; + }; +} + +const RISK_RANK: Readonly> = { + low: 0, + high: 1, + critical: 2, +}; + +/** The highest of a kind's base risk and its effects'. */ +function riskOf( + base: SettingsRisk, + effects: readonly SettingsEffect[], +): SettingsRisk { + let risk = base; + for (const effect of effects) { + const next = SETTINGS_EFFECTS[effect]; + if (RISK_RANK[next] > RISK_RANK[risk]) risk = next; + } + return risk; +} + +/** The refusal of a kind this deployment does not serve. */ +export function unavailable(kind: SettingsKind): McpRefusal { + return { + error: `settings of kind "${kind}" are not served over MCP on this deployment`, + code: 'SETTINGS_KIND_UNAVAILABLE', + hint: 'get_settings without kinds lists the kinds and whether each is available; change this one in Tale', + }; +} + +/** The refusal of an act on a resource that does not exist. */ +function notFound(key: string): McpRefusal { + return { + error: `no ${key} to act on`, + code: 'SETTINGS_NOT_FOUND', + hint: 'get_settings lists what exists', + }; +} + +/** The refusal of a second change to a resource the call already changes. */ +function duplicate(key: string): McpRefusal { + return { + error: `${key} is changed twice in one call`, + code: 'SETTINGS_DUPLICATE', + hint: 'send one change per resource: its whole config, as it should end', + }; +} + +/** The same change, refused: what it names and what is stored stay, what + * it would have done goes. */ +function refusedPlan( + planned: PlannedChange, + refusal: McpRefusal, +): PlannedChange { + const { kind, id, key, op, act, currentHash } = planned; + return { + kind, + id, + key, + op, + ...(act === undefined ? {} : { act }), + ...(currentHash === undefined ? {} : { currentHash }), + diff: [], + effects: [], + risk: settingsKindDescriptor(kind).baseRisk, + refusal, + }; +} + +/** A refusal read from what a handler threw; anything that is not one is a + * fault and propagates. */ +function refusalOrThrow(error: unknown): McpRefusal { + const refusal = refusalFromThrown(error); + if (refusal === null) throw error; + return refusal; +} + +interface Outcome { + readonly planned: PlannedChange; + readonly ready?: PreparedChange['ready']; +} + +/** Which resource a change names, before anything is read: its kind's + * handler, its id and its key — or why it names none this deployment + * serves. */ +export interface ChangeAddress { + readonly handler?: SettingsKindHandler; + readonly id: string | null; + readonly key: string; + readonly refusal?: McpRefusal; +} + +export function addressOf( + registry: SettingsRegistry, + change: SettingsChange, +): ChangeAddress { + const named = change.id ?? null; + const handler = registry[change.kind]; + if (handler === undefined) { + return { + id: named, + key: settingsKey(change.kind, named), + refusal: unavailable(change.kind), + }; + } + try { + const id = handler.identify(change); + return { handler, id, key: settingsKey(change.kind, id) }; + } catch (error) { + return { + handler, + id: named, + key: settingsKey(change.kind, named), + refusal: refusalOrThrow(error), + }; + } +} + +/** Plan one change against a fresh read of what it changes. */ +async function planOne( + ctx: SettingsContext, + registry: SettingsRegistry, + change: SettingsChange, +): Promise { + const descriptor = settingsKindDescriptor(change.kind); + const head = { + kind: change.kind, + op: change.op, + ...(change.act === undefined ? {} : { act: change.act }), + }; + const refused = ( + id: string | null, + refusal: McpRefusal, + currentHash?: string | null, + ): Outcome => ({ + planned: { + ...head, + id, + key: settingsKey(change.kind, id), + ...(currentHash === undefined ? {} : { currentHash }), + diff: [], + effects: [], + risk: descriptor.baseRisk, + refusal, + }, + }); + const { handler, id, key, refusal } = addressOf(registry, change); + if (handler === undefined || refusal !== undefined) { + return refused(id, refusal ?? unavailable(change.kind)); + } + const secret = secretArgumentRefusal(change, descriptor.secretPaths); + if (secret !== null) return refused(id, secret); + let current: SettingsResource | null; + try { + current = await handler.read(ctx, id); + } catch (error) { + return refused(id, refusalOrThrow(error)); + } + const currentHash = current?.hash ?? null; + if (change.op === 'act' && current === null) { + return refused(id, notFound(key), currentHash); + } + let prepared = change; + if (change.op === 'set') { + const restored = restoreMaskedSecrets( + change.config, + current?.config ?? null, + descriptor.secretPaths, + ); + if ('refusal' in restored) { + return refused(id, restored.refusal, currentHash); + } + prepared = { ...change, config: restored.config }; + } + let plan: HandlerPlan; + try { + plan = await handler.plan(ctx, prepared, current); + } catch (error) { + return refused(id, refusalOrThrow(error), currentHash); + } + const action: SettingsAction = + change.op === 'act' + ? 'act' + : change.op === 'delete' + ? current === null + ? 'unchanged' + : 'delete' + : current === null + ? 'create' + : plan.unchanged === true + ? 'unchanged' + : 'update'; + const effects = + action === 'unchanged' ? [] : [...new Set(plan.effects ?? [])]; + const before = + current === null + ? null + : maskSecrets(current.config, descriptor.secretPaths); + const after = + action === 'delete' + ? null + : maskSecrets( + plan.after === undefined + ? change.op === 'set' + ? prepared.config + : before + : plan.after, + descriptor.secretPaths, + ); + // A created resource reads member by member; a removed one, whole. + const { diff, truncated } = + action === 'unchanged' + ? { diff: [], truncated: false } + : diffConfigs( + action === 'create' && isRecord(after) ? {} : before, + after, + ); + return { + planned: { + ...head, + id, + key, + action, + currentHash, + diff, + ...(truncated ? { diffTruncated: true as const } : {}), + effects, + risk: + action === 'unchanged' ? 'low' : riskOf(descriptor.baseRisk, effects), + }, + ready: { handler, change: prepared }, + }; +} + +/** + * Every change planned against what is stored now, in the call's order. A + * resource the call changes twice is refused the second time: one change + * per resource, its whole config as it should end. + */ +export async function prepareChanges( + ctx: SettingsContext, + registry: SettingsRegistry, + changes: readonly SettingsChange[], +): Promise { + const prepared: PreparedChange[] = []; + const seen = new Set(); + for (const [index, change] of changes.entries()) { + const outcome = await planOne(ctx, registry, change); + const { key } = outcome.planned; + const twice = seen.has(key); + seen.add(key); + prepared.push({ + index, + order: settingsKindDescriptor(change.kind).order, + ...(twice + ? { planned: refusedPlan(outcome.planned, duplicate(key)) } + : outcome), + }); + } + return prepared; +} + +/** What `plan_settings` answers: every change planned, and whether all of + * them could be applied as planned. */ +export async function planSettings( + ctx: SettingsContext, + registry: SettingsRegistry, + changes: readonly SettingsChange[], +): Promise<{ ok: boolean; changes: PlannedChange[] }> { + const prepared = await prepareChanges(ctx, registry, changes); + const planned = prepared.map((entry) => entry.planned); + return { + ok: planned.every((entry) => entry.refusal === undefined), + changes: planned, + }; +} diff --git a/services/platform/backend/domains/mcp/settings/registry.ts b/services/platform/backend/domains/mcp/settings/registry.ts new file mode 100644 index 0000000000..5d2cd7ab89 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/registry.ts @@ -0,0 +1,132 @@ +/** + * The settings registry: one handler per settings kind, registered beside + * the native writer it calls, and the contract the MCP settings tools drive + * every handler through. + * + * A handler reads through its kind's native read path and writes through + * its native writer, so the role checks, locks, audit rows and side effects + * stay where the app's own screens meet them. The registry adds only what + * every kind shares — a resource's address, compare-and-set, masking, the + * plan and the apply order — and never decides who may change what. + */ + +import type { + SettingsEffect, + SettingsKind, +} from '@tale/shared/schemas/settings-kinds'; +import type { Sql } from 'postgres'; + +import type { McpCaller } from '../caller.ts'; + +/** Whom a settings call acts as, and where. */ +export interface SettingsContext { + readonly sql: Sql; + readonly caller: McpCaller; +} + +/** One resource as its kind's native read answers it. */ +export interface SettingsResource { + /** Its identity within its kind; null for a kind with one resource per + * organization or deployment. */ + readonly id: string | null; + /** What is stored, secrets included: the registry masks every secret + * path before anything leaves. */ + readonly config: unknown; + /** The native revision its writer checks — what a change names as the + * hash it expects. */ + readonly hash: string; +} + +export type SettingsOperation = 'set' | 'delete' | 'act'; + +/** One change as a call names it. */ +export interface SettingsChange { + readonly kind: SettingsKind; + readonly id?: string; + readonly op: SettingsOperation; + /** The whole config the resource holds afterwards (`set`). */ + readonly config?: unknown; + /** The one-shot action (`act`): one of the kind's `acts`. */ + readonly act?: string; + readonly args?: unknown; +} + +/** What a kind says one change would do, before anything is written. */ +export interface HandlerPlan { + /** The config the resource would hold afterwards, as its native writer + * would store it; left out by an act that changes no config. */ + readonly after?: unknown; + /** The stored resource already is what the change asks for: applying it + * writes nothing. */ + readonly unchanged?: boolean; + /** What the change does beyond replacing a value. */ + readonly effects?: readonly SettingsEffect[]; +} + +/** What the caller's role lets them do with a kind, as the app's own + * screens decide it. Advisory: the native writer stays the authority. */ +export interface SettingsAccess { + readonly read: boolean; + readonly write: boolean; +} + +/** One page of a kind's resources. */ +export interface SettingsPage { + readonly items: readonly SettingsResource[]; + /** Where the next page starts; null or absent on the last one. */ + readonly nextCursor?: string | null; +} + +export interface SettingsKindHandler { + readonly kind: SettingsKind; + access(caller: McpCaller): SettingsAccess; + /** The id a change names — its `id`, or the one its config carries; null + * for a kind with a single resource. Throws a coded refusal when the + * change names none. */ + identify(change: SettingsChange): string | null; + /** The resources the caller may read, through the native read path and + * its gate. */ + list( + ctx: SettingsContext, + query: { readonly ids?: readonly string[]; readonly cursor?: string }, + ): Promise; + /** One resource, or null when there is none. */ + read( + ctx: SettingsContext, + id: string | null, + ): Promise; + /** What the change would do to what is stored: the kind's own validation, + * its effects, whether it already is so. Writes nothing; throws a coded + * refusal. */ + plan( + ctx: SettingsContext, + change: SettingsChange, + current: SettingsResource | null, + ): Promise; + /** Make the change through the native writer, which checks + * `expectedHash` under its own lock. Answers the hash afterwards (null + * once removed); throws the writer's coded refusals. */ + apply( + ctx: SettingsContext, + change: SettingsChange, + expectedHash: string | null, + ): Promise<{ readonly hash: string | null }>; +} + +export type SettingsRegistry = Readonly< + Partial> +>; + +/** + * The kinds this deployment serves over MCP, each handler registered beside + * its native writer. A kind the shared descriptors name without a handler + * here is answered as not available on this deployment. + */ +export const SETTINGS_HANDLERS: SettingsRegistry = {}; + +/** A resource's address in a call — the key `expected` names it by: its + * kind, then its id when it has one, the form a declaration's resource id + * takes. */ +export function settingsKey(kind: SettingsKind, id: string | null): string { + return id === null ? kind : `${kind}/${id}`; +} diff --git a/services/platform/backend/domains/mcp/settings/secrets.test.ts b/services/platform/backend/domains/mcp/settings/secrets.test.ts new file mode 100644 index 0000000000..0d0530db6f --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/secrets.test.ts @@ -0,0 +1,173 @@ +import { describe, expect, it } from 'vitest'; + +import { + isMaskedSecret, + maskSecrets, + restoreMaskedSecrets, + secretArgumentRefusal, + secretPlaces, +} from './secrets'; + +/** A fake stored secret, long enough for an excerpt. */ +const SENTINEL = 'SENTINEL-stored-secret-0001'; +/** A fake credential an agent might paste. */ +const PASTED = 'sk-000000000000000000000000'; + +const PATHS = ['/apiKey', '/endpoint/headers/*', '/clients/*/secret']; + +const stored = { + name: 'vendor', + apiKey: SENTINEL, + endpoint: { + url: 'https://vendor.example.invalid', + headers: { 'X-Key': SENTINEL }, + }, + clients: [{ id: 'a', secret: SENTINEL }, { id: 'b' }], +}; + +describe('secret places', () => { + it('names every place a path reaches, a * standing for each member or index', () => { + expect(secretPlaces(stored, PATHS).sort()).toEqual([ + '/apiKey', + '/clients/0/secret', + '/endpoint/headers/X-Key', + ]); + expect(secretPlaces({ name: 'x' }, PATHS)).toEqual([]); + }); +}); + +describe('masking what is answered', () => { + it('masks every secret with an excerpt and leaves the rest as stored', () => { + const masked = maskSecrets(stored, PATHS); + expect(masked).toEqual({ + name: 'vendor', + apiKey: { masked: true, preview: 'SENT…01' }, + endpoint: { + url: 'https://vendor.example.invalid', + headers: { 'X-Key': { masked: true, preview: 'SENT…01' } }, + }, + clients: [ + { id: 'a', secret: { masked: true, preview: 'SENT…01' } }, + { id: 'b' }, + ], + }); + expect(JSON.stringify(masked)).not.toContain(SENTINEL); + // The stored value itself is never changed. + expect(stored.apiKey).toBe(SENTINEL); + }); + + it('shows nothing of a short or non-text secret, and keeps a value already masked', () => { + expect( + maskSecrets({ apiKey: 'short', other: 1 }, ['/apiKey', '/other']), + ).toEqual({ + apiKey: { masked: true, preview: '••••' }, + other: { masked: true }, + }); + const already = { apiKey: { masked: true, preview: 'sk-o…Z2' } }; + expect(maskSecrets(already, ['/apiKey'])).toEqual(already); + }); + + it('tells a masked value from anything else', () => { + expect(isMaskedSecret({ masked: true })).toBe(true); + expect(isMaskedSecret({ masked: true, preview: 'x' })).toBe(true); + expect(isMaskedSecret({ masked: true, value: SENTINEL })).toBe(false); + expect(isMaskedSecret({ masked: 'true' })).toBe(false); + expect(isMaskedSecret(SENTINEL)).toBe(false); + }); +}); + +describe('refusing a secret a change carries', () => { + it('refuses a value in a secret’s place, naming where and never the value', () => { + const refusal = secretArgumentRefusal( + { config: { name: 'vendor', apiKey: 'a-new-key-typed-in' } }, + ['/apiKey'], + ); + expect(refusal).toEqual({ + error: 'a secret value at /config/apiKey: no secret travels through MCP', + code: 'SECRET_ARGUMENT_REFUSED', + hint: expect.stringContaining('masked value'), + data: { places: [{ pointer: '/config/apiKey', kind: 'a secret value' }] }, + }); + expect(JSON.stringify(refusal)).not.toContain('a-new-key-typed-in'); + }); + + it('takes the masked value back in a secret’s place', () => { + expect( + secretArgumentRefusal({ config: maskSecrets(stored, PATHS) }, PATHS), + ).toBeNull(); + }); + + it('refuses a credential pasted anywhere else, in the config or the arguments', () => { + const refusal = secretArgumentRefusal( + { + config: { description: `use ${PASTED} for now` }, + args: { note: PASTED }, + }, + [], + ); + expect(refusal?.code).toBe('SECRET_ARGUMENT_REFUSED'); + expect(refusal?.data).toEqual({ + places: [ + { pointer: '/config/description', kind: 'API key (sk-…)' }, + { pointer: '/args/note', kind: 'API key (sk-…)' }, + ], + }); + expect(refusal?.error).toBe( + 'API key (sk-…) at /config/description (and 1 more): no secret travels through MCP', + ); + expect(JSON.stringify(refusal)).not.toContain(PASTED); + }); + + it('refuses a credential smuggled into a masked value’s preview', () => { + const refusal = secretArgumentRefusal( + { config: { apiKey: { masked: true, preview: PASTED } } }, + ['/apiKey'], + ); + expect(refusal?.data).toEqual({ + places: [{ pointer: '/config/apiKey/preview', kind: 'API key (sk-…)' }], + }); + }); + + it('lets a change through that carries no secret', () => { + expect( + secretArgumentRefusal( + { config: { name: 'vendor', timeoutMs: 3000 } }, + PATHS, + ), + ).toBeNull(); + }); +}); + +describe('keeping a stored secret through a masked value', () => { + it('puts back what is stored wherever the change sends the mask', () => { + const sent = maskSecrets({ ...stored, name: 'renamed' }, PATHS); + expect(restoreMaskedSecrets(sent, stored, PATHS)).toEqual({ + config: { ...stored, name: 'renamed' }, + }); + }); + + it('leaves the mask for the writer where the native read itself only masks', () => { + const readMasked = { apiKey: { masked: true, preview: 'SENT…01' } }; + expect( + restoreMaskedSecrets({ apiKey: { masked: true } }, readMasked, [ + '/apiKey', + ]), + ).toEqual({ config: { apiKey: { masked: true } } }); + }); + + it('refuses a mask where nothing is stored to keep', () => { + const outcome = restoreMaskedSecrets({ apiKey: { masked: true } }, null, [ + '/apiKey', + ]); + expect(outcome).toEqual({ + refusal: expect.objectContaining({ + code: 'SECRET_ARGUMENT_REFUSED', + data: { + places: [ + { pointer: '/config/apiKey', kind: 'nothing stored to keep' }, + ], + }, + }), + }); + }); +}); diff --git a/services/platform/backend/domains/mcp/settings/secrets.ts b/services/platform/backend/domains/mcp/settings/secrets.ts new file mode 100644 index 0000000000..43e30e2310 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/secrets.ts @@ -0,0 +1,240 @@ +/** + * No secret crosses MCP, in or out. A secret a resource stores reads as a + * masked value wherever a settings tool answers it. A change may carry that + * masked value back unchanged, which keeps what is stored, and nothing else + * in a secret's place; every string a change carries also goes through the + * credential detector, so a key pasted into a description is refused the + * same way. A refusal names where a secret was found and what it looked + * like, never the value. + */ + +import { findSecrets } from '../../../../lib/shared/secret-scan.ts'; +import { isRecord } from '../../../../lib/utils/type-utils.ts'; +import { maskSecret } from '../../../core/provider_credentials/masking.ts'; +import type { McpRefusal } from '../refusals.ts'; + +/** What a secret reads as. Sent back unchanged inside a change, it keeps + * the value that is stored. */ +export interface MaskedSecret { + readonly masked: true; + /** A short excerpt Tale shows for the secret, when it has one. */ + readonly preview?: string; +} + +export function isMaskedSecret(value: unknown): value is MaskedSecret { + return ( + isRecord(value) && + value.masked === true && + Object.keys(value).every((key) => key === 'masked' || key === 'preview') && + (value.preview === undefined || typeof value.preview === 'string') + ); +} + +/** The masked form of a stored value: an excerpt of a string, nothing of + * anything else. */ +function maskedOf(value: unknown): MaskedSecret { + if (isMaskedSecret(value)) return value; + return typeof value === 'string' + ? { masked: true, preview: maskSecret(value) } + : { masked: true }; +} + +// ------------------------------------------------------------ pointers + +function escapeToken(token: string): string { + return token.replaceAll('~', '~0').replaceAll('/', '~1'); +} + +function pointerTokens(pointer: string): string[] { + if (pointer === '') return []; + return pointer + .slice(1) + .split('/') + .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~')); +} + +const INDEX = /^(?:0|[1-9]\d*)$/; + +/** The value at a concrete pointer, if one is there. */ +function valueAt( + root: unknown, + pointer: string, +): { found: true; value: unknown } | { found: false } { + let current: unknown = root; + for (const token of pointerTokens(pointer)) { + if (Array.isArray(current)) { + if (!INDEX.test(token) || Number(token) >= current.length) { + return { found: false }; + } + current = current[Number(token)]; + } else if (isRecord(current) && Object.hasOwn(current, token)) { + current = current[token]; + } else { + return { found: false }; + } + } + return { found: true, value: current }; +} + +/** Replace the value at a concrete pointer below the root, in place. */ +function replaceAt(root: unknown, pointer: string, next: unknown): void { + const tokens = pointerTokens(pointer); + const last = tokens.pop(); + if (last === undefined) return; + const parent = valueAt( + root, + tokens.map((t) => `/${escapeToken(t)}`).join(''), + ); + if (!parent.found) return; + if (Array.isArray(parent.value) && INDEX.test(last)) { + parent.value[Number(last)] = next; + } else if (isRecord(parent.value)) { + parent.value[last] = next; + } +} + +/** + * Every place in `value` a secret path names, as concrete pointers: a `*` + * token stands for each member or index there. Only places that hold + * something are named. + */ +export function secretPlaces( + value: unknown, + secretPaths: readonly string[], +): string[] { + const places = new Set(); + const walk = (node: unknown, rest: readonly string[], at: string): void => { + const [head, ...tail] = rest; + if (head === undefined) { + places.add(at); + return; + } + if (Array.isArray(node)) { + node.forEach((item, index) => { + if (head === '*' || head === String(index)) { + walk(item, tail, `${at}/${index}`); + } + }); + } else if (isRecord(node)) { + for (const [name, item] of Object.entries(node)) { + if (head === '*' || head === name) { + walk(item, tail, `${at}/${escapeToken(name)}`); + } + } + } + }; + for (const path of secretPaths) walk(value, pointerTokens(path), ''); + return [...places]; +} + +/** A config with every secret it holds masked — what a settings tool + * answers in place of what is stored. */ +export function maskSecrets( + config: unknown, + secretPaths: readonly string[], +): unknown { + const places = secretPlaces(config, secretPaths); + if (places.length === 0) return config; + const masked = structuredClone(config); + for (const place of places) { + const stored = valueAt(masked, place); + if (stored.found) replaceAt(masked, place, maskedOf(stored.value)); + } + return masked; +} + +// ------------------------------------------------------------ refusals + +/** One place a change carries a secret: where, and what it looked like. */ +interface SecretPlace { + readonly pointer: string; + readonly kind: string; +} + +/** How many places one refusal names — enough to fix a change, never a + * hostile one echoed back at length. */ +const MAX_PLACES = 20; + +function secretRefusal(places: readonly SecretPlace[]): McpRefusal { + const [first] = places; + const where = first === undefined ? 'the change' : first.pointer; + const what = first === undefined ? 'a secret' : first.kind; + const more = places.length > 1 ? ` (and ${places.length - 1} more)` : ''; + return { + error: `${what} at ${where}${more}: no secret travels through MCP`, + code: 'SECRET_ARGUMENT_REFUSED', + hint: 'leave it out — send back the masked value get_settings answered to keep a stored secret; a person enters a new one in Tale', + data: { places: places.slice(0, MAX_PLACES) }, + }; +} + +/** + * The refusal of a change that carries a secret — anything but the masked + * value at a secret's place, or a credential anywhere in what it sends — + * or null when it carries none. + */ +export function secretArgumentRefusal( + change: { readonly config?: unknown; readonly args?: unknown }, + secretPaths: readonly string[], +): McpRefusal | null { + const places = new Map(); + if (change.config !== undefined) { + for (const place of secretPlaces(change.config, secretPaths)) { + const sent = valueAt(change.config, place); + if (sent.found && !isMaskedSecret(sent.value)) { + const pointer = `/config${place}`; + places.set(pointer, { pointer, kind: 'a secret value' }); + } + } + } + for (const hit of findSecrets({ config: change.config, args: change.args })) { + if (!places.has(hit.pointer)) { + places.set(hit.pointer, { pointer: hit.pointer, kind: hit.label }); + } + } + return places.size === 0 ? null : secretRefusal([...places.values()]); +} + +/** + * The config a change asks for, with every masked value put back to what + * is stored at the same place, so the native writer keeps it. Where the + * native read itself answers only a mask, the masked value stays for the + * writer, which keeps its stored secret; a masked value where nothing is + * stored keeps nothing, and is refused. + */ +export function restoreMaskedSecrets( + config: unknown, + stored: unknown, + secretPaths: readonly string[], +): { readonly config: unknown } | { readonly refusal: McpRefusal } { + const places = secretPlaces(config, secretPaths).filter((place) => { + const sent = valueAt(config, place); + return sent.found && isMaskedSecret(sent.value); + }); + if (places.length === 0) return { config }; + const restored = structuredClone(config); + const missing: SecretPlace[] = []; + for (const place of places) { + const kept = valueAt(stored, place); + if (!kept.found || kept.value === null) { + missing.push({ + pointer: `/config${place}`, + kind: 'nothing stored to keep', + }); + } else if (!isMaskedSecret(kept.value)) { + replaceAt(restored, place, kept.value); + } + } + if (missing.length > 0) { + const [first] = missing; + return { + refusal: { + error: `a masked value at ${first?.pointer ?? 'the change'} keeps nothing: no secret is stored there`, + code: 'SECRET_ARGUMENT_REFUSED', + hint: 'a new secret is entered in Tale, never sent through MCP; leave the field out', + data: { places: missing.slice(0, MAX_PLACES) }, + }, + }; + } + return { config: restored }; +} diff --git a/services/platform/backend/domains/mcp/settings/settings.test.ts b/services/platform/backend/domains/mcp/settings/settings.test.ts new file mode 100644 index 0000000000..8be21bedf4 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/settings.test.ts @@ -0,0 +1,809 @@ +/** + * The settings tools' shared core, driven through an in-memory registry + * whose handlers behave like the native writers they stand for: each read + * answers a hash, each write checks the expected hash under its "lock" and + * throws the writers' own `CONFIG_VERSION_CONFLICT` when it moved. + */ + +import type { SettingsKind } from '@tale/shared/schemas/settings-kinds'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; +import type { Sql } from 'postgres'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { ConfigurationError } from '../../../core/lib/config_store/precondition'; +import { runInRequestChannel } from '../../../lib/request-channel'; +import type { McpCaller } from '../caller'; +import { applySettings } from './apply'; +import { getSettings } from './get'; +import { planSettings } from './plan'; +import type { + HandlerPlan, + SettingsChange, + SettingsContext, + SettingsKindHandler, + SettingsRegistry, +} from './registry'; + +// Providers store one secret here, so the masked round trip runs end to +// end; every real kind of the first release stores none. +vi.mock('@tale/shared/schemas/settings-kinds', async (importOriginal) => { + const real = + await importOriginal< + typeof import('@tale/shared/schemas/settings-kinds') + >(); + return { + ...real, + settingsKindDescriptor: (kind: SettingsKind) => { + const descriptor = real.settingsKindDescriptor(kind); + return kind === 'provider' + ? { ...descriptor, secretPaths: ['/apiKey'] } + : descriptor; + }, + }; +}); + +/** A fake stored secret: no answer may ever carry it. */ +const SENTINEL = 'SENTINEL-provider-secret-0001'; + +const ada: McpCaller = { + organizationId: 'org_1', + orgSlug: 'acme', + userId: 'user_ada', + role: 'admin', + credential: { kind: 'api-key', apiKeyId: 'key_laptop' }, +}; + +// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double: the fake handlers never query +const sql = {} as unknown as Sql; + +function contextFor(caller: McpCaller = ada): SettingsContext { + return { sql, caller }; +} + +interface Fake { + readonly store: Map; + readonly writes: string[]; + readonly registry: SettingsRegistry; + readonly handlers: Record; +} + +/** + * Three kinds in memory: providers by name (one secret each), governance + * policies by key, and the organization's one branding. Changing a policy + * named `password_policy` may lock members out; a provider named + * `refused` is refused by its writer, and one named `broken` breaks it. + */ +function fake(): Fake { + const store = new Map(); + const writes: string[] = []; + const handler = ( + kind: SettingsKind, + single: boolean, + effects: HandlerPlan['effects'] = [], + ): SettingsKindHandler => { + const keyOf = (id: string | null) => (id === null ? kind : `${kind}/${id}`); + const resource = (id: string | null) => { + const config = store.get(keyOf(id)); + return config === undefined + ? null + : { id, config, hash: configurationHash(config) }; + }; + return { + kind, + access: (caller) => ({ + read: true, + write: caller.role === 'admin' || caller.role === 'owner', + }), + identify: (change) => { + if (single) return null; + if (change.id !== undefined) return change.id; + throw new ConfigurationError( + 'SETTINGS_ID_REQUIRED', + `a ${kind} change names its id`, + 400, + ); + }, + list: async (_ctx, query) => ({ + items: [...store.keys()] + .filter((key) => key === kind || key.startsWith(`${kind}/`)) + .map((key) => (key === kind ? null : key.slice(kind.length + 1))) + .filter( + (id) => query.ids === undefined || query.ids.includes(id ?? ''), + ) + .flatMap((id) => resource(id) ?? []), + nextCursor: null, + }), + read: async (_ctx, id) => resource(id), + plan: async (_ctx, change, current) => { + if (change.id === 'invalid') { + throw new ConfigurationError( + 'SETTINGS_INVALID', + 'minLength must be at least 8', + 400, + ); + } + return { + ...(change.op === 'set' ? { after: change.config } : {}), + unchanged: + current !== null && + change.op === 'set' && + configurationHash(current.config) === + configurationHash(change.config), + effects, + }; + }, + apply: async (_ctx, change, expectedHash) => { + const id = single ? null : (change.id ?? null); + if (id === 'refused') { + throw new ConfigurationError( + 'PROVIDER_FORBIDDEN', + 'Only owners and admins can change providers.', + 403, + ); + } + if (id === 'broken') throw new Error('disk full at /var/lib/tale'); + if ((resource(id)?.hash ?? null) !== expectedHash) { + throw new ConfigurationError( + 'CONFIG_VERSION_CONFLICT', + 'Configuration changed since it was reviewed.', + ); + } + writes.push(keyOf(id)); + if (change.op === 'delete') { + store.delete(keyOf(id)); + return { hash: null }; + } + if (change.op === 'set') store.set(keyOf(id), change.config); + return { hash: resource(id)?.hash ?? null }; + }, + }; + }; + const handlers = { + provider: handler('provider', false), + governance: handler('governance', false, ['may-lock-out-members']), + branding: handler('branding', true), + }; + return { store, writes, registry: handlers, handlers }; +} + +function seeded(): Fake { + const state = fake(); + state.store.set('provider/vendor', { + name: 'vendor', + baseUrl: 'https://vendor.example.invalid/v1', + apiKey: SENTINEL, + }); + state.store.set('governance/password_policy', { minLength: 8 }); + state.store.set('branding', { accentColor: '#336699' }); + return state; +} + +const hashOf = (state: Fake, key: string) => + configurationHash(state.store.get(key)); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('get_settings', () => { + it('answers the catalog of kinds without kinds: available here, and what the role may do', async () => { + const state = seeded(); + const catalog = await getSettings( + contextFor({ ...ada, role: 'member' }), + state.registry, + {}, + ); + const kinds = catalog.kinds as Array>; + expect(kinds.map((entry) => entry.kind)).toEqual([ + 'provider', + 'provider-credential', + 'governance', + 'knowledge-embedding', + 'branding', + 'project-instructions', + 'agent-instructions', + 'agent-tools', + 'task-instructions', + 'deployment', + ]); + expect(kinds.find((entry) => entry.kind === 'governance')).toMatchObject({ + available: true, + read: true, + write: false, + ops: ['set'], + baseRisk: 'high', + }); + expect(kinds.find((entry) => entry.kind === 'deployment')).toMatchObject({ + available: false, + read: false, + write: false, + }); + expect(catalog.resources).toEqual([]); + }); + + it('reads each resource with its key and hash, its secrets masked', async () => { + const state = seeded(); + const answer = await getSettings(contextFor(), state.registry, { + kinds: ['provider', 'branding'], + }); + expect(answer.resources).toEqual([ + { + kind: 'provider', + id: 'vendor', + key: 'provider/vendor', + hash: hashOf(state, 'provider/vendor'), + config: { + name: 'vendor', + baseUrl: 'https://vendor.example.invalid/v1', + apiKey: { masked: true, preview: 'SENT…01' }, + }, + }, + { + kind: 'branding', + id: null, + key: 'branding', + hash: hashOf(state, 'branding'), + config: { accentColor: '#336699' }, + }, + ]); + expect(JSON.stringify(answer)).not.toContain(SENTINEL); + }); + + it('answers a kind it cannot read as refused beside the others, never as empty', async () => { + const state = seeded(); + vi.spyOn(state.handlers.governance!, 'list').mockRejectedValue( + new ConfigurationError( + 'FORBIDDEN_ORG_SETTINGS', + 'Only owners and admins can read governance policies.', + 403, + ), + ); + const answer = await getSettings(contextFor(), state.registry, { + kinds: ['governance', 'deployment', 'branding'], + }); + expect(answer.refused).toEqual([ + { + kind: 'governance', + code: 'FORBIDDEN_ORG_SETTINGS', + error: 'Only owners and admins can read governance policies.', + }, + { + kind: 'deployment', + code: 'SETTINGS_KIND_UNAVAILABLE', + error: + 'settings of kind "deployment" are not served over MCP on this deployment', + hint: expect.any(String), + }, + ]); + expect(answer.resources).toHaveLength(1); + }); + + it('lets a fault through instead of answering it as a refusal', async () => { + const state = seeded(); + vi.spyOn(state.handlers.branding!, 'list').mockRejectedValue( + new Error('connection refused'), + ); + await expect( + getSettings(contextFor(), state.registry, { kinds: ['branding'] }), + ).rejects.toThrow('connection refused'); + }); +}); + +describe('plan_settings', () => { + it('says what each change would do to what is stored, member by member', async () => { + const state = seeded(); + const plan = await planSettings(contextFor(), state.registry, [ + { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: { minLength: 12 }, + }, + { kind: 'governance', id: 'budgets', op: 'set', config: { rules: [] } }, + { kind: 'branding', op: 'set', config: { accentColor: '#336699' } }, + { kind: 'provider', id: 'vendor', op: 'delete' }, + ]); + expect(plan.ok).toBe(true); + expect(plan.changes).toEqual([ + { + kind: 'governance', + id: 'password_policy', + key: 'governance/password_policy', + op: 'set', + action: 'update', + currentHash: hashOf(state, 'governance/password_policy'), + diff: [{ path: '/minLength', before: 8, after: 12 }], + effects: ['may-lock-out-members'], + risk: 'critical', + }, + { + kind: 'governance', + id: 'budgets', + key: 'governance/budgets', + op: 'set', + action: 'create', + currentHash: null, + diff: [{ path: '/rules', after: [] }], + effects: ['may-lock-out-members'], + risk: 'critical', + }, + { + kind: 'branding', + id: null, + key: 'branding', + op: 'set', + action: 'unchanged', + currentHash: hashOf(state, 'branding'), + diff: [], + effects: [], + risk: 'low', + }, + { + kind: 'provider', + id: 'vendor', + key: 'provider/vendor', + op: 'delete', + action: 'delete', + currentHash: hashOf(state, 'provider/vendor'), + diff: [ + { + path: '', + before: { + name: 'vendor', + baseUrl: 'https://vendor.example.invalid/v1', + apiKey: { masked: true, preview: 'SENT…01' }, + }, + after: null, + }, + ], + effects: [], + risk: 'high', + }, + ]); + expect(JSON.stringify(plan)).not.toContain(SENTINEL); + }); + + it('writes nothing', async () => { + const state = seeded(); + const before = JSON.stringify([...state.store]); + await planSettings(contextFor(), state.registry, [ + { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: { minLength: 12 }, + }, + { kind: 'provider', id: 'vendor', op: 'delete' }, + ]); + expect(state.writes).toEqual([]); + expect(JSON.stringify([...state.store])).toBe(before); + }); + + it('refuses each change that cannot be applied as asked, and plans the rest', async () => { + const state = seeded(); + const plan = await planSettings(contextFor(), state.registry, [ + { kind: 'deployment', op: 'set', config: { version: 1 } }, + { kind: 'governance', op: 'set', config: {} }, + { + kind: 'governance', + id: 'invalid', + op: 'set', + config: { minLength: 1 }, + }, + { kind: 'provider', id: 'ghost', op: 'act', act: 'refresh-catalogs' }, + { kind: 'branding', op: 'set', config: { accentColor: '#000000' } }, + { kind: 'branding', op: 'set', config: { accentColor: '#ffffff' } }, + ]); + expect(plan.ok).toBe(false); + expect( + plan.changes.map((change) => [ + change.key, + change.refusal?.code ?? change.action, + ]), + ).toEqual([ + ['deployment', 'SETTINGS_KIND_UNAVAILABLE'], + ['governance', 'SETTINGS_ID_REQUIRED'], + ['governance/invalid', 'SETTINGS_INVALID'], + ['provider/ghost', 'SETTINGS_NOT_FOUND'], + ['branding', 'update'], + ['branding', 'SETTINGS_DUPLICATE'], + ]); + // A refused change says why, and nothing of what it would have done. + expect(plan.changes[5]).toEqual({ + kind: 'branding', + id: null, + key: 'branding', + op: 'set', + currentHash: hashOf(state, 'branding'), + diff: [], + effects: [], + risk: 'low', + refusal: expect.objectContaining({ code: 'SETTINGS_DUPLICATE' }), + }); + }); + + it('refuses a credential pasted into a setting, wherever it sits, without repeating it', async () => { + const state = seeded(); + const pasted = 'sk-000000000000000000000000'; + const plan = await planSettings(contextFor(), state.registry, [ + { + kind: 'governance', + id: 'system_prompt', + op: 'set', + config: { prompt: `Call the API with ${pasted}` }, + }, + { + kind: 'provider', + id: 'vendor', + op: 'set', + config: { name: 'vendor', apiKey: 'typed-in-new-key' }, + }, + ]); + expect(plan.changes.map((change) => change.refusal?.data)).toEqual([ + { places: [{ pointer: '/config/prompt', kind: 'API key (sk-…)' }] }, + { places: [{ pointer: '/config/apiKey', kind: 'a secret value' }] }, + ]); + expect(JSON.stringify(plan)).not.toContain(pasted); + expect(JSON.stringify(plan)).not.toContain('typed-in-new-key'); + }); +}); + +describe('apply_settings', () => { + const passwordChange: SettingsChange = { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: { minLength: 12 }, + }; + + it('needs the expected hash of every changed resource, and nothing else, before it reads anything', async () => { + const state = seeded(); + const read = vi.spyOn(state.handlers.governance!, 'read'); + const answer = await applySettings( + contextFor(), + state.registry, + [ + passwordChange, + { kind: 'branding', op: 'set', config: { accentColor: '#000000' } }, + ], + { branding: hashOf(state, 'branding'), 'governance/budgets': null }, + ); + expect(answer).toEqual({ + error: + 'invalid arguments for apply_settings: "expected.governance/budgets" names a resource no change in this call changes (and 1 more)', + code: 'INVALID_ARGUMENTS', + hint: expect.any(String), + data: { + issues: [ + { + path: 'expected.governance/budgets', + code: 'unrecognized_key', + message: 'names a resource no change in this call changes', + }, + { + path: 'expected.governance/password_policy', + code: 'missing', + message: expect.stringContaining('changes.0'), + }, + ], + }, + }); + expect(read).not.toHaveBeenCalled(); + expect(state.writes).toEqual([]); + }); + + it('applies nothing when one resource moved since it was read', async () => { + const state = seeded(); + const read = hashOf(state, 'governance/password_policy'); + // Ben changes the policy in the app between the agent's read and apply. + state.store.set('governance/password_policy', { minLength: 10 }); + const answer = await applySettings( + contextFor(), + state.registry, + [ + { kind: 'branding', op: 'set', config: { accentColor: '#000000' } }, + passwordChange, + ], + { + branding: hashOf(state, 'branding'), + 'governance/password_policy': read, + }, + ); + expect(answer).toMatchObject({ + code: 'SETTINGS_STALE', + data: { currentHash: hashOf(state, 'governance/password_policy') }, + applied: [], + failed: { + key: 'governance/password_policy', + code: 'SETTINGS_STALE', + currentHash: hashOf(state, 'governance/password_policy'), + }, + skipped: [{ kind: 'branding', id: null, key: 'branding' }], + }); + expect(state.writes).toEqual([]); + expect(state.store.get('branding')).toEqual({ accentColor: '#336699' }); + }); + + it('applies nothing when one change is refused', async () => { + const state = seeded(); + const answer = await applySettings( + contextFor(), + state.registry, + [ + passwordChange, + { kind: 'deployment', op: 'set', config: { version: 1 } }, + ], + { + 'governance/password_policy': hashOf( + state, + 'governance/password_policy', + ), + deployment: null, + }, + ); + expect(answer).toMatchObject({ + code: 'SETTINGS_KIND_UNAVAILABLE', + applied: [], + failed: { key: 'deployment' }, + skipped: [{ key: 'governance/password_policy' }], + }); + expect(state.writes).toEqual([]); + }); + + it('applies in the kinds’ order, whatever order the call names them in', async () => { + const state = seeded(); + const answer = await applySettings( + contextFor(), + state.registry, + [ + { kind: 'branding', op: 'set', config: { accentColor: '#000000' } }, + passwordChange, + { + kind: 'provider', + id: 'second', + op: 'set', + config: { name: 'second' }, + }, + ], + { + branding: hashOf(state, 'branding'), + 'governance/password_policy': hashOf( + state, + 'governance/password_policy', + ), + 'provider/second': null, + }, + ); + expect(state.writes).toEqual([ + 'provider/second', + 'governance/password_policy', + 'branding', + ]); + expect(answer).toEqual({ + applied: [ + { + kind: 'provider', + id: 'second', + key: 'provider/second', + action: 'create', + hash: hashOf(state, 'provider/second'), + }, + { + kind: 'governance', + id: 'password_policy', + key: 'governance/password_policy', + action: 'update', + hash: hashOf(state, 'governance/password_policy'), + }, + { + kind: 'branding', + id: null, + key: 'branding', + action: 'update', + hash: hashOf(state, 'branding'), + }, + ], + skipped: [], + }); + }); + + it('stops at a refused write: what landed stays, the rest is skipped', async () => { + const state = seeded(); + state.store.set('provider/refused', { name: 'refused' }); + const answer = await applySettings( + contextFor(), + state.registry, + [ + { kind: 'branding', op: 'set', config: { accentColor: '#000000' } }, + { + kind: 'provider', + id: 'second', + op: 'set', + config: { name: 'second' }, + }, + { + kind: 'provider', + id: 'refused', + op: 'set', + config: { name: 'refused', note: 'x' }, + }, + ], + { + branding: hashOf(state, 'branding'), + 'provider/second': null, + 'provider/refused': hashOf(state, 'provider/refused'), + }, + ); + expect(answer).toMatchObject({ + error: 'Only owners and admins can change providers.', + code: 'PROVIDER_FORBIDDEN', + applied: [{ key: 'provider/second', action: 'create' }], + failed: { key: 'provider/refused', code: 'PROVIDER_FORBIDDEN' }, + skipped: [{ key: 'branding' }], + }); + expect(state.writes).toEqual(['provider/second']); + expect(state.store.get('provider/second')).toEqual({ name: 'second' }); + }); + + it('answers a write that lost a race as stale, with the hash stored now', async () => { + const state = seeded(); + const read = hashOf(state, 'governance/password_policy'); + const governance = state.handlers.governance!; + const realApply = governance.apply.bind(governance); + // Someone saves the policy after the agent's preflight, before its write. + vi.spyOn(governance, 'apply').mockImplementation( + async (ctx, change, expected) => { + state.store.set('governance/password_policy', { minLength: 9 }); + return realApply(ctx, change, expected); + }, + ); + const answer = await applySettings( + contextFor(), + state.registry, + [passwordChange], + { + 'governance/password_policy': read, + }, + ); + expect(answer).toMatchObject({ + code: 'SETTINGS_STALE', + applied: [], + failed: { + key: 'governance/password_policy', + currentHash: hashOf(state, 'governance/password_policy'), + }, + skipped: [], + }); + expect(state.store.get('governance/password_policy')).toEqual({ + minLength: 9, + }); + }); + + it('answers a writer that broke with the request id alone, after what landed', async () => { + const state = seeded(); + state.store.set('provider/broken', { name: 'broken' }); + const logged = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined); + const answer = await runInRequestChannel( + { via: 'mcp', requestId: 'req-9' }, + () => + applySettings( + contextFor(), + state.registry, + [ + { + kind: 'provider', + id: 'second', + op: 'set', + config: { name: 'second' }, + }, + { + kind: 'provider', + id: 'broken', + op: 'set', + config: { name: 'broken', x: 1 }, + }, + ], + { + 'provider/second': null, + 'provider/broken': hashOf(state, 'provider/broken'), + }, + ), + ); + expect(answer).toMatchObject({ + code: 'INTERNAL_ERROR', + data: { requestId: 'req-9' }, + applied: [{ key: 'provider/second' }], + failed: { key: 'provider/broken', code: 'INTERNAL_ERROR' }, + }); + expect(JSON.stringify(answer)).not.toContain('disk full'); + expect(logged).toHaveBeenCalledOnce(); + }); + + it('writes nothing for a change that already is so', async () => { + const state = seeded(); + const answer = await applySettings( + contextFor(), + state.registry, + [{ kind: 'branding', op: 'set', config: { accentColor: '#336699' } }], + { branding: hashOf(state, 'branding') }, + ); + expect(answer).toEqual({ + applied: [ + { + kind: 'branding', + id: null, + key: 'branding', + action: 'unchanged', + hash: hashOf(state, 'branding'), + }, + ], + skipped: [], + }); + expect(state.writes).toEqual([]); + }); + + it('keeps a stored secret through the masked value it read: read, edit, write back', async () => { + const state = seeded(); + const read = await getSettings(contextFor(), state.registry, { + kinds: ['provider'], + ids: ['vendor'], + }); + const [vendor] = read.resources as Array<{ + key: string; + hash: string; + config: Record; + }>; + const answer = await applySettings( + contextFor(), + state.registry, + [ + { + kind: 'provider', + id: 'vendor', + op: 'set', + config: { + ...vendor!.config, + baseUrl: 'https://vendor.example.invalid/v2', + }, + }, + ], + { [vendor!.key]: vendor!.hash }, + ); + expect(answer).toMatchObject({ + applied: [{ key: 'provider/vendor', action: 'update' }], + }); + expect(state.store.get('provider/vendor')).toEqual({ + name: 'vendor', + baseUrl: 'https://vendor.example.invalid/v2', + apiKey: SENTINEL, + }); + expect(JSON.stringify([read, answer])).not.toContain(SENTINEL); + }); + + it('refuses a new secret and applies nothing', async () => { + const state = seeded(); + const answer = await applySettings( + contextFor(), + state.registry, + [ + { + kind: 'provider', + id: 'vendor', + op: 'set', + config: { name: 'vendor', apiKey: 'typed-in-new-key' }, + }, + ], + { 'provider/vendor': hashOf(state, 'provider/vendor') }, + ); + expect(answer).toMatchObject({ + code: 'SECRET_ARGUMENT_REFUSED', + applied: [], + }); + expect(JSON.stringify(answer)).not.toContain('typed-in-new-key'); + expect(state.store.get('provider/vendor')).toMatchObject({ + apiKey: SENTINEL, + }); + }); +}); From 25441191ebdc6e46daba70d869205f699450260c Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:46:33 +0200 Subject: [PATCH 08/35] feat(platform): read, plan and change settings over MCP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three tools in a new `settings` group put the settings core behind the MCP endpoint: - `get_settings` answers the catalog of setting kinds, or the resources of the kinds asked for with their keys and native hashes, secrets masked; - `plan_settings` plans up to 32 changes and writes nothing; - `apply_settings` applies them compare-and-set (`expected` names every changed resource's hash), asks the person before every call and draws from a new `rest:settings` budget (30 a minute, 60 at once), charged after the arguments pass. A change names its kind, its id and its op; what a kind does not take — an op, an action, a missing config — is refused with every other problem as INVALID_ARGUMENTS before anything is read. The server instructions gain the settings loop; the MCP tab lists the group in English, German and French; the endpoint page documents the tools, the access rule and the new codes, and the rate-limit page the budget, in all three languages. Spec cards MCP-R11 (a call applies only when each setting is still what was read) and MCP-R12 (no secret in or out) are held by the core's suites. Contract 3.28.0: the MCP fingerprint, the schema and skill snapshots and the OpenAPI document move with it; no REST operation changes. No kind is served yet, so every kind reads as unavailable until its handler lands beside its writer. --- docs/de/develop/mcp-endpoint.md | 17 +- docs/de/develop/rate-limits.md | 3 +- docs/en/develop/mcp-endpoint.md | 17 +- docs/en/develop/rate-limits.md | 3 +- docs/fr/develop/mcp-endpoint.md | 17 +- docs/fr/develop/rate-limits.md | 3 +- .../components/mcp-endpoint-section.test.tsx | 1 + .../backend/domains/mcp/platform-tools.ts | 11 +- .../backend/domains/mcp/protocol.test.ts | 4 + .../domains/mcp/settings/settings.test.ts | 10 +- .../backend/domains/mcp/settings/tools.ts | 50 +++ services/platform/backend/domains/mcp/spec.md | 38 +- .../backend/domains/mcp/tools.test.ts | 133 +++++++ .../platform/backend/domains/mcp/tools.ts | 39 +- services/platform/backend/lib/rate-limit.ts | 9 + services/platform/backend/rest/v1-mcp.ts | 5 +- services/platform/lib/mcp/args.ts | 145 ++++++++ .../lib/mcp/contract-fingerprint.json | 4 +- .../platform/lib/mcp/endpoint-docs.test.ts | 1 + .../platform/lib/mcp/instructions.test.ts | 16 +- services/platform/lib/mcp/instructions.ts | 4 + services/platform/lib/mcp/results.ts | 38 ++ services/platform/lib/mcp/skill.snapshot.md | 2 +- .../lib/mcp/tools.schema.snapshot.json | 337 ++++++++++++++++++ services/platform/lib/mcp/tools.test.ts | 20 +- services/platform/lib/mcp/tools.ts | 69 +++- .../lib/shared/constants/api-contract.ts | 22 +- services/platform/messages/de/settings.yml | 4 + services/platform/messages/en/settings.yml | 4 + services/platform/messages/fr/settings.yml | 4 + services/platform/public/openapi.json | 4 +- .../scripts/openapi/contract-fingerprint.json | 2 +- 32 files changed, 975 insertions(+), 61 deletions(-) create mode 100644 services/platform/backend/domains/mcp/settings/tools.ts diff --git a/docs/de/develop/mcp-endpoint.md b/docs/de/develop/mcp-endpoint.md index 94995271a7..42289cb056 100644 --- a/docs/de/develop/mcp-endpoint.md +++ b/docs/de/develop/mcp-endpoint.md @@ -97,7 +97,7 @@ Die Antwort nennt unter `supportedVersions` alle Revisionen und enthält dieselb `tools/list` liefert das Eingabeschema jedes Tools, und ein lesendes Tool beschreibt seine Antwort zusätzlich in `outputSchema`. Die Argumente werden vor der Ausführung geprüft: Fehlende, falsch typisierte, leere oder unerwartete Argumente lehnt der Endpunkt mit einem einzigen Tool-Ergebnis mit `isError` ab, dessen `code` `INVALID_ARGUMENTS` lautet und dessen `data.issues` jedes Problem mit `path`, `code` und `message` aufführt. Den Wert eines Arguments wiederholt die Ablehnung nie. Jedes Ergebnis trägt seine Antwort als kompakten JSON-Text, und die erfolgreiche Antwort eines lesenden Tools kommt zusätzlich als `structuredContent`, dasselbe Objekt. Das Dokument in `validate_automation`, `run_automation`, `test_automation` oder `save_automation` hat bewusst eine offene Hülle: `get_docs` erklärt die Grammatik, die Engine validiert den Inhalt. -Tools liefern außerdem `readOnlyHint`, `destructiveHint`, `idempotentHint` und `openWorldHint`. Ein Host kann damit einen Aufruf erklären; die Hinweise erteilen aber weder Rechte noch Sicherheitsgarantien. Lesezugriffe sind als solche markiert, Speichern schreibt eine Version, Live-Schalten, Löschen, Installieren und Triggeränderungen können Bestehendes ersetzen. Live-Ausführungen können echte Dienste ansprechen. Live-Schalten, Löschen, einen Trigger setzen, eine Automatisierung in Projekten installieren und die Frage eines Laufs beantworten tragen zusätzlich `_meta["anthropic/requiresUserInteraction"]`: Ein Client, der das beachtet, fragt die Person vor jedem solchen Aufruf. +Tools liefern außerdem `readOnlyHint`, `destructiveHint`, `idempotentHint` und `openWorldHint`. Ein Host kann damit einen Aufruf erklären; die Hinweise erteilen aber weder Rechte noch Sicherheitsgarantien. Lesezugriffe sind als solche markiert, Speichern schreibt eine Version, Live-Schalten, Löschen, Installieren, Triggeränderungen und Einstellungsänderungen können Bestehendes ersetzen. Live-Ausführungen und manche Einstellungsänderungen können echte Dienste ansprechen. Live-Schalten, Löschen, einen Trigger setzen, eine Automatisierung in Projekten installieren, die Frage eines Laufs beantworten und Einstellungen ändern tragen zusätzlich `_meta["anthropic/requiresUserInteraction"]`: Ein Client, der das beachtet, fragt die Person vor jedem solchen Aufruf. ### Automatisierungen entwickeln {#authoring} @@ -182,6 +182,18 @@ Beide Tools für bereitgestellte Versionen verwenden denselben dauerhaften Runne Jede Antwort trägt einen `hint`, der das Tool oder die Einstellung nennt, mit der sie sich ändert. +### Einstellungen {#settings} + +| Tool | Was es tut | +| --- | --- | +| `get_settings` | Ohne `kinds` der Katalog: jede Art von Einstellung mit dem, was sie ist, ihren Operationen (`ops`) und Aktionen (`acts`), ihrem `baseRisk`, den Einstellungsseiten, auf denen eine Person dieselbe Änderung vornimmt (`areas`), ob dieses Deployment sie über MCP bedient (`available`) und ob deine Rolle sie lesen (`read`) und ändern (`write`) darf. Mit `kinds` — für eine einzelne Art auch mit `ids` oder dem `cursor` ihrer nächsten Seite — jede Ressource, die du lesen darfst, mit ihrem `key`, ihrer `config` und ihrem `hash`. Eine Art, die du nicht lesen darfst, steht mit dem Grund unter `refused`. | +| `plan_settings` | Plant bis zu 32 Änderungen, ohne eine davon vorzunehmen. Jede nennt ihre `action` (`create`, `update`, `delete`, `act` oder `unchanged`), den `currentHash`, einen `diff` Feld für Feld, ihre `effects` und ihr `risk` (`low`, `high` oder `critical`) oder die Ablehnung (`refusal`), an der sie scheitert. | +| `apply_settings` | Nimmt die Änderungen vor. `expected` ordnet dem `key` jeder geänderten Ressource den Hash zu, den du gelesen hast, oder `null` für eine, die du anlegst. Wird eine Änderung abgelehnt oder hat sich eine Ressource seit dem Lesen geändert, wird nichts übernommen. Sonst laufen die Änderungen in einer festen Reihenfolge über die Arten hinweg, und die erste, die scheitert, hält die übrigen an: Die Antwort listet, was übernommen wurde (`applied`), was gescheitert ist (`failed`) und was übersprungen wurde (`skipped`). | + +Eine Änderung nennt ihre Art (`kind`), die `id` der Ressource (entfällt bei einer Art mit nur einer Ressource) und ihre Operation (`op`): `set` ersetzt die Ressource durch die ganze `config` und legt sie an, wenn es sie noch nicht gibt; `delete` entfernt sie; `act` führt eine der Aktionen der Art mit ihren `args` aus. Plane zuerst, zeig der Person den Plan und nimm dann dieselben Änderungen vor: `apply_settings` fragt die Person vor jedem Aufruf und hat ein eigenes [Budget](/de/develop/rate-limits). + +Kein Secret geht durch diese Tools. Ein gespeichertes Secret erscheint als `{"masked": true, "preview": "…"}`; schick diesen Wert unverändert zurück, um es zu behalten. Eine Änderung mit einem anderen Wert an der Stelle eines Secrets oder mit Zugangsdaten irgendwo in ihrer Konfiguration wird mit `SECRET_ARGUMENT_REFUSED` abgelehnt; ein neues Secret gibt eine Person in Tale ein. + ### Capabilities und Wissen {#capabilities} | Tool | Was es tut | @@ -229,6 +241,7 @@ Jedes Argument ist ein einzelnes Wort, weil Clients wie Claude Code die Argument | Lesen, Validierung, Mock-Ausführungen (auch `start_run` mit `mode: "mock"`) und Akzeptanztests, Capability-Suche, Wissensabruf | Mitgliedschaft plus normale Zugriffsregeln der Ressource | | Die Frage eines Laufs beantworten | Mitgliedschaft; bei einem Lauf in einem Projekt Bearbeitungszugriff auf dieses Projekt | | Namen der Agent-Secrets (`list_agent_secrets`) | Rolle Inhaber, Admin oder Entwickler; alle anderen bekommen eine leere Liste | +| Einstellungen lesen, planen und ändern (`get_settings`, `plan_settings`, `apply_settings`) | Was deine Rolle auf derselben Einstellungsseite darf; der Katalog sagt, was deine Rolle mit jeder Art tun darf | | Speichern, live schalten, löschen, in Projekten installieren, Trigger setzen/löschen, Lauf abbrechen oder live ausführen | Entwicklerberechtigung plus normale Zugriffsregeln der Ressource | Der Schlüssel identifiziert seinen Inhaber. Er erweitert weder dessen Rolle noch dessen Projektzugriff. Eine Automatisierung, die nur in Projekten installiert ist, die der Schlüsselinhaber nicht lesen darf, fehlt in `list_automations`, und jeder Lesezugriff auf sie antwortet `AUTOMATION_NOT_FOUND` wie bei einer, die es nicht gibt. Auch eine Live-Ausführung über `invoke_capability` durchläuft die Ausführungsprüfungen. @@ -251,7 +264,7 @@ Lies vor dem Einrichten privilegierter Tools `GET /api/v1/me`: `capabilities.dev | Capability mit `status: "waiting"` in `output` | Der Lauf wartet, etwa auf eine Genehmigung, die eine Person in Tale erteilt; er ist weder fertig noch fehlgeschlagen. `get_run` abfragen und nicht erneut versuchen | | Capability mit `refused` | Fehlerergebnis; die genannte Ursache beheben | -Zu den Tool-Codes gehören `AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_UNKNOWN`, `AUTOMATION_NOT_DEPLOYED`, `RUN_NOT_FOUND`, `AUTOMATION_INVALID`, `AUTOMATION_TESTS_FAILING`, `AUTOMATION_VERSION_STALE`, `AUTOMATION_DEPLOYMENT_STALE`, `AUTOMATION_NAME_TAKEN`, `AUTOMATION_HAS_ACTIVE_RUNS`, `AUTOMATION_NOT_INSTALLED`, `HUMAN_ASK_NOT_FOUND`, `HUMAN_ASK_NOT_PENDING`, `HUMAN_ASK_EXPIRED`, `EMPTY_ANSWER`, `INVALID_CURSOR`, `LIVE_MODE_UNAVAILABLE` und `NOT_SUPPORTED`. Letzterer bedeutet, dass der Host den Vorgang für Läufe, Versionen oder Trigger nicht unterstützt. `start_run` lehnt einen wiederverwendeten `idempotencyKey` mit anderen Argumenten als `IDEMPOTENCY_KEY_REUSED` ab; `invoke_capability` lehnt eine ID, die das Register nicht führt — eine nur gespeicherte Automatisierung steht nicht darin —, als `CAPABILITY_NOT_FOUND` ab und Eingaben, die ihr Schema zurückweist, als `CAPABILITY_INPUT_INVALID`; `get_knowledge` reicht die eigenen Codes der Wissens-Tür durch (`KNOWLEDGE_UNAVAILABLE`, wenn die Suche selbst fehlgeschlagen ist). Plattformfehler behalten ihren eigenen Code, Hinweis und gegebenenfalls Daten; fehlender Entwicklerzugriff liefert etwa `FORBIDDEN_DEVELOPER_SETTINGS`. `INVALID_ARGUMENTS` führt jedes Argumentproblem auf; ein Wert außerhalb einer aufgezählten Menge wird abgelehnt, und die Meldung nennt die Menge. `RATE_LIMITED` bedeutet, dass das Tool eine Ausführung gebraucht hätte und das [Ausführungsbudget](/de/develop/rate-limits) des Schlüsselinhabers aufgebraucht ist: Warte `data.retryAfterMs` ab. `INTERNAL_ERROR` bedeutet, dass der Aufruf unerwartet fehlgeschlagen ist; nenne dem Betreiber des Deployments die `data.requestId`. +Zu den Tool-Codes gehören `AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_UNKNOWN`, `AUTOMATION_NOT_DEPLOYED`, `RUN_NOT_FOUND`, `AUTOMATION_INVALID`, `AUTOMATION_TESTS_FAILING`, `AUTOMATION_VERSION_STALE`, `AUTOMATION_DEPLOYMENT_STALE`, `AUTOMATION_NAME_TAKEN`, `AUTOMATION_HAS_ACTIVE_RUNS`, `AUTOMATION_NOT_INSTALLED`, `HUMAN_ASK_NOT_FOUND`, `HUMAN_ASK_NOT_PENDING`, `HUMAN_ASK_EXPIRED`, `EMPTY_ANSWER`, `INVALID_CURSOR`, `LIVE_MODE_UNAVAILABLE` und `NOT_SUPPORTED`. Letzterer bedeutet, dass der Host den Vorgang für Läufe, Versionen oder Trigger nicht unterstützt. `start_run` lehnt einen wiederverwendeten `idempotencyKey` mit anderen Argumenten als `IDEMPOTENCY_KEY_REUSED` ab; `invoke_capability` lehnt eine ID, die das Register nicht führt — eine nur gespeicherte Automatisierung steht nicht darin —, als `CAPABILITY_NOT_FOUND` ab und Eingaben, die ihr Schema zurückweist, als `CAPABILITY_INPUT_INVALID`; `get_knowledge` reicht die eigenen Codes der Wissens-Tür durch (`KNOWLEDGE_UNAVAILABLE`, wenn die Suche selbst fehlgeschlagen ist). Plattformfehler behalten ihren eigenen Code, Hinweis und gegebenenfalls Daten; fehlender Entwicklerzugriff liefert etwa `FORBIDDEN_DEVELOPER_SETTINGS`. `INVALID_ARGUMENTS` führt jedes Argumentproblem auf; ein Wert außerhalb einer aufgezählten Menge wird abgelehnt, und die Meldung nennt die Menge. `RATE_LIMITED` bedeutet, dass das Tool eine Ausführung oder eine Einstellungsänderung gebraucht hätte und das [Budget](/de/develop/rate-limits) des Schlüsselinhabers dafür aufgebraucht ist: Warte `data.retryAfterMs` ab. `INTERNAL_ERROR` bedeutet, dass der Aufruf unerwartet fehlgeschlagen ist; nenne dem Betreiber des Deployments die `data.requestId`. Die Einstellungs-Tools ergänzen `SETTINGS_STALE` (eine Ressource hat sich seit dem Lesen geändert; `data.currentHash` ist ihr aktueller Hash), `SECRET_ARGUMENT_REFUSED` (eine Änderung enthielt ein Secret; `data.places` sagt, wo, nie, was), `SETTINGS_KIND_UNAVAILABLE` (dieses Deployment bedient diese Art nicht über MCP), `SETTINGS_NOT_FOUND` (eine Aktion auf einer Ressource, die es nicht gibt) und `SETTINGS_DUPLICATE` (eine Ressource wurde in einem Aufruf zweimal geändert). Ein unbekannter Automatisierungsname ist auch bei `list_versions`, `list_runs` und `list_triggers` ein Fehler. Eine leere Liste bedeutet, dass eine vorhandene Automatisierung keine passenden Einträge hat. Die eine Ausnahme ist die Laufhistorie: Eine gelöschte Automatisierung behält ihre Läufe, `list_runs {name}` antwortet sie also, solange es sie gibt, und nur ein Name, der nie gelaufen ist, ergibt `AUTOMATION_NOT_FOUND`. `get_catalog`, auf eine Kern-Knotenart eingegrenzt (`transform`, `llm`, `agent`, `subautomation`), antwortet mit einer leeren Liste und einem `hint` auf `get_docs`, wie `search_catalog` auch, und liefert unter `reference` den Abschnitt der Referenz zu dieser Knotenart. Ungültige Dokumente für Tools, die ein gültiges Dokument benötigen, fehlgeschlagene Suchen und fehlende Bereitstellungen setzen `isError: true`. Nur das Validierungstool meldet ein ungültiges Dokument als normales Prüfergebnis. diff --git a/docs/de/develop/rate-limits.md b/docs/de/develop/rate-limits.md index 911d38a0a6..4383373263 100644 --- a/docs/de/develop/rate-limits.md +++ b/docs/de/develop/rate-limits.md @@ -15,6 +15,7 @@ Ein Token-Bucket füllt sich kontinuierlich bis zu seiner Burst-Kapazität auf. | --- | --- | --- | --- | | Allgemeine `/api/v1`-Aufrufe einschließlich MCP und Modell-Endpunkten | 120/Minute | 200 | Schlüsselinhaber | | Laufstarts, Modellnachrichten, Aufgabenstarts und MCP-Ausführungen | 20/Minute | 40 | Schlüsselinhaber | +| Einstellungsänderungen über MCP (`apply_settings`) | 30/Minute | 60 | Schlüsselinhaber | | Upload-Freigabe und Dateizuordnung im Projekt | 240/Minute | 300 | Schlüsselinhaber | | Fehlgeschlagene API-Schlüsselprüfung | 20/Minute | 40 | Quell-IP | | Webhook-Zustellungen vor der Tokenprüfung | 120/Minute | 240 | Absenderadresse | @@ -24,7 +25,7 @@ REST-Ausführungen und Uploads verbrauchen zusätzlich das allgemeine Budget. Ei Zur Ausführung gehören projektgebundene und globale Automatisierungsstarts, Thread-Nachrichten und ausdrückliche Aufgabenstarts. Die Aufgabenübernahme verbraucht ebenfalls Ausführungsbudget, wenn `runWorkflowSlug` gesetzt ist. Eine Arbeit-startende Anfrage wird belastet, sobald Body und Kopfzeilen die eigenen Prüfungen der Tür bestanden haben — eine `400 INVALID_BODY` oder `INVALID_HEADER` kostet nichts — und bevor irgendetwas nachgeschlagen wird, eine `404` für einen Thread, eine Aufgabe oder eine Automatisierung, die du nicht sehen kannst, kostet also ein Token, so wie eine `409`, die der Zustand antwortet. Manche Änderungen, etwa Aufgabenkommentare und Ordneränderungen, unterliegen weiteren Fachbereichslimits, die auch für die App gelten. -MCP-Batches rechnen zusätzliche Tool-Aufrufe als zusätzliche Anfragen ab. Der [MCP-Endpunkt](/de/develop/mcp-endpoint) erklärt den Unterschied zwischen HTTP `429` und einer einzelnen abgelehnten Batch-Nachricht. Ein MCP-Tool, das eine Automatisierung ausführt (`run_automation`, `test_automation`, `deploy_automation`, `run_deployed`, `start_run` und `invoke_capability`), verbraucht zusätzlich eine Ausführung, sobald die Rolle des Schlüsselinhabers den Aufruf erlaubt; ebenso `answer_run_ask`, dessen Antwort einen wartenden Lauf fortsetzt wie die Antwort über REST. Ist dieses Budget aufgebraucht, antwortet der Aufruf mit einem Tool-Ergebnis mit `code` `RATE_LIMITED`, dessen `data.retryAfterMs` die Wartezeit nennt, nicht mit HTTP `429`. Lesen, Prüfen und Speichern verbrauchen keine Ausführung. Webhooks haben getrennte Budgets; sowohl Absender- als auch Auslöserlimit müssen die Zustellung zulassen. +MCP-Batches rechnen zusätzliche Tool-Aufrufe als zusätzliche Anfragen ab. Der [MCP-Endpunkt](/de/develop/mcp-endpoint) erklärt den Unterschied zwischen HTTP `429` und einer einzelnen abgelehnten Batch-Nachricht. Ein MCP-Tool, das eine Automatisierung ausführt (`run_automation`, `test_automation`, `deploy_automation`, `run_deployed`, `start_run` und `invoke_capability`), verbraucht zusätzlich eine Ausführung, sobald die Rolle des Schlüsselinhabers den Aufruf erlaubt; ebenso `answer_run_ask`, dessen Antwort einen wartenden Lauf fortsetzt wie die Antwort über REST. Ist dieses Budget aufgebraucht, antwortet der Aufruf mit einem Tool-Ergebnis mit `code` `RATE_LIMITED`, dessen `data.retryAfterMs` die Wartezeit nennt, nicht mit HTTP `429`. Lesen, Prüfen und Speichern verbrauchen keine Ausführung. Eine Einstellungsänderung (`apply_settings`) verbraucht auf dieselbe Weise eine Einheit ihres eigenen Einstellungsbudgets und wird mit `RATE_LIMITED` beantwortet, sobald es aufgebraucht ist; Einstellungen lesen und planen verbraucht nichts davon. Webhooks haben getrennte Budgets; sowohl Absender- als auch Auslöserlimit müssen die Zustellung zulassen. Aufrufe der [Modell-Endpunkte](/de/develop/api-reference#model-endpoints) unter `/api/v1/openai` und `/api/v1/anthropic` zählen nur gegen das allgemeine Budget, jeweils als eine Anfrage, ob gestreamt oder nicht; was ein Aufruf ausgeben darf, begrenzen die Budgetregeln gesondert. Außerdem dürfen eine Person und jeder API-Schlüssel acht dieser Aufrufe gleichzeitig laufen haben: Ein neunter erhält `429` mit `code` `MODEL_API_CONCURRENCY_EXCEEDED` und `Retry-After: 2`. diff --git a/docs/en/develop/mcp-endpoint.md b/docs/en/develop/mcp-endpoint.md index 1d95025c23..cc0e93b5f1 100644 --- a/docs/en/develop/mcp-endpoint.md +++ b/docs/en/develop/mcp-endpoint.md @@ -97,7 +97,7 @@ The answer lists every revision under `supportedVersions` and carries the same c `tools/list` is the source for each tool's input schema, and a read tool also states its answer in `outputSchema`. Arguments are checked before execution: missing, mistyped, blank, or unexpected ones are refused with one tool result marked `isError`, whose `code` is `INVALID_ARGUMENTS` and whose `data.issues` lists every problem with its `path`, `code`, and `message`. The refusal never repeats an argument's value. Every result carries its answer as compact JSON text, and a read tool's successful answer also comes as `structuredContent`, the same object. The document passed to `validate_automation`, `run_automation`, `test_automation`, or `save_automation` is intentionally an open envelope: `get_docs` explains its grammar, and the engine validates its contents. -Tools also expose `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`. Hosts can use these annotations to explain a call, but they do not grant permission or guarantee safety. Reads are marked read-only; saving writes a version; deployment, deletion, installation and trigger changes can replace existing state; live runs can contact real services. Deploying, deleting, setting a trigger, installing an automation in projects, and answering a run's question also carry `_meta["anthropic/requiresUserInteraction"]`, so a client that honors it asks the person before every such call. +Tools also expose `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`. Hosts can use these annotations to explain a call, but they do not grant permission or guarantee safety. Reads are marked read-only; saving writes a version; deployment, deletion, installation, trigger and settings changes can replace existing state; live runs and some settings changes can contact real services. Deploying, deleting, setting a trigger, installing an automation in projects, answering a run's question, and changing settings also carry `_meta["anthropic/requiresUserInteraction"]`, so a client that honors it asks the person before every such call. ### Authoring {#authoring} @@ -182,6 +182,18 @@ Both deployed-run tools use the durable runner with the same authorization and e Each answer carries a `hint` that names the tool or the setting that changes it. +### Settings {#settings} + +| Tool | What it does | +| --- | --- | +| `get_settings` | Without `kinds`, the catalog: every kind of setting with what it is, its operations (`ops`) and actions (`acts`), its `baseRisk`, the Settings pages where a person makes the same change (`areas`), whether this deployment serves it over MCP (`available`), and whether your role may `read` and `write` it. With `kinds` — for one kind, also `ids` or the `cursor` of its next page — every resource you may read, with its `key`, its `config` and its `hash`. A kind you may not read is listed under `refused` with the reason. | +| `plan_settings` | Plan up to 32 changes without making any. Each answers its `action` (`create`, `update`, `delete`, `act` or `unchanged`), the `currentHash`, a `diff` member by member, its `effects` and its `risk` (`low`, `high` or `critical`), or the `refusal` that stops it. | +| `apply_settings` | Make the changes. `expected` maps each changed resource's `key` to the hash you read, or `null` for one you create. If a change is refused or a resource changed since you read it, nothing is applied. Otherwise the changes run in a fixed order across kinds, and the first one that fails stops the rest: the answer lists what was `applied`, what `failed` and what was `skipped`. | + +A change names its `kind`, the resource's `id` (left out for a kind with one resource) and its `op`: `set` replaces the resource with the whole `config`, creating it when it does not exist; `delete` removes it; `act` runs one of the kind's actions, with its `args`. Plan first, show the plan to the person, then apply the same changes: `apply_settings` asks the person before every call and uses a [budget](/develop/rate-limits) of its own. + +No secret travels through these tools. A stored secret reads as `{"masked": true, "preview": "…"}`; send that value back unchanged to keep it. A change that carries any other value in a secret's place, or a credential anywhere in its config, is refused with `SECRET_ARGUMENT_REFUSED`; a person enters a new secret in Tale. + ### Capabilities & knowledge {#capabilities} | Tool | What it does | @@ -229,6 +241,7 @@ Each argument is a single word, because clients such as Claude Code split argume | Reads, validation, mock runs (`start_run` with `mode: "mock"` included) and acceptance tests, capability search, knowledge retrieval | Organization membership, plus the resource's normal access rules | | Answer a run's question | Organization membership; for a run in a project, edit access to that project | | Agent secret names (`list_agent_secrets`) | Owner, Admin or Developer role; anyone else gets an empty list | +| Read, plan and change settings (`get_settings`, `plan_settings`, `apply_settings`) | What your role allows on the same Settings page; the catalog says what your role may do with each kind | | Save, deploy, delete, install in projects, set/delete a trigger, cancel a run, or execute live | Developer capability, plus the resource's normal access rules | The key identifies its holder; it does not expand that person's role or project access. An automation installed only in projects the key holder cannot read is left out of `list_automations`, and every read of it answers `AUTOMATION_NOT_FOUND`, as for one that does not exist. Live `invoke_capability` calls also pass through the execution checks. @@ -251,7 +264,7 @@ Read `GET /api/v1/me` before configuring privileged tools: `capabilities.develop | Capability `output` with `status: "waiting"` | The run waits, for example for an approval a person gives in Tale; it has neither finished nor failed. Poll `get_run` and do not retry it | | Capability result `refused` | Error result; correct the stated cause | -Tool refusal codes include `AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_UNKNOWN`, `AUTOMATION_NOT_DEPLOYED`, `RUN_NOT_FOUND`, `AUTOMATION_INVALID`, `AUTOMATION_TESTS_FAILING`, `AUTOMATION_VERSION_STALE`, `AUTOMATION_DEPLOYMENT_STALE`, `AUTOMATION_NAME_TAKEN`, `AUTOMATION_HAS_ACTIVE_RUNS`, `AUTOMATION_NOT_INSTALLED`, `HUMAN_ASK_NOT_FOUND`, `HUMAN_ASK_NOT_PENDING`, `HUMAN_ASK_EXPIRED`, `EMPTY_ANSWER`, `INVALID_CURSOR`, `LIVE_MODE_UNAVAILABLE`, and `NOT_SUPPORTED`. The latter means the host does not support that run/version/trigger operation. `start_run` refuses a reused `idempotencyKey` with different arguments as `IDEMPOTENCY_KEY_REUSED`; `invoke_capability` refuses an id the registry does not hold — a saved-only automation is not in it — as `CAPABILITY_NOT_FOUND` and input its schema rejects as `CAPABILITY_INPUT_INVALID`; `get_knowledge` lifts the knowledge endpoint's own codes through (`KNOWLEDGE_UNAVAILABLE` when the search itself failed). Platform errors retain their own code, hint, and optional data; for example, missing developer access returns `FORBIDDEN_DEVELOPER_SETTINGS`. `INVALID_ARGUMENTS` lists every argument problem; a value outside an enumerated set is refused with the set named. `RATE_LIMITED` means the tool needed an execution and the key holder's [execution budget](/develop/rate-limits) is spent: wait `data.retryAfterMs`. `INTERNAL_ERROR` means the call failed unexpectedly; its `data.requestId` is the id to quote to whoever runs the deployment. +Tool refusal codes include `AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_UNKNOWN`, `AUTOMATION_NOT_DEPLOYED`, `RUN_NOT_FOUND`, `AUTOMATION_INVALID`, `AUTOMATION_TESTS_FAILING`, `AUTOMATION_VERSION_STALE`, `AUTOMATION_DEPLOYMENT_STALE`, `AUTOMATION_NAME_TAKEN`, `AUTOMATION_HAS_ACTIVE_RUNS`, `AUTOMATION_NOT_INSTALLED`, `HUMAN_ASK_NOT_FOUND`, `HUMAN_ASK_NOT_PENDING`, `HUMAN_ASK_EXPIRED`, `EMPTY_ANSWER`, `INVALID_CURSOR`, `LIVE_MODE_UNAVAILABLE`, and `NOT_SUPPORTED`. The latter means the host does not support that run/version/trigger operation. `start_run` refuses a reused `idempotencyKey` with different arguments as `IDEMPOTENCY_KEY_REUSED`; `invoke_capability` refuses an id the registry does not hold — a saved-only automation is not in it — as `CAPABILITY_NOT_FOUND` and input its schema rejects as `CAPABILITY_INPUT_INVALID`; `get_knowledge` lifts the knowledge endpoint's own codes through (`KNOWLEDGE_UNAVAILABLE` when the search itself failed). Platform errors retain their own code, hint, and optional data; for example, missing developer access returns `FORBIDDEN_DEVELOPER_SETTINGS`. `INVALID_ARGUMENTS` lists every argument problem; a value outside an enumerated set is refused with the set named. `RATE_LIMITED` means the tool needed an execution, or a settings change, and the key holder's [budget](/develop/rate-limits) for it is spent: wait `data.retryAfterMs`. `INTERNAL_ERROR` means the call failed unexpectedly; its `data.requestId` is the id to quote to whoever runs the deployment. The settings tools add `SETTINGS_STALE` (a resource changed since you read it; `data.currentHash` is its hash now), `SECRET_ARGUMENT_REFUSED` (a change carried a secret; `data.places` says where, never what), `SETTINGS_KIND_UNAVAILABLE` (this deployment does not serve that kind over MCP), `SETTINGS_NOT_FOUND` (an action on a resource that does not exist) and `SETTINGS_DUPLICATE` (one resource changed twice in one call). An unknown automation name is an error even for `list_versions`, `list_runs`, and `list_triggers`; an empty list means an existing automation has no matching items. The one exception is run history: a deleted automation keeps its runs, so `list_runs {name}` answers them for as long as they exist, and only a name that never ran is `AUTOMATION_NOT_FOUND`. `get_catalog` narrowed to a core node kind (`transform`, `llm`, `agent`, `subautomation`) answers an empty list with a `hint` pointing at `get_docs`, as `search_catalog` does, and the kind's own section of the reference as `reference`. Invalid documents passed to tools that need a valid one, search failures, and missing deployments set `isError: true`. Only the validation tool reports an invalid document as its ordinary verdict. diff --git a/docs/en/develop/rate-limits.md b/docs/en/develop/rate-limits.md index cf17a63d5c..7ca0cff2e3 100644 --- a/docs/en/develop/rate-limits.md +++ b/docs/en/develop/rate-limits.md @@ -15,6 +15,7 @@ A token bucket refills continuously up to its burst capacity. A short batch can | --- | --- | --- | --- | | General `/api/v1` traffic, including MCP and the model endpoints | 120/minute | 200 | Key holder | | Run starts, model-message sends, task starts and MCP executions | 20/minute | 40 | Key holder | +| Settings changes over MCP (`apply_settings`) | 30/minute | 60 | Key holder | | Project upload handoff and file binding | 240/minute | 300 | Key holder | | Failed API-key authentication | 20/minute | 40 | Source IP | | Webhook deliveries before token validation | 120/minute | 240 | Sender address | @@ -24,7 +25,7 @@ REST execution and upload requests also consume the general budget. For example, Execution includes project and non-project automation starts, thread-message sends and explicit task starts. Task intake also consumes the execution budget when `runWorkflowSlug` is supplied. A starting-work request is charged once its body and headers have passed the endpoint's own checks — a `400 INVALID_BODY` or `INVALID_HEADER` spends nothing — and before anything is looked up, so a `404` for a thread, task or automation you cannot see costs a token, as does a `409` the state answers. Some mutations, such as task comments and folder changes, have additional domain budgets shared with the app. -MCP batches have their own accounting: additional tool calls consume additional request budget. See [MCP endpoint](/develop/mcp-endpoint) for the difference between an HTTP `429` and a refused message inside a batch. An MCP tool that executes an automation (`run_automation`, `test_automation`, `deploy_automation`, `run_deployed`, `start_run` and `invoke_capability`) also uses one execution once the key holder's role allows the call, and so does `answer_run_ask`, whose answer resumes a waiting run as the REST answer does. When that budget is spent, the call is answered with a tool result whose `code` is `RATE_LIMITED` and whose `data.retryAfterMs` names the wait, not with an HTTP `429`. Reads, validation and saving use no execution. Webhook budgets are separate from API-key traffic; both sender and trigger limits must allow a delivery. +MCP batches have their own accounting: additional tool calls consume additional request budget. See [MCP endpoint](/develop/mcp-endpoint) for the difference between an HTTP `429` and a refused message inside a batch. An MCP tool that executes an automation (`run_automation`, `test_automation`, `deploy_automation`, `run_deployed`, `start_run` and `invoke_capability`) also uses one execution once the key holder's role allows the call, and so does `answer_run_ask`, whose answer resumes a waiting run as the REST answer does. When that budget is spent, the call is answered with a tool result whose `code` is `RATE_LIMITED` and whose `data.retryAfterMs` names the wait, not with an HTTP `429`. Reads, validation and saving use no execution. A settings change (`apply_settings`) uses one unit of its own settings budget the same way and is answered with `RATE_LIMITED` once that budget is spent; reading and planning settings use none. Webhook budgets are separate from API-key traffic; both sender and trigger limits must allow a delivery. Calls to the [model endpoints](/develop/api-reference#model-endpoints) under `/api/v1/openai` and `/api/v1/anthropic` count against the general budget only, one request each, streamed or not; what a call may spend is capped separately by budget rules. A person, and each API key, may also have eight of these calls running at once: a ninth answers `429` with `code` `MODEL_API_CONCURRENCY_EXCEEDED` and `Retry-After: 2`. diff --git a/docs/fr/develop/mcp-endpoint.md b/docs/fr/develop/mcp-endpoint.md index a7431fc1a3..cd0a4bc058 100644 --- a/docs/fr/develop/mcp-endpoint.md +++ b/docs/fr/develop/mcp-endpoint.md @@ -97,7 +97,7 @@ La réponse liste toutes les révisions dans `supportedVersions` et contient les `tools/list` fournit le schéma d'entrée de chaque outil, et un outil de lecture décrit aussi sa réponse dans `outputSchema`. Les arguments sont vérifiés avant exécution : un argument manquant, vide, mal typé ou inattendu est refusé par un seul résultat d’outil marqué `isError`, dont le `code` est `INVALID_ARGUMENTS` et dont `data.issues` liste chaque problème avec son `path`, son `code` et son `message`. Le refus ne répète jamais la valeur d’un argument. Chaque résultat porte sa réponse sous forme de texte JSON compact, et la réponse réussie d’un outil de lecture arrive aussi comme `structuredContent`, le même objet. Le document passé à `validate_automation`, `run_automation`, `test_automation` ou `save_automation` garde volontairement une enveloppe ouverte : `get_docs` en explique la grammaire et le moteur valide son contenu. -Les outils exposent aussi `readOnlyHint`, `destructiveHint`, `idempotentHint` et `openWorldHint`. Un hôte peut s'en servir pour expliquer un appel, mais ces indications n'accordent aucun droit et ne garantissent pas sa sûreté. Les lectures sont marquées comme telles ; enregistrer écrit une version ; déployer, supprimer, installer ou modifier un déclencheur peut remplacer un état existant. Les exécutions réelles peuvent joindre de vrais services. Mettre en service, supprimer, définir un déclencheur, installer une automatisation dans des projets et répondre à la question d’une exécution portent aussi `_meta["anthropic/requiresUserInteraction"]` : un client qui en tient compte demande à la personne avant chacun de ces appels. +Les outils exposent aussi `readOnlyHint`, `destructiveHint`, `idempotentHint` et `openWorldHint`. Un hôte peut s'en servir pour expliquer un appel, mais ces indications n'accordent aucun droit et ne garantissent pas sa sûreté. Les lectures sont marquées comme telles ; enregistrer écrit une version ; déployer, supprimer, installer, modifier un déclencheur ou modifier les paramètres peut remplacer un état existant. Les exécutions réelles et certaines modifications de paramètres peuvent joindre de vrais services. Mettre en service, supprimer, définir un déclencheur, installer une automatisation dans des projets, répondre à la question d’une exécution et modifier les paramètres portent aussi `_meta["anthropic/requiresUserInteraction"]` : un client qui en tient compte demande à la personne avant chacun de ces appels. ### Écriture {#authoring} @@ -182,6 +182,18 @@ Les deux outils de version déployée utilisent le même moteur durable, avec le Chaque réponse porte un `hint` qui nomme l’outil ou le paramètre qui la fait changer. +### Paramètres {#settings} + +| Outil | Ce qu’il fait | +| --- | --- | +| `get_settings` | Sans `kinds`, le catalogue : chaque type de paramètre avec ce qu’il est, ses opérations (`ops`) et ses actions (`acts`), son `baseRisk`, les pages des paramètres où une personne fait la même modification (`areas`), si ce déploiement le sert par MCP (`available`) et si ton rôle peut le lire (`read`) et le modifier (`write`). Avec `kinds` — pour un seul type, aussi `ids` ou le `cursor` de sa page suivante —, chaque ressource que tu peux lire, avec sa `key`, sa `config` et son `hash`. Un type que tu ne peux pas lire figure sous `refused` avec la raison. | +| `plan_settings` | Planifie jusqu’à 32 modifications sans en faire aucune. Chacune indique son `action` (`create`, `update`, `delete`, `act` ou `unchanged`), le `currentHash`, un `diff` membre par membre, ses `effects` et son `risk` (`low`, `high` ou `critical`), ou le refus (`refusal`) qui l’arrête. | +| `apply_settings` | Applique les modifications. `expected` associe la `key` de chaque ressource modifiée au hash que tu as lu, ou `null` pour une ressource que tu crées. Si une modification est refusée ou si une ressource a changé depuis ta lecture, rien n’est appliqué. Sinon, les modifications s’exécutent dans un ordre fixe d’un type à l’autre, et la première qui échoue arrête les suivantes : la réponse indique ce qui a été appliqué (`applied`), ce qui a échoué (`failed`) et ce qui a été ignoré (`skipped`). | + +Une modification indique son type (`kind`), l’`id` de la ressource (absent pour un type qui n’a qu’une ressource) et son opération (`op`) : `set` remplace la ressource par toute la `config` et la crée si elle n’existe pas ; `delete` la supprime ; `act` lance une des actions du type, avec ses `args`. Planifie d’abord, montre le plan à la personne, puis applique les mêmes modifications : `apply_settings` demande à la personne avant chaque appel et dispose de son propre [budget](/fr/develop/rate-limits). + +Aucun secret ne passe par ces outils. Un secret enregistré se lit `{"masked": true, "preview": "…"}` ; renvoie cette valeur telle quelle pour le garder. Une modification qui porte une autre valeur à la place d’un secret, ou des identifiants n’importe où dans sa configuration, est refusée avec `SECRET_ARGUMENT_REFUSED` ; une personne saisit un nouveau secret dans Tale. + ### Capacités & connaissances {#capabilities} | Outil | Ce qu'il fait | @@ -229,6 +241,7 @@ Chaque argument est un seul mot, car des clients comme Claude Code séparent les | Lectures, validation, simulations (y compris `start_run` avec `mode: "mock"`) et tests d'acceptation, recherche de capacités, récupération de connaissances | Appartenance à l'organisation, puis règles habituelles de la ressource | | Répondre à la question d’une exécution | Appartenance à l’organisation ; pour une exécution dans un projet, droit de modifier ce projet | | Noms des secrets d’agent (`list_agent_secrets`) | Rôle Propriétaire, Admin ou Développeur ; les autres reçoivent une liste vide | +| Lire, planifier et modifier les paramètres (`get_settings`, `plan_settings`, `apply_settings`) | Ce que ton rôle permet sur la même page des paramètres ; le catalogue indique ce que ton rôle peut faire de chaque type | | Enregistrer, déployer, supprimer, installer dans des projets, définir/supprimer un déclencheur, annuler ou exécuter réellement | Capacité développeur, puis règles habituelles de la ressource | La clé identifie son titulaire ; elle n'élargit ni son rôle ni son accès aux projets. Une automatisation installée uniquement dans des projets que le titulaire de la clé ne peut pas lire n’apparaît pas dans `list_automations`, et toute lecture de celle-ci répond `AUTOMATION_NOT_FOUND`, comme pour une automatisation qui n’existe pas. Les appels réels via `invoke_capability` passent aussi par les contrôles d'exécution. @@ -251,7 +264,7 @@ Avant de configurer des outils privilégiés, lis `GET /api/v1/me` : `capabiliti | Capacité dont l’`output` porte `status: "waiting"` | L’exécution attend, par exemple une approbation qu’une personne donne dans Tale ; elle n’est ni terminée ni en échec. Interroger `get_run`, sans relancer | | Capacité avec `refused` | Résultat d'erreur ; corriger la cause indiquée | -Les codes de refus comprennent `AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_UNKNOWN`, `AUTOMATION_NOT_DEPLOYED`, `RUN_NOT_FOUND`, `AUTOMATION_INVALID`, `AUTOMATION_TESTS_FAILING`, `AUTOMATION_VERSION_STALE`, `AUTOMATION_DEPLOYMENT_STALE`, `AUTOMATION_NAME_TAKEN`, `AUTOMATION_HAS_ACTIVE_RUNS`, `AUTOMATION_NOT_INSTALLED`, `HUMAN_ASK_NOT_FOUND`, `HUMAN_ASK_NOT_PENDING`, `HUMAN_ASK_EXPIRED`, `EMPTY_ANSWER`, `INVALID_CURSOR`, `LIVE_MODE_UNAVAILABLE` et `NOT_SUPPORTED`. Ce dernier indique que l'hôte ne prend pas en charge l'opération sur les exécutions, versions ou déclencheurs. `start_run` refuse un `idempotencyKey` réutilisé avec d’autres arguments par `IDEMPOTENCY_KEY_REUSED` ; `invoke_capability` refuse un id que le registre ne tient pas — une automatisation seulement enregistrée n’y est pas — par `CAPABILITY_NOT_FOUND` et une entrée que son schéma rejette par `CAPABILITY_INPUT_INVALID` ; `get_knowledge` transmet les codes propres de la porte des connaissances (`KNOWLEDGE_UNAVAILABLE` quand la recherche elle-même a échoué). Les erreurs de plateforme conservent leur code, leur conseil et leurs données éventuelles ; par exemple, l'absence d'accès développeur renvoie `FORBIDDEN_DEVELOPER_SETTINGS`. `INVALID_ARGUMENTS` liste chaque problème d’argument ; une valeur hors d’un ensemble énuméré est refusée et le message nomme l’ensemble. `RATE_LIMITED` signifie que l’outil avait besoin d’une exécution et que le [budget d’exécution](/fr/develop/rate-limits) du détenteur de la clé est épuisé : attends `data.retryAfterMs`. `INTERNAL_ERROR` signifie que l’appel a échoué de façon inattendue ; communique son `data.requestId` à l’équipe qui exploite le déploiement. +Les codes de refus comprennent `AUTOMATION_NOT_FOUND`, `AUTOMATION_VERSION_UNKNOWN`, `AUTOMATION_NOT_DEPLOYED`, `RUN_NOT_FOUND`, `AUTOMATION_INVALID`, `AUTOMATION_TESTS_FAILING`, `AUTOMATION_VERSION_STALE`, `AUTOMATION_DEPLOYMENT_STALE`, `AUTOMATION_NAME_TAKEN`, `AUTOMATION_HAS_ACTIVE_RUNS`, `AUTOMATION_NOT_INSTALLED`, `HUMAN_ASK_NOT_FOUND`, `HUMAN_ASK_NOT_PENDING`, `HUMAN_ASK_EXPIRED`, `EMPTY_ANSWER`, `INVALID_CURSOR`, `LIVE_MODE_UNAVAILABLE` et `NOT_SUPPORTED`. Ce dernier indique que l'hôte ne prend pas en charge l'opération sur les exécutions, versions ou déclencheurs. `start_run` refuse un `idempotencyKey` réutilisé avec d’autres arguments par `IDEMPOTENCY_KEY_REUSED` ; `invoke_capability` refuse un id que le registre ne tient pas — une automatisation seulement enregistrée n’y est pas — par `CAPABILITY_NOT_FOUND` et une entrée que son schéma rejette par `CAPABILITY_INPUT_INVALID` ; `get_knowledge` transmet les codes propres de la porte des connaissances (`KNOWLEDGE_UNAVAILABLE` quand la recherche elle-même a échoué). Les erreurs de plateforme conservent leur code, leur conseil et leurs données éventuelles ; par exemple, l'absence d'accès développeur renvoie `FORBIDDEN_DEVELOPER_SETTINGS`. `INVALID_ARGUMENTS` liste chaque problème d’argument ; une valeur hors d’un ensemble énuméré est refusée et le message nomme l’ensemble. `RATE_LIMITED` signifie que l’outil avait besoin d’une exécution, ou d’une modification de paramètres, et que le [budget](/fr/develop/rate-limits) du détenteur de la clé pour celle-ci est épuisé : attends `data.retryAfterMs`. `INTERNAL_ERROR` signifie que l’appel a échoué de façon inattendue ; communique son `data.requestId` à l’équipe qui exploite le déploiement. Les outils de paramètres ajoutent `SETTINGS_STALE` (une ressource a changé depuis ta lecture ; `data.currentHash` est son hash actuel), `SECRET_ARGUMENT_REFUSED` (une modification portait un secret ; `data.places` dit où, jamais quoi), `SETTINGS_KIND_UNAVAILABLE` (ce déploiement ne sert pas ce type par MCP), `SETTINGS_NOT_FOUND` (une action sur une ressource qui n’existe pas) et `SETTINGS_DUPLICATE` (une ressource modifiée deux fois dans un même appel). Un nom d'automatisation inconnu est aussi une erreur pour `list_versions`, `list_runs` et `list_triggers`. Une liste vide signifie qu'une automatisation existante n'a pas d'éléments correspondants. La seule exception est l’historique des exécutions : une automatisation supprimée conserve ses exécutions, `list_runs {name}` les renvoie donc tant qu’elles existent, et seul un nom qui n’a jamais tourné donne `AUTOMATION_NOT_FOUND`. `get_catalog` restreint à un type de nœud de base (`transform`, `llm`, `agent`, `subautomation`) répond une liste vide accompagnée d’un `hint` renvoyant à `get_docs`, comme le fait `search_catalog`, et de la section de la référence consacrée à ce type de nœud sous `reference`. Un document invalide soumis à un outil qui exige un document valide, une recherche échouée ou un déploiement absent produisent `isError: true`. Seul l'outil de validation présente un document invalide comme son verdict normal. diff --git a/docs/fr/develop/rate-limits.md b/docs/fr/develop/rate-limits.md index cdf582d383..c1d42b0916 100644 --- a/docs/fr/develop/rate-limits.md +++ b/docs/fr/develop/rate-limits.md @@ -15,6 +15,7 @@ Un seau de jetons se remplit en continu jusqu’à sa capacité de rafale. Une c | --- | --- | --- | --- | | Appels généraux `/api/v1`, MCP et endpoints de modèles compris | 120/minute | 200 | Détenteur de la clé | | Démarrages d’exécution, messages au modèle, démarrages de tâche et exécutions MCP | 20/minute | 40 | Détenteur de la clé | +| Modifications de paramètres par MCP (`apply_settings`) | 30/minute | 60 | Détenteur de la clé | | Autorisation de téléversement et rattachement de fichier au projet | 240/minute | 300 | Détenteur de la clé | | Authentification par clé API échouée | 20/minute | 40 | IP source | | Livraisons webhook avant validation du jeton | 120/minute | 240 | Adresse de l’expéditeur | @@ -24,7 +25,7 @@ Les appels REST d’exécution et de téléversement consomment aussi le budget L’exécution comprend les démarrages d’automatisation avec ou sans projet, les messages de fil et les démarrages explicites de tâche. La création ou mise à jour d’une tâche consomme aussi ce budget si `runWorkflowSlug` est fourni. Une requête qui démarre du travail est facturée une fois que son corps et ses en-têtes ont passé les vérifications propres de la porte — un `400 INVALID_BODY` ou `INVALID_HEADER` ne coûte rien — et avant que quoi que ce soit soit cherché, si bien qu’un `404` pour un fil, une tâche ou une automatisation que tu ne peux pas voir coûte un jeton, comme un `409` que l’état répond. Certaines mutations, comme les commentaires de tâche ou les changements de dossier, ont des limites supplémentaires partagées avec l’application. -Dans un lot MCP, les appels d’outil supplémentaires consomment du budget supplémentaire. Le [point d’accès MCP](/fr/develop/mcp-endpoint) distingue une réponse HTTP `429` d’un message refusé à l’intérieur du lot. Un outil MCP qui exécute une automatisation (`run_automation`, `test_automation`, `deploy_automation`, `run_deployed`, `start_run` et `invoke_capability`) consomme en plus une exécution, une fois que le rôle du détenteur de la clé autorise l’appel ; de même pour `answer_run_ask`, dont la réponse relance une exécution en attente, comme la réponse REST. Quand ce budget est épuisé, l’appel reçoit un résultat d’outil dont le `code` est `RATE_LIMITED` et dont `data.retryAfterMs` indique l’attente, et non une réponse HTTP `429`. Les lectures, la validation et l’enregistrement ne consomment aucune exécution. Les webhooks ont des budgets séparés ; les limites de l’expéditeur et du déclencheur doivent toutes deux permettre la livraison. +Dans un lot MCP, les appels d’outil supplémentaires consomment du budget supplémentaire. Le [point d’accès MCP](/fr/develop/mcp-endpoint) distingue une réponse HTTP `429` d’un message refusé à l’intérieur du lot. Un outil MCP qui exécute une automatisation (`run_automation`, `test_automation`, `deploy_automation`, `run_deployed`, `start_run` et `invoke_capability`) consomme en plus une exécution, une fois que le rôle du détenteur de la clé autorise l’appel ; de même pour `answer_run_ask`, dont la réponse relance une exécution en attente, comme la réponse REST. Quand ce budget est épuisé, l’appel reçoit un résultat d’outil dont le `code` est `RATE_LIMITED` et dont `data.retryAfterMs` indique l’attente, et non une réponse HTTP `429`. Les lectures, la validation et l’enregistrement ne consomment aucune exécution. Une modification de paramètres (`apply_settings`) consomme de la même façon une unité de son propre budget de paramètres et reçoit `RATE_LIMITED` dès qu’il est épuisé ; lire et planifier des paramètres n’en consomme pas. Les webhooks ont des budgets séparés ; les limites de l’expéditeur et du déclencheur doivent toutes deux permettre la livraison. Les appels aux [endpoints de modèles](/fr/develop/api-reference#model-endpoints) sous `/api/v1/openai` et `/api/v1/anthropic` ne comptent que dans le budget général, pour une requête chacun, en flux ou non ; ce qu’un appel peut dépenser est plafonné à part par les règles de budget. Une personne, et chaque clé API, peuvent en outre avoir huit de ces appels en cours en même temps : un neuvième reçoit `429` avec le `code` `MODEL_API_CONCURRENCY_EXCEEDED` et `Retry-After: 2`. diff --git a/services/platform/app/features/settings/connectors/components/mcp-endpoint-section.test.tsx b/services/platform/app/features/settings/connectors/components/mcp-endpoint-section.test.tsx index af7e780317..52e027688f 100644 --- a/services/platform/app/features/settings/connectors/components/mcp-endpoint-section.test.tsx +++ b/services/platform/app/features/settings/connectors/components/mcp-endpoint-section.test.tsx @@ -49,6 +49,7 @@ const GROUP_HEADINGS: Record = { authoring: 'Authoring', management: 'Run & trigger management', discovery: 'Discovery', + settings: 'Settings', capability: 'Capabilities & knowledge', }; diff --git a/services/platform/backend/domains/mcp/platform-tools.ts b/services/platform/backend/domains/mcp/platform-tools.ts index d528f99a59..611ea65ff6 100644 --- a/services/platform/backend/domains/mcp/platform-tools.ts +++ b/services/platform/backend/domains/mcp/platform-tools.ts @@ -7,8 +7,10 @@ * The discovery tools list what an automation may name — models, agent * runtimes, skills, connectors, secret names, projects and events — from the * same readers the editor's pickers use, so an agent is offered what a - * person at the editor would be, and nothing of another organization's. No - * answer carries a secret's value. + * person at the editor would be, and nothing of another organization's. The + * settings tools read, plan and change the organization's settings through + * each kind's native reader and writer (`settings/`). No answer carries a + * secret's value. */ import type { Sql } from 'postgres'; @@ -38,6 +40,7 @@ import { import { listConnectedConnectorSlugs } from '../connector_credentials/service.ts'; import { getProjectAuthContext, listProjects } from '../projects/service.ts'; import type { McpCaller } from './caller.ts'; +import { dispatchSettingsTool } from './settings/tools.ts'; /** The run figures the automations metrics page shows — every member reads * them in the app, so every member's agent does. */ @@ -357,6 +360,10 @@ export async function dispatchPlatformTool( return listProjectsTool(sql, caller, params); case 'list_events': return listEvents(); + case 'get_settings': + case 'plan_settings': + case 'apply_settings': + return dispatchSettingsTool(sql, caller, method, params); default: return { error: `unknown platform tool "${method}"`, diff --git a/services/platform/backend/domains/mcp/protocol.test.ts b/services/platform/backend/domains/mcp/protocol.test.ts index 360dac5900..c61a4568bb 100644 --- a/services/platform/backend/domains/mcp/protocol.test.ts +++ b/services/platform/backend/domains/mcp/protocol.test.ts @@ -264,6 +264,10 @@ describe('tools/list', () => { 'list_agent_secrets', 'list_projects', 'list_events', + // The platform's settings tools — read, plan, apply. + 'get_settings', + 'plan_settings', + 'apply_settings', // The platform capability tools — real schemas, a different backend. 'search_capabilities', 'invoke_capability', diff --git a/services/platform/backend/domains/mcp/settings/settings.test.ts b/services/platform/backend/domains/mcp/settings/settings.test.ts index 8be21bedf4..3860aa50b6 100644 --- a/services/platform/backend/domains/mcp/settings/settings.test.ts +++ b/services/platform/backend/domains/mcp/settings/settings.test.ts @@ -422,7 +422,7 @@ describe('plan_settings', () => { }); }); - it('refuses a credential pasted into a setting, wherever it sits, without repeating it', async () => { + it('refuses a credential pasted into a setting, wherever it sits, without repeating it [MCP-R12]', async () => { const state = seeded(); const pasted = 'sk-000000000000000000000000'; const plan = await planSettings(contextFor(), state.registry, [ @@ -492,7 +492,7 @@ describe('apply_settings', () => { expect(state.writes).toEqual([]); }); - it('applies nothing when one resource moved since it was read', async () => { + it('applies nothing when one resource moved since it was read [MCP-R11]', async () => { const state = seeded(); const read = hashOf(state, 'governance/password_policy'); // Ben changes the policy in the app between the agent's read and apply. @@ -607,7 +607,7 @@ describe('apply_settings', () => { }); }); - it('stops at a refused write: what landed stays, the rest is skipped', async () => { + it('stops at a refused write: what landed stays, the rest is skipped [MCP-R11]', async () => { const state = seeded(); state.store.set('provider/refused', { name: 'refused' }); const answer = await applySettings( @@ -744,7 +744,7 @@ describe('apply_settings', () => { expect(state.writes).toEqual([]); }); - it('keeps a stored secret through the masked value it read: read, edit, write back', async () => { + it('keeps a stored secret through the masked value it read: read, edit, write back [MCP-R12]', async () => { const state = seeded(); const read = await getSettings(contextFor(), state.registry, { kinds: ['provider'], @@ -782,7 +782,7 @@ describe('apply_settings', () => { expect(JSON.stringify([read, answer])).not.toContain(SENTINEL); }); - it('refuses a new secret and applies nothing', async () => { + it('refuses a new secret and applies nothing [MCP-R12]', async () => { const state = seeded(); const answer = await applySettings( contextFor(), diff --git a/services/platform/backend/domains/mcp/settings/tools.ts b/services/platform/backend/domains/mcp/settings/tools.ts new file mode 100644 index 0000000000..3e700dfd99 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/tools.ts @@ -0,0 +1,50 @@ +/** + * The settings tools as the MCP endpoint calls them: `get_settings`, + * `plan_settings` and `apply_settings` over the registry of the kinds this + * deployment serves. The call's arguments were checked against the tool's + * schema before it got here; they are read back through the same schema so + * each tool gets them typed. + */ + +import type { Sql } from 'postgres'; + +import { PLATFORM_TOOL_ARGS } from '../../../../lib/mcp/args.ts'; +import type { McpCaller } from '../caller.ts'; +import { applySettings } from './apply.ts'; +import { getSettings } from './get.ts'; +import { planSettings } from './plan.ts'; +import { SETTINGS_HANDLERS, type SettingsRegistry } from './registry.ts'; + +/** One settings tool, acting as the caller in the caller's organization. */ +export async function dispatchSettingsTool( + sql: Sql, + caller: McpCaller, + method: 'get_settings' | 'plan_settings' | 'apply_settings', + params: Record, + registry: SettingsRegistry = SETTINGS_HANDLERS, +): Promise> { + const ctx = { sql, caller }; + switch (method) { + case 'get_settings': + return getSettings( + ctx, + registry, + PLATFORM_TOOL_ARGS.get_settings.parse(params), + ); + case 'plan_settings': + return planSettings( + ctx, + registry, + PLATFORM_TOOL_ARGS.plan_settings.parse(params).changes, + ); + case 'apply_settings': { + const { changes, expected } = + PLATFORM_TOOL_ARGS.apply_settings.parse(params); + return applySettings(ctx, registry, changes, expected); + } + default: { + const unknown: never = method; + throw new Error(`No settings tool "${String(unknown)}"`); + } + } +} diff --git a/services/platform/backend/domains/mcp/spec.md b/services/platform/backend/domains/mcp/spec.md index ec05cb5dd5..b5b0fe36a1 100644 --- a/services/platform/backend/domains/mcp/spec.md +++ b/services/platform/backend/domains/mcp/spec.md @@ -4,8 +4,9 @@ The rules of the door a coding agent uses to work in Tale, `/api/v1/mcp`: whom a call acts as and what the key holder's role lets it read and change, how an agent's save, deploy and runs meet the -editor's rules, how a refusal or a bad argument reaches the agent, what a request and a batch of -calls cost, what is kept of a call, and which protocol revisions the endpoint speaks. The rest of +editor's rules, how a settings change is checked and that no secret travels with it, how a refusal +or a bad argument reaches the agent, what a request and a batch of calls cost, what is kept of a +call, and which protocol revisions the endpoint speaks. The rest of what a call does once it reaches an automation, the capability surface, and the tool inventory itself are not covered; see Not yet. Resources and prompts are reads the tools already answer, and the Tale skill is the one file an agent installs to work here. @@ -175,6 +176,36 @@ answer carries a secret's value. and never its value. Mia lists the projects → Sales is listed with `sales/follow-up`, and nothing of the HR project she is not in. +## Changing settings + +An agent reads the organization's settings, plans a change and applies it through three tools. +Each kind of setting is read and written by the same code the Settings page uses, so the +person's role allows the same changes over MCP as in the app. + +### MCP-R11 · A settings call applies only when each setting is still what the agent read + +Every change names the hash of the setting the agent read, or none for a setting it creates. +Before anything is written, each change is planned again against what is stored now: when one +setting has moved since it was read, or one change is refused, nothing in the call is applied, +and the agent learns the hash stored now (`SETTINGS_STALE`). The changes then run one setting at +a time, each checking its hash again; a failure stops the rest, and the agent is told what was +applied, what failed and what was skipped. + +- **Example**: Ada's agent reads the password policy and plans a longer minimum length; Ben + changes the policy in the app before the agent applies → refused with the policy's current + hash, and the branding change in the same call is not applied either. + +### MCP-R12 · No secret goes into or comes out of a settings call + +A stored secret reads as masked, with a short excerpt at most. A change may send that masked +value back to keep the stored secret, and nothing else in its place; a credential anywhere else +in a change — a key pasted into a description — refuses the change, naming where it was found +and never the value (`SECRET_ARGUMENT_REFUSED`). A person enters a new secret in Tale. + +- **Example**: Ada's agent reads a provider whose key is stored → the key reads as masked; it + changes the address and sends the masked key back → the stored key is kept; it sends a key it + typed instead → refused, and the answer names the field, not the key. + ## Answers and refusals ### MCP-R18 · A refusal comes back as an answer the agent can read, not a protocol error @@ -358,6 +389,9 @@ deployment of a release. A signed-in person downloads it in the app; an agent re a version its agent saves records the door and the key but no client name; a 2026-07-28 client names itself on every call (MCP-R26). - The tool inventory and each tool's arguments (`lib/mcp/tools.ts`, `lib/mcp/args.ts`). +- No kind of setting is served over MCP yet: each arrives with its handler beside the code that + writes it in the app. Until then the catalog lists it as unavailable, and a change to it is + refused (`SETTINGS_KIND_UNAVAILABLE`). - A client cannot subscribe to a resource or be told that a list changed (`subscriptions/listen` answers 404 on 2026-07-28): the lists are read again when a client reconnects, or on 2026-07-28 once the time the answer named has passed. diff --git a/services/platform/backend/domains/mcp/tools.test.ts b/services/platform/backend/domains/mcp/tools.test.ts index 6263ed256a..14dc32d6a7 100644 --- a/services/platform/backend/domains/mcp/tools.test.ts +++ b/services/platform/backend/domains/mcp/tools.test.ts @@ -172,6 +172,16 @@ function readCalls(): Array<[string, Record]> { ['list_agent_secrets', {}], ['list_projects', { includeArchived: true }], ['list_events', {}], + ['get_settings', {}], + ['get_settings', { kinds: ['governance'], ids: ['password_policy'] }], + [ + 'plan_settings', + { + changes: [ + { kind: 'branding', op: 'set', config: { accentColor: '#336699' } }, + ], + }, + ], ['search_capabilities', { query: 'orders' }], ['get_knowledge', { query: 'refunds' }], ]; @@ -286,6 +296,8 @@ describe('tools/list', () => { set_automation_projects: { 'anthropic/requiresUserInteraction': true }, run_deployed: { 'anthropic/maxResultSizeChars': 200_000 }, get_run: { 'anthropic/maxResultSizeChars': 250_000 }, + get_settings: { 'anthropic/maxResultSizeChars': 250_000 }, + apply_settings: { 'anthropic/requiresUserInteraction': true }, }); }); }); @@ -331,3 +343,124 @@ describe('a write over MCP names the coding agent', () => { ]); }); }); + +/** + * The settings tools at the door: a change draws from its own budget once + * its arguments pass, reading and planning draw from none, and what a kind + * does not take is refused with every other problem before anything runs. + */ +describe('settings over MCP', () => { + const apply = findMcpTool('apply_settings'); + const plan = findMcpTool('plan_settings'); + const get = findMcpTool('get_settings'); + if (apply === undefined || plan === undefined || get === undefined) { + throw new Error('no settings tools'); + } + const change = { + changes: [ + { kind: 'branding', op: 'set', config: { accentColor: '#000000' } }, + ], + expected: { branding: null }, + }; + + it('draws one settings change from the key holder’s settings budget', async () => { + const charged: string[] = []; + const reply = await callTool(caller, apply, change, { + host, + requestId: 'r', + charge: async (lane) => { + charged.push(lane); + return null; + }, + }); + if (reply.kind !== 'answer') throw new Error('not admitted'); + expect(charged).toEqual(['rest:settings']); + }); + + it('refuses a change once that budget is spent, and runs nothing', async () => { + const platform = vi.fn(host.platform); + const reply = await callTool(caller, apply, change, { + host: { ...host, platform }, + requestId: 'r', + charge: async () => ({ retryAfterMs: 1500 }), + }); + if (reply.kind !== 'answer') throw new Error('not admitted'); + expect(reply.answer.result.isError).toBe(true); + expect(JSON.parse(reply.answer.result.content[0]?.text ?? '{}')).toEqual({ + error: + 'apply_settings is refused for now: this key holder has changed settings as often as a minute allows; retry in 2 s', + code: 'RATE_LIMITED', + hint: expect.stringContaining('plan_settings'), + data: { retryAfterMs: 1500 }, + }); + expect(platform).not.toHaveBeenCalled(); + }); + + it('charges nothing to read or plan', async () => { + const charge = vi.fn(async () => null); + for (const [tool, args] of [ + [get, {}], + [plan, { changes: change.changes }], + ] as const) { + const reply = await callTool(caller, tool, args, { + host, + requestId: 'r', + charge, + }); + if (reply.kind !== 'answer') throw new Error('not admitted'); + } + expect(charge).not.toHaveBeenCalled(); + }); + + it('refuses what a kind does not take with every other problem, before anything runs', async () => { + const platform = vi.fn(host.platform); + const reply = await callTool( + caller, + plan, + { + changes: [ + { kind: 'governance', id: 'budgets', op: 'delete' }, + { kind: 'branding', op: 'act', act: 'reset' }, + { kind: 'provider', id: 'vendor', op: 'set' }, + { kind: 'provider', id: 'vendor', op: 'act', act: 'rename' }, + { kind: 'files', op: 'set', config: {} }, + ], + }, + { host: { ...host, platform }, requestId: 'r' }, + ); + if (reply.kind !== 'answer') throw new Error('not admitted'); + const answer = JSON.parse(reply.answer.result.content[0]?.text ?? '{}'); + expect(answer.code).toBe('INVALID_ARGUMENTS'); + expect( + answer.data.issues.map( + (issue: { path: string; code: string }) => + `${issue.path} ${issue.code}`, + ), + ).toEqual([ + 'changes.0.op op_not_supported', + 'changes.1.op op_not_supported', + 'changes.2.config required', + 'changes.3.act act_unknown', + 'changes.4.kind invalid_value', + ]); + expect(platform).not.toHaveBeenCalled(); + }); + + it('reads one kind’s pages or ids only, never several kinds’ at once', async () => { + const reply = await callTool( + caller, + get, + { kinds: ['governance', 'branding'], ids: ['budgets'] }, + { host, requestId: 'r' }, + ); + if (reply.kind !== 'answer') throw new Error('not admitted'); + const answer = JSON.parse(reply.answer.result.content[0]?.text ?? '{}'); + expect(answer.data.issues).toEqual([ + { + path: 'kinds', + code: 'one_kind', + message: 'must name exactly one kind when ids or cursor is given', + }, + ]); + }); +}); diff --git a/services/platform/backend/domains/mcp/tools.ts b/services/platform/backend/domains/mcp/tools.ts index 80156ae4f3..292864b038 100644 --- a/services/platform/backend/domains/mcp/tools.ts +++ b/services/platform/backend/domains/mcp/tools.ts @@ -282,24 +282,39 @@ export interface ToolCallContext { /** Asked before the call runs when the request already spent its first * call (a batch); a wait refuses this call at the protocol level. */ readonly admit?: () => Promise<{ retryAfterMs: number } | null>; - /** Draws one execution from the caller's budget for an `execute` tool, - * after its role check; a wait refuses the call as `RATE_LIMITED`. */ + /** Draws one unit from the caller's budget for a tool that executes an + * automation (`rest:execute`) or changes settings (`rest:settings`), after + * its role check; a wait refuses the call as `RATE_LIMITED`. */ readonly charge?: ( - lane: 'rest:execute', + lane: 'rest:execute' | 'rest:settings', ) => Promise<{ retryAfterMs: number } | null>; } -/** The refusal of a call whose execution budget is spent. */ +/** The budget a tool's lane draws from, beyond the request itself. */ +const LANE_BUDGETS = { + execute: 'rest:execute', + settings: 'rest:settings', +} as const; + +/** The refusal of a call whose execution or settings budget is spent. */ function rateLimited( tool: McpToolSpec, retryAfterMs: number, ): Record { - return { - error: `${tool.name} is refused for now: this key holder has started as many executions as a minute allows; retry in ${Math.max(1, Math.ceil(retryAfterMs / 1000))} s`, - code: 'RATE_LIMITED', - hint: 'wait data.retryAfterMs before calling it again; reads, validation and saving do not draw from this budget', - data: { retryAfterMs }, - }; + const wait = Math.max(1, Math.ceil(retryAfterMs / 1000)); + return tool.lane === 'settings' + ? { + error: `${tool.name} is refused for now: this key holder has changed settings as often as a minute allows; retry in ${wait} s`, + code: 'RATE_LIMITED', + hint: 'wait data.retryAfterMs before calling it again; get_settings and plan_settings do not draw from this budget', + data: { retryAfterMs }, + } + : { + error: `${tool.name} is refused for now: this key holder has started as many executions as a minute allows; retry in ${wait} s`, + code: 'RATE_LIMITED', + hint: 'wait data.retryAfterMs before calling it again; reads, validation and saving do not draw from this budget', + data: { retryAfterMs }, + }; } /** What the protocol layer answers a `tools/call` with: a tool result, or — @@ -349,8 +364,8 @@ export async function callTool( }; } } - if (tool.lane === 'execute' && context.charge !== undefined) { - const wait = await context.charge('rest:execute'); + if (tool.lane !== 'api' && context.charge !== undefined) { + const wait = await context.charge(LANE_BUDGETS[tool.lane]); if (wait !== null) { return { kind: 'answer', diff --git a/services/platform/backend/lib/rate-limit.ts b/services/platform/backend/lib/rate-limit.ts index 6c43916e18..0f5bf7e3b2 100644 --- a/services/platform/backend/lib/rate-limit.ts +++ b/services/platform/backend/lib/rate-limit.ts @@ -205,6 +205,15 @@ export const RATE_LIMITS = { period: MINUTE, capacity: 40, }, + // Settings changes over MCP (`apply_settings`): a coding agent loops, and + // every change runs a native writer that may snapshot a history file or + // reach a vendor, so a key holder's changes have a budget of their own. + 'rest:settings': { + kind: 'token bucket', + rate: 30, + period: MINUTE, + capacity: 60, + }, // The sandbox-device door: a join token or device secret that matches // nothing is charged to its source IP — the trusted-headers posture. 'sandbox-devices:auth-fail-ip': { diff --git a/services/platform/backend/rest/v1-mcp.ts b/services/platform/backend/rest/v1-mcp.ts index 79aba3d383..18e0d499c9 100644 --- a/services/platform/backend/rest/v1-mcp.ts +++ b/services/platform/backend/rest/v1-mcp.ts @@ -31,7 +31,7 @@ import { DEFAULT_BODY_BYTES, restBodyLimit, type RestEnv } from './shared.ts'; * wait when the budget is spent. */ async function chargeLane( sql: Sql, - lane: 'rest:api' | 'rest:execute', + lane: 'rest:api' | 'rest:execute' | 'rest:settings', userId: string, ): Promise<{ retryAfterMs: number } | null> { try { @@ -110,7 +110,8 @@ export function createRestMcpRoutes(deps: { sql: Sql }): Hono { // never cheaper than the requests it stands for. admit: () => chargeLane(deps.sql, 'rest:api', caller.userId), // A tool that executes an automation draws one execution from the - // budget the REST API's run starts draw from, after its role check. + // budget the REST API's run starts draw from, and a settings change + // one change from its own, after the tool's role check. charge: (lane) => chargeLane(deps.sql, lane, caller.userId), }); }); diff --git a/services/platform/lib/mcp/args.ts b/services/platform/lib/mcp/args.ts index e4f2b8e14b..1d3f4d00a6 100644 --- a/services/platform/lib/mcp/args.ts +++ b/services/platform/lib/mcp/args.ts @@ -1,4 +1,9 @@ import { automationSettingsSchema } from '@tale/shared/schemas/automation-settings'; +import { expectedConfigurationHashSchema } from '@tale/shared/schemas/configuration'; +import { + SETTINGS_KINDS, + settingsKindDescriptor, +} from '@tale/shared/schemas/settings-kinds'; import { taskSubjectContractSchema } from '@tale/shared/schemas/task-contract'; import { z } from 'zod'; @@ -432,6 +437,95 @@ export const ENGINE_TOOL_ARGS = { const listingQuery = (description: string) => nonBlank().max(200).optional().describe(description); +/** A settings kind, as the shared descriptors name them. */ +const settingsKind = z + .enum(SETTINGS_KINDS.map((descriptor) => descriptor.kind)) + .describe('The kind of setting; get_settings without kinds lists them.'); + +/** A resource's id within its kind. */ +const settingsId = nonBlank().max(600); + +/** + * One settings change. Which operations and actions a kind takes is the + * kind's own (`settings-kinds.ts`), so a call that names one it does not + * take is refused with the others, before anything is read. + */ +const settingsChange = z + .strictObject({ + kind: settingsKind, + id: settingsId + .optional() + .describe( + "The resource's id within its kind, as get_settings answers it. Left out for a kind with one resource.", + ), + op: z + .enum(['set', 'delete', 'act']) + .describe( + "set: replace the resource with config, creating it when absent; delete: remove it; act: run one of the kind's actions on it.", + ), + config: z + .unknown() + .optional() + .describe( + 'With set: the whole config the resource should hold, as get_settings answers it. A secret stays the masked value it read, which keeps what is stored.', + ), + act: nonBlank() + .max(64) + .optional() + .describe("With act: the action, one of the kind's acts."), + args: z.unknown().optional().describe('With act: what the action takes.'), + }) + .superRefine((change, ctx) => { + const { acts, ops } = settingsKindDescriptor(change.kind); + const issue = (path: string, code: string, message: string) => + ctx.addIssue({ code: 'custom', path: [path], message, params: { code } }); + if (change.op === 'act') { + if (acts.length === 0) { + issue( + 'op', + 'op_not_supported', + `${change.kind} takes ${ops.join(' or ')}`, + ); + } else if (change.act === undefined) { + issue('act', 'required', 'is required with op "act"'); + } else if (!acts.includes(change.act)) { + issue( + 'act', + 'act_unknown', + `is not an action of ${change.kind}: ${acts.join(', ')}`, + ); + } + } else { + if (!ops.includes(change.op)) { + issue( + 'op', + 'op_not_supported', + `${change.kind} takes ${[...ops, ...(acts.length > 0 ? ['act'] : [])].join(' or ')}`, + ); + } + if (change.act !== undefined) { + issue('act', 'not_allowed', 'is taken only with op "act"'); + } + if (change.args !== undefined) { + issue('args', 'not_allowed', 'is taken only with op "act"'); + } + } + if (change.op === 'set' && change.config === undefined) { + issue( + 'config', + 'required', + 'is required with op "set": the whole config the resource should hold', + ); + } + if (change.op !== 'set' && change.config !== undefined) { + issue('config', 'not_allowed', 'is taken only with op "set"'); + } + }); + +/** The changes of one plan or apply. */ +const settingsChanges = (description: string) => + z.array(settingsChange).min(1).max(32).describe(description); + /** The arguments of the platform tools — answered by the platform itself, * not the automation engine. */ export const PLATFORM_TOOL_ARGS = { @@ -485,6 +579,57 @@ export const PLATFORM_TOOL_ARGS = { .describe('Also archived projects (default false).'), }), list_events: z.strictObject({}), + get_settings: z + .strictObject({ + kinds: z + .array(settingsKind) + .min(1) + .max(SETTINGS_KINDS.length) + .optional() + .describe( + 'The kinds to read. Left out, the catalog: every kind, what it is and what your role may do with it.', + ), + ids: z + .array(settingsId) + .min(1) + .max(100) + .optional() + .describe('Only these resources, by id; with exactly one kind.'), + cursor: nonBlank() + .max(1000) + .optional() + .describe( + 'The nextCursor a read of one kind answered, for its next page.', + ), + }) + .superRefine((args, ctx) => { + if ( + (args.ids !== undefined || args.cursor !== undefined) && + args.kinds?.length !== 1 + ) { + ctx.addIssue({ + code: 'custom', + path: ['kinds'], + message: 'must name exactly one kind when ids or cursor is given', + params: { code: 'one_kind' }, + }); + } + }), + plan_settings: z.strictObject({ + changes: settingsChanges( + 'The changes to plan, at most 32: each names its kind, its resource (id) and its operation; set sends the whole config the resource should hold.', + ), + }), + apply_settings: z.strictObject({ + changes: settingsChanges( + 'The changes to make, at most 32 — the ones you planned and showed the person.', + ), + expected: z + .record(nonBlank().max(700), expectedConfigurationHashSchema) + .describe( + 'The hash each changed resource had when you read it, by its key (kind/id, or the kind alone for a kind with one resource); null for one you create. If any resource changed since, nothing is applied.', + ), + }), } satisfies Record; /** The arguments of the organization's capability tools. */ diff --git a/services/platform/lib/mcp/contract-fingerprint.json b/services/platform/lib/mcp/contract-fingerprint.json index ec211c62e2..d931030adf 100644 --- a/services/platform/lib/mcp/contract-fingerprint.json +++ b/services/platform/lib/mcp/contract-fingerprint.json @@ -1,4 +1,4 @@ { - "version": "3.27.0", - "fingerprint": "e2315379ceaeff4ede857d9fe0396e36c1caa22c18f01644ade96de0fdf6b9c9" + "version": "3.28.0", + "fingerprint": "5f86c9e9e8038d4272206f3808bea5471a9f8be1f4d6ebfcc825be6e639b02e0" } diff --git a/services/platform/lib/mcp/endpoint-docs.test.ts b/services/platform/lib/mcp/endpoint-docs.test.ts index f8b2d05eea..c1cf9e2a79 100644 --- a/services/platform/lib/mcp/endpoint-docs.test.ts +++ b/services/platform/lib/mcp/endpoint-docs.test.ts @@ -32,6 +32,7 @@ const GROUP_ANCHORS: Record = { authoring: 'authoring', management: 'management', discovery: 'discovery', + settings: 'settings', capability: 'capabilities', }; diff --git a/services/platform/lib/mcp/instructions.test.ts b/services/platform/lib/mcp/instructions.test.ts index 152e9bba66..e9a326b53f 100644 --- a/services/platform/lib/mcp/instructions.test.ts +++ b/services/platform/lib/mcp/instructions.test.ts @@ -14,18 +14,14 @@ import { import { MCP_TOOLS } from './tools'; /** - * The lines the instructions gain once the settings tools, agent requests - * and subscriptions ship, as long as they are planned to be. A client keeps - * only the first 2,048 characters, so the limit holds for the full set: the - * text today leaves their room, and none of them has to cut it to land. A - * line moves into `INSTRUCTION_FRAGMENTS`, with its final words, together - * with its tools. + * The lines the instructions gain once agent requests and subscriptions + * ship, as long as they are planned to be. A client keeps only the first + * 2,048 characters, so the limit holds for the full set: the text today + * leaves their room, and none of them has to cut it to land. A line moves + * into `INSTRUCTION_FRAGMENTS`, with its final words, together with its + * tools. */ const LATER_FRAGMENTS: readonly InstructionFragment[] = [ - { - text: "Settings: get_settings -> plan_settings -> show the plan -> apply_settings with each resource's expected hash.", - tools: ['get_settings', 'plan_settings', 'apply_settings'], - }, { text: 'Never ask for, accept or print a secret (API keys, tokens, passwords). A change that needs one returns a link where the person finishes it in Tale; poll get_agent_request.', tools: ['get_agent_request'], diff --git a/services/platform/lib/mcp/instructions.ts b/services/platform/lib/mcp/instructions.ts index cd4489f34c..4732ccd5b8 100644 --- a/services/platform/lib/mcp/instructions.ts +++ b/services/platform/lib/mcp/instructions.ts @@ -74,6 +74,10 @@ export const INSTRUCTION_FRAGMENTS: readonly InstructionFragment[] = [ text: 'Approvals are human-only; never try to decide one.', tools: [], }, + { + text: "Settings: get_settings -> plan_settings -> show the plan -> apply_settings with each resource's expected hash.", + tools: ['get_settings', 'plan_settings', 'apply_settings'], + }, { text: "A failed run: read it with get_run, fix the document, reproduce with run_automation and the run's input.", tools: ['get_run', 'run_automation'], diff --git a/services/platform/lib/mcp/results.ts b/services/platform/lib/mcp/results.ts index 01801228fa..8c9a4b8c8a 100644 --- a/services/platform/lib/mcp/results.ts +++ b/services/platform/lib/mcp/results.ts @@ -141,6 +141,44 @@ export const READ_TOOL_RESULTS = { ), hint: z.string(), }), + get_settings: z.looseObject({ + kinds: z + .array( + z.looseObject({ + kind: z.string(), + available: z.boolean(), + read: z.boolean(), + write: z.boolean(), + }), + ) + .optional(), + resources: z.array( + z.looseObject({ + kind: z.string(), + key: z.string(), + id: z.string().nullable(), + hash: z.string(), + }), + ), + refused: z.array( + z.looseObject({ kind: z.string(), code: z.string(), error: z.string() }), + ), + nextCursor: z.string().nullable(), + hint: z.string(), + }), + plan_settings: z.looseObject({ + ok: z.boolean(), + changes: z.array( + z.looseObject({ + kind: z.string(), + key: z.string(), + op: z.string(), + diff: z.array(z.looseObject({ path: z.string() })), + effects: z.array(z.string()), + risk: z.string(), + }), + ), + }), search_capabilities: z.looseObject({ capabilities: z.array(z.looseObject({ id: z.string() })), }), diff --git a/services/platform/lib/mcp/skill.snapshot.md b/services/platform/lib/mcp/skill.snapshot.md index 4e59555b75..63776f444a 100644 --- a/services/platform/lib/mcp/skill.snapshot.md +++ b/services/platform/lib/mcp/skill.snapshot.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Needs Tale's MCP server connected (https:///api/v1/mcp); works with any MCP client that reads skills." metadata: publisher: tale - contract: "3.27.0" + contract: "3.28.0" --- # Tale diff --git a/services/platform/lib/mcp/tools.schema.snapshot.json b/services/platform/lib/mcp/tools.schema.snapshot.json index 0fb2ba5950..bfd6684799 100644 --- a/services/platform/lib/mcp/tools.schema.snapshot.json +++ b/services/platform/lib/mcp/tools.schema.snapshot.json @@ -1364,6 +1364,343 @@ "additionalProperties": {} } }, + "get_settings": { + "inputSchema": { + "type": "object", + "properties": { + "kinds": { + "description": "The kinds to read. Left out, the catalog: every kind, what it is and what your role may do with it.", + "minItems": 1, + "maxItems": 10, + "type": "array", + "items": { + "type": "string", + "enum": [ + "provider", + "provider-credential", + "governance", + "knowledge-embedding", + "branding", + "project-instructions", + "agent-instructions", + "agent-tools", + "task-instructions", + "deployment" + ], + "description": "The kind of setting; get_settings without kinds lists them." + } + }, + "ids": { + "description": "Only these resources, by id; with exactly one kind.", + "minItems": 1, + "maxItems": 100, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 600, + "pattern": "\\S" + } + }, + "cursor": { + "description": "The nextCursor a read of one kind answered, for its next page.", + "type": "string", + "minLength": 1, + "maxLength": 1000, + "pattern": "\\S" + } + }, + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "properties": { + "kinds": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "available": { + "type": "boolean" + }, + "read": { + "type": "boolean" + }, + "write": { + "type": "boolean" + } + }, + "required": ["kind", "available", "read", "write"], + "additionalProperties": {} + } + }, + "resources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "key": { + "type": "string" + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "hash": { + "type": "string" + } + }, + "required": ["kind", "key", "id", "hash"], + "additionalProperties": {} + } + }, + "refused": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "code": { + "type": "string" + }, + "error": { + "type": "string" + } + }, + "required": ["kind", "code", "error"], + "additionalProperties": {} + } + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "hint": { + "type": "string" + } + }, + "required": ["resources", "refused", "nextCursor", "hint"], + "additionalProperties": {} + } + }, + "plan_settings": { + "inputSchema": { + "type": "object", + "properties": { + "changes": { + "minItems": 1, + "maxItems": 32, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "provider", + "provider-credential", + "governance", + "knowledge-embedding", + "branding", + "project-instructions", + "agent-instructions", + "agent-tools", + "task-instructions", + "deployment" + ], + "description": "The kind of setting; get_settings without kinds lists them." + }, + "id": { + "description": "The resource's id within its kind, as get_settings answers it. Left out for a kind with one resource.", + "type": "string", + "minLength": 1, + "maxLength": 600, + "pattern": "\\S" + }, + "op": { + "type": "string", + "enum": ["set", "delete", "act"], + "description": "set: replace the resource with config, creating it when absent; delete: remove it; act: run one of the kind's actions on it." + }, + "config": { + "description": "With set: the whole config the resource should hold, as get_settings answers it. A secret stays the masked value it read, which keeps what is stored." + }, + "act": { + "description": "With act: the action, one of the kind's acts.", + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "\\S" + }, + "args": { + "description": "With act: what the action takes." + } + }, + "required": ["kind", "op"], + "additionalProperties": false + }, + "description": "The changes to plan, at most 32: each names its kind, its resource (id) and its operation; set sends the whole config the resource should hold." + } + }, + "required": ["changes"], + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "changes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "key": { + "type": "string" + }, + "op": { + "type": "string" + }, + "diff": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + } + }, + "required": ["path"], + "additionalProperties": {} + } + }, + "effects": { + "type": "array", + "items": { + "type": "string" + } + }, + "risk": { + "type": "string" + } + }, + "required": ["kind", "key", "op", "diff", "effects", "risk"], + "additionalProperties": {} + } + } + }, + "required": ["ok", "changes"], + "additionalProperties": {} + } + }, + "apply_settings": { + "inputSchema": { + "type": "object", + "properties": { + "changes": { + "minItems": 1, + "maxItems": 32, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "provider", + "provider-credential", + "governance", + "knowledge-embedding", + "branding", + "project-instructions", + "agent-instructions", + "agent-tools", + "task-instructions", + "deployment" + ], + "description": "The kind of setting; get_settings without kinds lists them." + }, + "id": { + "description": "The resource's id within its kind, as get_settings answers it. Left out for a kind with one resource.", + "type": "string", + "minLength": 1, + "maxLength": 600, + "pattern": "\\S" + }, + "op": { + "type": "string", + "enum": ["set", "delete", "act"], + "description": "set: replace the resource with config, creating it when absent; delete: remove it; act: run one of the kind's actions on it." + }, + "config": { + "description": "With set: the whole config the resource should hold, as get_settings answers it. A secret stays the masked value it read, which keeps what is stored." + }, + "act": { + "description": "With act: the action, one of the kind's acts.", + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "\\S" + }, + "args": { + "description": "With act: what the action takes." + } + }, + "required": ["kind", "op"], + "additionalProperties": false + }, + "description": "The changes to make, at most 32 — the ones you planned and showed the person." + }, + "expected": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 700, + "pattern": "\\S" + }, + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "pattern": "^[a-f0-9]{64}(?![\\s\\S])" + }, + { + "type": "null" + } + ] + }, + "description": "The hash each changed resource had when you read it, by its key (kind/id, or the kind alone for a kind with one resource); null for one you create. If any resource changed since, nothing is applied." + } + }, + "required": ["changes", "expected"], + "additionalProperties": false + } + }, "search_capabilities": { "inputSchema": { "type": "object", diff --git a/services/platform/lib/mcp/tools.test.ts b/services/platform/lib/mcp/tools.test.ts index 43d38f37eb..e4a21bd1a2 100644 --- a/services/platform/lib/mcp/tools.test.ts +++ b/services/platform/lib/mcp/tools.test.ts @@ -62,6 +62,11 @@ describe('MCP tool grouping', () => { 'list_projects', 'list_events', ]); + expect(byGroup('settings')).toEqual([ + 'get_settings', + 'plan_settings', + 'apply_settings', + ]); expect(byGroup('capability')).toEqual([ 'search_capabilities', 'invoke_capability', @@ -131,6 +136,9 @@ describe('MCP tool annotations', () => { list_agent_secrets: { ...READ, idempotentHint: true }, list_projects: { ...READ, idempotentHint: true }, list_events: { ...READ, idempotentHint: true }, + get_settings: { ...READ, idempotentHint: true }, + plan_settings: { ...READ, idempotentHint: true }, + apply_settings: hints(false, true, false, true), search_capabilities: { ...READ, idempotentHint: true }, invoke_capability: hints(false, true, false, true), get_knowledge: { ...READ, idempotentHint: true }, @@ -166,6 +174,7 @@ describe('MCP tool annotations', () => { 'invoke_capability', 'run_automation', 'test_automation', + 'apply_settings', ]); for (const tool of MCP_TOOLS) { expect(tool.annotations.readOnlyHint, tool.name).toBe( @@ -277,6 +286,14 @@ describe('MCP tool roles and budgets', () => { ]); }); + test('a settings change draws from the settings budget; planning one does not', () => { + expect( + MCP_TOOLS.filter((tool) => tool.lane === 'settings').map( + (tool) => tool.name, + ), + ).toEqual(['apply_settings']); + }); + test('a read never draws from it', () => { for (const tool of MCP_TOOLS) { if (tool.annotations.readOnlyHint) { @@ -315,7 +332,7 @@ describe('MCP tool answers and client hints', () => { } }); - test('putting a version live, deleting, installing, binding a trigger and answering for a person ask the person before every call', () => { + test('putting a version live, deleting, installing, binding a trigger, answering for a person and changing settings ask the person before every call', () => { expect( MCP_TOOLS.filter((tool) => tool.requiresUserInteraction).map( (tool) => tool.name, @@ -326,6 +343,7 @@ describe('MCP tool answers and client hints', () => { 'set_trigger', 'answer_run_ask', 'set_automation_projects', + 'apply_settings', ]); for (const tool of MCP_TOOLS) { if (tool.annotations.readOnlyHint) { diff --git a/services/platform/lib/mcp/tools.ts b/services/platform/lib/mcp/tools.ts index da33ad17e4..117861dfe7 100644 --- a/services/platform/lib/mcp/tools.ts +++ b/services/platform/lib/mcp/tools.ts @@ -30,6 +30,7 @@ export const MCP_TOOL_GROUPS = [ 'authoring', 'management', 'discovery', + 'settings', 'capability', ] as const; @@ -70,14 +71,16 @@ export interface McpToolSpec { readonly group: McpToolGroup; /** Who may call it, checked before it runs: `developer` takes the owner, * admin or developer role (the in-app equivalent's bar); `member` leaves it - * to the surface's own rules; `live-developer` takes the developer bar for - * a live call (`mode: "live"`, the default) and leaves a mock one to every - * member. A tool a role cannot use stays listed. */ + * to the surface's own rules (each settings kind's native writer decides + * for itself); `live-developer` takes the developer bar for a live call + * (`mode: "live"`, the default) and leaves a mock one to every member. A + * tool a role cannot use stays listed. */ readonly role: 'member' | 'developer' | 'live-developer'; /** The budget a call draws from once its role check passed: `api` only * the request the door already charged; `execute` also one execution - * (`rest:execute`, the REST API's run-start budget). */ - readonly lane: 'api' | 'execute'; + * (`rest:execute`, the REST API's run-start budget); `settings` also one + * settings change (`rest:settings`). */ + readonly lane: 'api' | 'execute' | 'settings'; /** What every answer that is not a refusal carries — read tools only: * `tools/list` advertises it as the `outputSchema`, and the answer carries * it as `structuredContent` beside the same JSON as text. */ @@ -94,14 +97,15 @@ export interface McpToolSpec { } /** Tools that put a version live, decide what starts one or where it runs, - * remove one, or speak for a person: a client asks the person before each - * call, whatever its permission mode. */ + * remove one, speak for a person or change the organization's settings: a + * client asks the person before each call, whatever its permission mode. */ const ASK_FIRST_TOOLS: ReadonlySet = new Set([ 'deploy_automation', 'delete_automation', 'set_trigger', 'answer_run_ask', 'set_automation_projects', + 'apply_settings', ]); /** The tools whose answers run long — the reference, the catalog, an @@ -115,6 +119,7 @@ const MAX_RESULT_CHARS: Readonly> = { get_automation: 200_000, run_deployed: 200_000, get_run: 250_000, + get_settings: 250_000, }; const RESULTS: ReadonlyMap = new Map( @@ -134,7 +139,9 @@ function withContract(spec: Omit): McpToolSpec { return Object.assign(spec, { lane: EXECUTE_TOOLS.has(spec.name) ? ('execute' as const) - : ('api' as const), + : SETTINGS_WRITE_TOOLS.has(spec.name) + ? ('settings' as const) + : ('api' as const), result: RESULTS.get(spec.name) ?? null, requiresUserInteraction: ASK_FIRST_TOOLS.has(spec.name), ...(maxResultChars === undefined ? {} : { maxResultChars }), @@ -181,6 +188,11 @@ const EXECUTE_TOOLS: ReadonlySet = new Set([ 'invoke_capability', ]); +/** Tools that change the organization's settings and draw from the settings + * budget (`rest:settings`): an agent loops, and every change runs a native + * writer that may snapshot a history file or reach a vendor. */ +const SETTINGS_WRITE_TOOLS: ReadonlySet = new Set(['apply_settings']); + /** A read: changes nothing, repeats freely, stays inside the platform. */ const READ: McpToolAnnotations = { readOnlyHint: true, @@ -242,6 +254,17 @@ const EXECUTE_MOCK: McpToolAnnotations = { openWorldHint: false, }; +/** A settings change: it may replace or remove what exists, repeating one is + * no no-op (an action runs again; a change whose hash moved is refused), and + * some kinds reach outside the platform — an invitation e-mails a person, a + * connector check reaches its vendor. */ +const SETTINGS_WRITE: McpToolAnnotations = { + readOnlyHint: false, + destructiveHint: true, + idempotentHint: false, + openWorldHint: true, +}; + /** Every engine method's annotations — exhaustive over `Method`, so a new * method cannot ship without saying what it does to the world. */ const METHOD_ANNOTATIONS: Record = { @@ -318,7 +341,10 @@ const METHOD_DESCRIPTIONS: Record = { * writes one, so it belongs with the trigger management, not the authoring * loop). Exhaustive over `Method`, so a new engine method cannot ship * unclassified. */ -const METHOD_GROUPS: Record> = { +const METHOD_GROUPS: Record< + Method, + Exclude +> = { get_docs: 'authoring', get_catalog: 'authoring', search_catalog: 'authoring', @@ -402,6 +428,27 @@ const PLATFORM_TOOLS = [ annotations: READ, group: 'discovery', }, + { + name: 'get_settings', + description: + "The organization's settings your role may read. Without kinds: the catalog — each kind, what it is, its operations and actions, its risk, whether this deployment serves it and whether your role may read and change it. With kinds (and ids): each resource with its key, its config and its hash, the value apply_settings expects. A secret never comes back: it reads as {masked: true, preview}; send that back unchanged to keep it.", + annotations: READ, + group: 'settings', + }, + { + name: 'plan_settings', + description: + 'Plan settings changes without making any: for each, what it would do (create, update, delete, act or unchanged), the diff member by member, its effects and its risk — or why it is refused. Show the plan to the person, then call apply_settings with the same changes.', + annotations: READ, + group: 'settings', + }, + { + name: 'apply_settings', + description: + "Make the settings changes you planned and showed the person. expected names each changed resource's key with the hash you read (null for one you create): if any resource changed since, or any change is refused, nothing is applied. Changes run in a fixed order across kinds; one that fails stops the rest, and the answer lists what was applied, what failed and what was skipped. Never send a secret: a person enters it in Tale.", + annotations: SETTINGS_WRITE, + group: 'settings', + }, ] as const satisfies ReadonlyArray<{ name: keyof typeof PLATFORM_TOOL_ARGS; description: string; @@ -441,8 +488,8 @@ const CAPABILITY_TOOL_ANNOTATIONS: Record< /** * Every tool this endpoint serves, in the order it advertises them: the engine's * method table first (authoring, then management, exactly as the engine lists - * them), then the platform's own reads (its management read, then - * discovery), then the capability tools. + * them), then the platform's own tools (its management read, discovery, + * then settings), then the capability tools. */ export const MCP_TOOLS: readonly McpToolSpec[] = [ ...METHODS.map((name) => diff --git a/services/platform/lib/shared/constants/api-contract.ts b/services/platform/lib/shared/constants/api-contract.ts index d8af86f1ff..e4d6154e56 100644 --- a/services/platform/lib/shared/constants/api-contract.ts +++ b/services/platform/lib/shared/constants/api-contract.ts @@ -537,5 +537,25 @@ * recorded with the call and on the versions and audit rows it writes. * No other REST operation changes. A script that matched the -32602 * argument error, or read the indented text, reads the tool result instead. + * + * 3.28.0 — 2026-10-09: the MCP endpoint reads, plans and changes the + * organization's settings, in a new `settings` group. `get_settings` + * answers, without `kinds`, the catalog of setting kinds (what each is, its + * `ops` and `acts`, `baseRisk`, the Settings pages it covers, whether this + * deployment serves it and what the caller's role may do) and, with + * `kinds`, each resource the caller may read with its `key`, `config` and + * native `hash`, a secret reading as `{masked: true, preview}`. + * `plan_settings` answers each change's `action`, `currentHash`, `diff`, + * `effects` and `risk`, or its `refusal`, and writes nothing. + * `apply_settings` is compare-and-set: `expected` names every changed + * resource's hash (null for one it creates); a refused change or a resource + * that moved applies nothing (`SETTINGS_STALE` with `data.currentHash`); + * changes run in a fixed order across kinds and the first failure stops the + * rest, the answer naming what was `applied`, what `failed` and what was + * `skipped`. It asks the person before every call and draws from a new + * `rest:settings` budget (30 a minute, 60 at once). No argument may carry a + * secret (`SECRET_ARGUMENT_REFUSED`); further codes `SETTINGS_KIND_UNAVAILABLE`, + * `SETTINGS_NOT_FOUND` and `SETTINGS_DUPLICATE`. The server instructions + * name the settings loop. No REST operation changes. */ -export const API_CONTRACT_VERSION = '3.27.0'; +export const API_CONTRACT_VERSION = '3.28.0'; diff --git a/services/platform/messages/de/settings.yml b/services/platform/messages/de/settings.yml index 1e94ca4ba3..98c69826b3 100644 --- a/services/platform/messages/de/settings.yml +++ b/services/platform/messages/de/settings.yml @@ -81,6 +81,10 @@ mcpEndpoint: description: Nachsehen, was eine Automatisierung nennen darf — Modelle, Agent-Laufzeiten, Skills, Connectors, Namen von Secrets, Projekte und Ereignisse. + settings: + title: Einstellungen + description: Die Einstellungen lesen, planen und ändern, die deine Rolle + erlaubt. Secrets gibst du immer in Tale ein. capability: title: Capabilities & Wissen description: Die eigene Oberfläche der Organisation — durchsuchen, was diff --git a/services/platform/messages/en/settings.yml b/services/platform/messages/en/settings.yml index abbb43a5be..3a5eb89ee8 100644 --- a/services/platform/messages/en/settings.yml +++ b/services/platform/messages/en/settings.yml @@ -78,6 +78,10 @@ mcpEndpoint: title: Discovery description: Look up what an automation may name — models, agent runtimes, skills, connectors, secret names, projects and events. + settings: + title: Settings + description: Read, plan and change the settings your role allows. + Secrets are always entered in Tale. capability: title: Capabilities & knowledge description: This organization's own surface — search what it can do, diff --git a/services/platform/messages/fr/settings.yml b/services/platform/messages/fr/settings.yml index 4cb14c351f..94da371ad1 100644 --- a/services/platform/messages/fr/settings.yml +++ b/services/platform/messages/fr/settings.yml @@ -83,6 +83,10 @@ mcpEndpoint: description: Consulter ce qu'une automatisation peut nommer — modèles, environnements d'agent, skills, connectors, noms de secrets, projets et événements. + settings: + title: Paramètres + description: Lire, planifier et modifier les paramètres que ton rôle + autorise. Les secrets se saisissent toujours dans Tale. capability: title: Capacités & connaissances description: La surface propre à l'organisation — chercher ce qu'elle diff --git a/services/platform/public/openapi.json b/services/platform/public/openapi.json index 86a0af58b6..41df6b349f 100644 --- a/services/platform/public/openapi.json +++ b/services/platform/public/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "Tale Platform API", - "version": "3.27.0", + "version": "3.28.0", "contact": { "name": "Tale", "url": "https://tale.dev" @@ -39477,7 +39477,7 @@ "description": "The version of this contract (`info.version`) the serving instance implements — semver for the wire", "schema": { "type": "string", - "example": "3.27.0" + "example": "3.28.0" } }, "Location": { diff --git a/services/platform/scripts/openapi/contract-fingerprint.json b/services/platform/scripts/openapi/contract-fingerprint.json index 654d34c2d8..7316328883 100644 --- a/services/platform/scripts/openapi/contract-fingerprint.json +++ b/services/platform/scripts/openapi/contract-fingerprint.json @@ -1,5 +1,5 @@ { - "version": "3.27.0", + "version": "3.28.0", "operations": "26c9424b511a9ddaac1a98af5ae5b14a95502e15fd7ed39ff7bfba6cb02de6e6", "schemas": "5d6d0095d67ad88656e35fdea3f9c05c8f68e1d73008beb0d5b28d8154ddf978" } From f51c872e3ab8d854074b6a503ace19a1750e68bf Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 18:48:35 +0200 Subject: [PATCH 09/35] test(platform): hold every Settings page to its MCP story MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new guard reads the settings rail — its rows, and the tabs of the rows that open tabs (governance, metrics, API) — and holds every page to one story. A settings kind names the page among its areas, or `backend/domains/mcp/settings/coverage.ts` says what an agent cannot change there yet (planned) or why the page holds nothing to change (not exposed). It also holds the shared list of Settings pages to the rail in both directions, the mobile overview to the desktop rail, and one story per page, each reason a sentence. Ten pages are covered by the kinds described so far, the MCP page holds nothing to change, and the other twenty-two say what is missing. A page added to the rail without its story fails the guard. --- .../domains/mcp/settings/coverage.test.ts | 117 ++++++++++++++++++ .../backend/domains/mcp/settings/coverage.ts | 55 ++++++++ 2 files changed, 172 insertions(+) create mode 100644 services/platform/backend/domains/mcp/settings/coverage.test.ts create mode 100644 services/platform/backend/domains/mcp/settings/coverage.ts diff --git a/services/platform/backend/domains/mcp/settings/coverage.test.ts b/services/platform/backend/domains/mcp/settings/coverage.test.ts new file mode 100644 index 0000000000..18e03b0627 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/coverage.test.ts @@ -0,0 +1,117 @@ +// @vitest-environment node + +/** + * Every page of Settings has its MCP story: a settings kind covers it, or + * `coverage.ts` says what an agent cannot change there yet, or why the page + * holds nothing to change. The pages are read from the settings rail itself + * — its rows (`settings-rail.tsx`, and the mobile overview's + * `use-settings-menu-groups.ts`, which must list the same) and the tabs of + * the rows that have them — so a page added to the rail without its story + * fails here, and so does a page the shared list names that the rail lost. + */ + +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + SETTINGS_AREAS, + SETTINGS_KINDS, + type SettingsArea, +} from '@tale/shared/schemas/settings-kinds'; +import { describe, expect, it } from 'vitest'; + +import { API_NAV_ITEMS } from '../../../../app/routes/dashboard/$id/settings/api/-nav-items'; +import { GOVERNANCE_NAV_ITEMS } from '../../../../app/routes/dashboard/$id/settings/governance/-nav-items'; +import { METRICS_NAV_ITEMS } from '../../../../app/routes/dashboard/$id/settings/metrics/-nav-items'; +import { SETTINGS_NOT_EXPOSED, SETTINGS_PLANNED } from './coverage'; + +const PLATFORM = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../..', +); + +/** The rail's rows that open tabs, with the tabs each one opens. */ +const TABS: Readonly>> = { + governance: GOVERNANCE_NAV_ITEMS, + metrics: METRICS_NAV_ITEMS, + api: API_NAV_ITEMS, +}; + +function source(file: string): string { + return readFileSync(path.join(PLATFORM, file), 'utf8'); +} + +/** Every row a rail source lists, by its path under Settings. */ +function rows(text: string): string[] { + return [...text.matchAll(/\bpath:\s*'([a-z-]+)'/g)].map( + (match) => match[1] ?? '', + ); +} + +const RAIL = source('app/features/settings/components/settings-rail.tsx'); +const OVERVIEW = source( + 'app/features/settings/components/use-settings-menu-groups.ts', +); + +/** Every page of Settings the app shows, tab by tab. */ +function appAreas(): string[] { + return rows(RAIL).flatMap((row) => { + const tabs = TABS[row]; + return tabs === undefined ? [row] : tabs.map((tab) => `${row}/${tab.slug}`); + }); +} + +const covered = new Set( + SETTINGS_KINDS.flatMap((descriptor): readonly string[] => descriptor.areas), +); + +describe('the pages of Settings over MCP', () => { + it('reads the rail: its rows, and the tabs of the rows that open tabs', () => { + const rail = rows(RAIL); + expect(rail.length).toBeGreaterThan(10); + // The mobile overview lists the same pages as the desktop rail. + expect([...rows(OVERVIEW)].sort()).toEqual([...rail].sort()); + // A row opens tabs exactly when the rail draws it as a group. + const groups = [ + ...RAIL.matchAll(/kind:\s*'group',[^}]*?path:\s*'([a-z-]+)'/g), + ].map((match) => match[1]); + expect(groups.sort()).toEqual(Object.keys(TABS).sort()); + }); + + it('names in the shared list exactly the pages the rail shows', () => { + expect([...SETTINGS_AREAS].sort()).toEqual(appAreas().sort()); + }); + + it('gives every page its story: a kind covers it, or it says why not', () => { + const untold = SETTINGS_AREAS.filter( + (area) => + !covered.has(area) && + SETTINGS_PLANNED[area] === undefined && + SETTINGS_NOT_EXPOSED[area] === undefined, + ); + expect( + untold, + 'name the page in a settings kind’s areas, or say why not in coverage.ts', + ).toEqual([]); + }); + + it('tells each page one story', () => { + const listed = (area: SettingsArea) => + [ + covered.has(area), + SETTINGS_PLANNED[area] !== undefined, + SETTINGS_NOT_EXPOSED[area] !== undefined, + ].filter(Boolean).length; + expect(SETTINGS_AREAS.filter((area) => listed(area) > 1)).toEqual([]); + }); + + it('says why in a sentence', () => { + for (const [area, reason] of Object.entries({ + ...SETTINGS_PLANNED, + ...SETTINGS_NOT_EXPOSED, + })) { + expect(reason, area).toMatch(/^\S.*\.$/); + } + }); +}); diff --git a/services/platform/backend/domains/mcp/settings/coverage.ts b/services/platform/backend/domains/mcp/settings/coverage.ts new file mode 100644 index 0000000000..687c03def5 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/coverage.ts @@ -0,0 +1,55 @@ +/** + * Where each page of Settings stands over MCP. A page is covered when a + * settings kind names it among its `areas` (`@tale/shared/schemas/ + * settings-kinds`); every other page is listed here with its reason — + * either what an agent cannot change there yet, or why the page holds + * nothing an agent changes. `coverage.test.ts` holds the settings rail to + * these lists, so a new page of Settings cannot ship without its MCP story. + */ + +import type { SettingsArea } from '@tale/shared/schemas/settings-kinds'; + +/** Pages that hold nothing a settings kind would change. */ +export const SETTINGS_NOT_EXPOSED: Readonly< + Partial> +> = { + 'api/mcp': + 'It shows the endpoint itself — its address, its tools and how to connect — which no setting changes.', +}; + +/** Pages no settings kind covers yet, each with what an agent cannot do + * there. A page leaves this list when a kind names it. */ +export const SETTINGS_PLANNED: Readonly>> = + { + account: + 'No kind changes the display name yet; passwords, passkeys and authenticators stay in Tale.', + personalization: + 'No kind changes custom instructions or the chat model yet.', + notifications: 'No kind changes notification preferences yet.', + usage: "No kind reads a person's own usage and budget status yet.", + organization: + 'No kind changes the organization profile yet; deleting it stays in Tale.', + teams: 'No kind changes teams or their members yet.', + members: + "No kind changes members' roles, removals or invitations yet; transferring ownership stays in Tale.", + connectors: + 'No kind changes connector credentials or sign-in apps yet; their secrets are entered in Tale.', + skills: 'No kind changes skills or who may use them yet.', + 'governance/competences': 'No kind grants or revokes competences yet.', + 'governance/logs': 'No kind reads the audit log yet.', + 'governance/legal-hold': + 'No kind changes legal matters, holds or release requests yet.', + 'governance/data-subject-requests': + 'No kind files erasure requests or changes the request policy yet.', + 'governance/trash': 'No kind restores deleted items yet.', + 'metrics/usage': 'No kind reads the usage figures yet.', + 'metrics/feedback': 'No kind reads the feedback figures yet.', + 'metrics/chat-health': 'No kind reads the chat health figures yet.', + 'metrics/external-turns': 'No kind reads the external turn figures yet.', + 'metrics/automations': 'No kind reads the automation figures yet.', + 'metrics/projects': 'No kind reads the project figures yet.', + 'api/rest': + 'No kind revokes API keys yet; a key is created in Tale, where it is shown once.', + 'api/webdav': + 'No kind revokes WebDAV app passwords yet; one is created in Tale, where it is shown once.', + }; From 8236dcb0ce26942b61c8748890f9f0fe24b3a769 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:01:57 +0200 Subject: [PATCH 10/35] refactor(platform): lift the governance policy writer out of its route The policy read and save moved from the governance door into policy-writer.ts: who may read which policy, the checks a change passes (its workflow, the role, the expected hash, the schema, the standard agent's runtime, the sandbox capacity) and the audited write with the file last. The door answers its refusals exactly as before; another caller can now check and save a policy by the same rules. --- .../domains/governance/policy-writer.ts | 365 ++++++++++++++++++ .../backend/domains/governance/routes.ts | 306 ++++----------- 2 files changed, 441 insertions(+), 230 deletions(-) create mode 100644 services/platform/backend/domains/governance/policy-writer.ts diff --git a/services/platform/backend/domains/governance/policy-writer.ts b/services/platform/backend/domains/governance/policy-writer.ts new file mode 100644 index 0000000000..171bd3de62 --- /dev/null +++ b/services/platform/backend/domains/governance/policy-writer.ts @@ -0,0 +1,365 @@ +import { transactSerializable } from '@tale/shared/db/serializable'; +import { expectedConfigurationHashSchema } from '@tale/shared/schemas/configuration'; +import { + DEFAULT_SANDBOX_QUOTA, + isFilePolicyType, + isPolicyReadableByMember, + POLICY_SCHEMAS, + sandboxQuotaConfigSchema, + sandboxQuotaTotal, + sandboxWorkspacesConfigSchema, + standardAgentConfigSchema, + type FilePolicyType, +} from '@tale/shared/schemas/governance'; +import type { Sql } from 'postgres'; + +import { PROVIDER_CREDENTIAL_HINT_ENTITY } from '../../../lib/shared/hint-entities'; +import { isAdmin } from '../../core/lib/rls/helpers/role_helpers.ts'; +import { + readGovernancePolicyForOrg, + resolveOrgSlug, +} from '../../lib/org-config.ts'; +import { emitHintInTx } from '../../realtime/outbox.ts'; +import { createAuditLog } from '../audit_logs/service.ts'; +import { eligibleProjectAgentHarnesses } from '../projects/service.ts'; +import { getSandboxDeploymentLimits } from '../sandbox/limits.ts'; +import { recordUnusedWorkspaceRule } from '../sandbox/unused-rule.ts'; + +/** + * The organization's policies, read and changed by one set of rules: who + * may read which policy, how a change is checked before anything is + * written, and how it lands — audited, announced to every open session and + * written to its file last, inside one transaction. The Settings pages' + * door (`routes.ts`) answers through it, and so does every other caller + * that changes a policy, so the rules cannot differ by where the change + * comes from. The policy files are the store: `lib/governance-policy-write.ts` + * owns their bytes, history and compare-and-set. + */ + +/** Policies with their own staged workflows (bounds, grace periods) — + * never changed through the generic write. */ +const SPECIAL_WRITE_POLICY_TYPES: ReadonlySet = new Set([ + 'retention_policy', + 'dsar_governance', +]); + +/** + * A refusal of a policy read or change, as the app's door answers it: the + * code and status it puts on the wire, the sentence a reader is told, and + * the data some refusals carry. `answersMessage` says whether the door's + * answer carries the sentence. + */ +export class GovernancePolicyError extends Error { + readonly code: string; + readonly status: 400 | 403 | 404 | 503; + readonly data?: Record; + readonly answersMessage: boolean; + + constructor( + code: string, + message: string, + status: 400 | 403 | 404 | 503, + options: { data?: Record; answersMessage?: boolean } = {}, + ) { + super(message); + this.name = 'GovernancePolicyError'; + this.code = code; + this.status = status; + if (options.data !== undefined) this.data = options.data; + this.answersMessage = options.answersMessage === true; + } +} + +/** Who changes a policy, in which organization, with which role. */ +export interface GovernancePolicyActor { + readonly organizationId: string; + readonly userId: string; + readonly email?: string; + readonly role: string; +} + +function unknownPolicy(policyType: string): GovernancePolicyError { + return new GovernancePolicyError( + 'UNKNOWN_POLICY_TYPE', + `"${policyType}" is not an organization policy.`, + 400, + ); +} + +function organizationGone(): GovernancePolicyError { + return new GovernancePolicyError( + 'ORG_NOT_FOUND', + 'The organization no longer exists.', + 404, + ); +} + +/** The policy a reader names, when the reader's role may read it: any + * member reads the policies `isPolicyReadableByMember` lists, an owner or + * admin every one. */ +export function assertGovernancePolicyReadable( + role: string, + policyType: string, +): FilePolicyType { + if (!isFilePolicyType(policyType)) throw unknownPolicy(policyType); + if (!isPolicyReadableByMember(policyType) && !isAdmin(role)) { + throw new GovernancePolicyError( + 'FORBIDDEN', + `Only owners and admins can read the ${policyType} policy.`, + 403, + ); + } + return policyType; +} + +/** + * A policy as its file holds it now, past every cache, with the hash its + * writer checks a change against: no policy and a null hash when the + * organization has never saved one. + */ +export async function readGovernancePolicySnapshotFor( + sql: Sql, + member: { readonly organizationId: string; readonly role: string }, + policyType: string, +): Promise<{ + policy: { key: FilePolicyType; config: unknown } | null; + hash: string | null; +}> { + const type = assertGovernancePolicyReadable(member.role, policyType); + const orgSlug = await resolveOrgSlug(sql, member.organizationId, { + fresh: true, + }); + if (orgSlug === null) throw organizationGone(); + const { readGovernancePolicySnapshot } = + await import('../../lib/governance-policy-write'); + const snapshot = await readGovernancePolicySnapshot(orgSlug, type); + return { + policy: + snapshot.config === null ? null : { key: type, config: snapshot.config }, + hash: snapshot.hash, + }; +} + +/** A change as the writer will store it, checked the way the save checks + * it. */ +export interface CheckedGovernancePolicy { + readonly policyType: FilePolicyType; + readonly config: unknown; + /** The hash the change expects is stored now; undefined when it names + * none, and the write then replaces whatever is there. */ + readonly expectedHash: string | null | undefined; +} + +/** + * Check one policy change as the save does, and write nothing: the policy + * exists and has no workflow of its own, the actor is an owner or admin, + * the expected hash is well formed, the config is the policy's own, a + * standard agent names a runtime the managed lane can run, and the sandbox + * budgets fit the deployment's capacity as it is now. + */ +export async function checkGovernancePolicy( + sql: Sql, + actor: GovernancePolicyActor, + policyType: string, + input: { readonly config: unknown; readonly expectedHash?: unknown }, +): Promise { + if (!isFilePolicyType(policyType)) throw unknownPolicy(policyType); + if (SPECIAL_WRITE_POLICY_TYPES.has(policyType)) { + throw new GovernancePolicyError( + 'use_special_action', + `${policyType} has a dedicated write door.`, + 400, + { answersMessage: true }, + ); + } + if (!isAdmin(actor.role)) { + throw new GovernancePolicyError( + 'FORBIDDEN', + 'Only owners and admins can change organization policies.', + 403, + ); + } + const precondition = expectedConfigurationHashSchema + .optional() + .safeParse(input.expectedHash); + if (!precondition.success) { + throw new GovernancePolicyError( + 'INVALID_CONFIG_PRECONDITION', + 'The expected hash is not a configuration hash.', + 400, + ); + } + const parsed = POLICY_SCHEMAS[policyType].safeParse(input.config); + if (!parsed.success) { + throw new GovernancePolicyError( + 'validation', + `Invalid ${policyType} configuration: ${parsed.error.message}`, + 400, + { answersMessage: true }, + ); + } + if (policyType === 'standard_agent') { + // The runtime a project agent may run on is the managed lane's list, + // which only the platform knows; the shared schema cannot check it. + const { harness } = standardAgentConfigSchema.parse(parsed.data); + const harnesses = eligibleProjectAgentHarnesses(); + if (harness !== undefined && !harnesses.includes(harness)) { + throw new GovernancePolicyError( + 'STANDARD_AGENT_HARNESS_INVALID', + `The agent runtime "${harness}" cannot run project agents here; choose one of ${harnesses.join(', ')}.`, + 400, + { data: { harnesses } }, + ); + } + } + if (policyType === 'sandbox_quota') { + const total = sandboxQuotaTotal( + sandboxQuotaConfigSchema.parse(parsed.data), + ); + // Read at save time; neither a client-supplied ceiling nor the UI's + // last snapshot can authorize a configuration against a changed host. + const limits = await getSandboxDeploymentLimits(actor.organizationId); + if (limits.status === 'unavailable') { + // No readable ceiling: a total that does not grow is still saved. + // Lowering limits can never oversubscribe more than the saved + // configuration already does, and shedding load is the one edit an + // admin needs while the sandbox service is down; only raising the + // total needs the capacity. + const saved = sandboxQuotaConfigSchema.safeParse( + await readGovernancePolicyForOrg( + sql, + actor.organizationId, + 'sandbox_quota', + { fresh: true }, + ), + ); + const savedTotal = sandboxQuotaTotal( + saved.success ? saved.data : DEFAULT_SANDBOX_QUOTA, + ); + if (total > savedTotal) { + throw new GovernancePolicyError( + 'SANDBOX_CAPACITY_UNAVAILABLE', + 'The sandbox service cannot say how many sessions this deployment runs, so the sandbox budgets cannot grow now; lowering them still works.', + 503, + ); + } + } else if (total > limits.maxSessions + (limits.deviceSessions ?? 0)) { + // The organization's connected devices add their own slots: a quota + // may use the deployment's capacity plus its own machines'. + throw new GovernancePolicyError( + 'SANDBOX_QUOTA_EXCEEDS_DEPLOYMENT', + `The sandbox budgets add up to ${total} sessions, more than the ${limits.maxSessions + (limits.deviceSessions ?? 0)} this deployment can run for the organization.`, + 400, + { + data: { + total, + maxSessions: limits.maxSessions, + ...(limits.deviceSessions + ? { deviceSessions: limits.deviceSessions } + : {}), + }, + }, + ); + } + } + return { + policyType, + config: parsed.data, + expectedHash: precondition.data, + }; +} + +/** + * Change one policy: checked as `checkGovernancePolicy` checks it, then + * audited, announced and written in one transaction — the file last, so a + * failed write rolls the audit row back and no policy is ever in force + * that the tamper-evident chain knows nothing about. With an expected hash + * the write lands only on the file it names. + */ +export async function saveGovernancePolicy( + sql: Sql, + actor: GovernancePolicyActor, + policyType: string, + input: { readonly config: unknown; readonly expectedHash?: unknown }, +): Promise { + const checked = await checkGovernancePolicy(sql, actor, policyType, input); + const { organizationId } = actor; + const orgSlug = await resolveOrgSlug(sql, organizationId); + if (orgSlug === null) throw organizationGone(); + // The file as it IS, not the TTL cache's view of it: two admins saving + // inside the cache window must each audit the config they replaced. + const previous = await readGovernancePolicyForOrg( + sql, + organizationId, + checked.policyType, + { fresh: true }, + ); + const { writeGovernancePolicyFile } = + await import('../../lib/governance-policy-write.ts'); + await transactSerializable(sql, async (tx) => { + await createAuditLog(tx, { + organizationId, + actorId: actor.userId, + ...(actor.email !== undefined ? { actorEmail: actor.email } : {}), + actorType: 'user', + action: + previous === null + ? 'governance_policy.created' + : 'governance_policy.updated', + category: 'security', + resourceType: 'governance_policy', + resourceId: checked.policyType, + ...(previous !== null ? { previousState: { config: previous } } : {}), + newState: { config: checked.config }, + status: 'success', + }); + await emitHintInTx(tx, { + orgId: organizationId, + entity: 'governance_policy', + entityId: checked.policyType, + }); + if ( + checked.policyType === 'model_access' || + checked.policyType === 'vision_model' || + checked.policyType === 'transcription_model' || + checked.policyType === 'image_generation' + ) { + // The serving catalog and resolved picks are provider-derived reads. + // Every open session must refresh them, not only the saving tab. + await emitHintInTx(tx, { + orgId: organizationId, + entity: PROVIDER_CREDENTIAL_HINT_ENTITY, + entityId: checked.policyType, + }); + } + if (checked.policyType === 'sandbox_workspaces') { + // The unused-workspace rule takes effect with this save: a rule + // turned (back) on or a shorter window starts its full window now, + // not at the next hourly sweep. + await recordUnusedWorkspaceRule( + tx, + organizationId, + sandboxWorkspacesConfigSchema.parse(checked.config), + Date.now(), + ); + } + // The file LAST, inside the transaction: a write failure rolls the + // audit row back, and a transaction failure never leaves a policy in + // force that the tamper-evident chain knows nothing about. + if (checked.expectedHash === undefined) + await writeGovernancePolicyFile( + tx, + orgSlug, + checked.policyType, + checked.config, + ); + else + await writeGovernancePolicyFile( + tx, + orgSlug, + checked.policyType, + checked.config, + checked.expectedHash, + ); + }); +} diff --git a/services/platform/backend/domains/governance/routes.ts b/services/platform/backend/domains/governance/routes.ts index 9e265e2e94..aec1acf533 100644 --- a/services/platform/backend/domains/governance/routes.ts +++ b/services/platform/backend/domains/governance/routes.ts @@ -1,22 +1,10 @@ import { transactSerializable } from '@tale/shared/db/serializable'; -import { expectedConfigurationHashSchema } from '@tale/shared/schemas/configuration'; import { epochMsSchema } from '@tale/shared/schemas/epoch-ms'; -import { - DEFAULT_SANDBOX_QUOTA, - dsarGovernanceConfigSchema, - isFilePolicyType, - isPolicyReadableByMember, - POLICY_SCHEMAS, - sandboxQuotaConfigSchema, - sandboxQuotaTotal, - sandboxWorkspacesConfigSchema, - standardAgentConfigSchema, -} from '@tale/shared/schemas/governance'; +import { dsarGovernanceConfigSchema } from '@tale/shared/schemas/governance'; import { Hono, type Context } from 'hono'; import type { Sql } from 'postgres'; import { z } from 'zod'; -import { PROVIDER_CREDENTIAL_HINT_ENTITY } from '../../../lib/shared/hint-entities'; import { mayCreateApiKeys } from '../../auth/api-key-create-gate.ts'; import type { Auth } from '../../auth/auth.ts'; import { getUserTeamIds } from '../../auth/membership.ts'; @@ -34,16 +22,11 @@ import { readGovernancePolicyForOrg, resolveOrgSlug, } from '../../lib/org-config.ts'; -import { emitHintInTx } from '../../realtime/outbox.ts'; -import { createAuditLog } from '../audit_logs/service.ts'; import { projectChatAccess } from '../chat/threads.ts'; import { ContactError } from '../contacts/service.ts'; import { syncRagDocumentScope } from '../knowledge/service.ts'; import { readModelApiStanding } from '../model_api/access.ts'; import { listModelApiModels } from '../model_api/models.ts'; -import { eligibleProjectAgentHarnesses } from '../projects/service.ts'; -import { getSandboxDeploymentLimits } from '../sandbox/limits.ts'; -import { recordUnusedWorkspaceRule } from '../sandbox/unused-rule.ts'; import { describeRuleApiKeys, holdsApiKeys, @@ -63,6 +46,12 @@ import { revokeCompetence, } from './competence.ts'; import { testModerationProvider } from './moderation.ts'; +import { + assertGovernancePolicyReadable, + GovernancePolicyError, + readGovernancePolicySnapshotFor, + saveGovernancePolicy, +} from './policy-writer.ts'; import { cancelPendingDsarPolicyChange, getDsarPolicyForUi, @@ -84,18 +73,12 @@ import { getOrgUsageMetricsPg } from './usage-metrics.ts'; /** * /api/app/governance — the governance SETTINGS core: policy file - * reads/writes (history-snapshotted yaml, the 0.4 `saveGovernancePolicy` - * semantics), the caller's resolved feature flags, budget status and budget - * usage, the model-access filter, and the admin Trash listing/restore. + * reads/writes (history-snapshotted yaml, through the policy writer in + * `policy-writer.ts`, which holds who may read and change each policy), the + * caller's resolved feature flags, budget status and budget usage, the + * model-access filter, and the admin Trash listing/restore. */ -/** Types with dedicated write actions (bounds / grace flows) — never - * writable through the generic save door. */ -const SPECIAL_WRITE_POLICY_TYPES: ReadonlySet = new Set([ - 'retention_policy', - 'dsar_governance', -]); - export function createGovernanceRoutes(deps: { sql: Sql; auth: Auth; @@ -111,221 +94,84 @@ export function createGovernanceRoutes(deps: { return appErrorHandler(error, c); }); - app.get('/policies/:policyType', async (c) => { - const policyType = c.req.param('policyType'); - if (!isFilePolicyType(policyType)) { - return c.json({ error: 'UNKNOWN_POLICY_TYPE' }, 400); - } - if ( - !isPolicyReadableByMember(policyType) && - !isAdmin(c.get('orgMember').role) - ) { - return c.json({ error: 'FORBIDDEN' }, 403); + /** A policy refusal as the door answers it: the code and status, with + * the sentence and data the refusal carries on the wire. */ + const policyErrorResponse = (c: Context, error: unknown) => { + if (error instanceof GovernancePolicyError) { + return c.json( + { + error: error.code, + ...(error.answersMessage ? { message: error.message } : {}), + ...(error.data !== undefined ? { data: error.data } : {}), + }, + error.status, + ); } - if (c.req.query('includeHash') === '1') { - const orgSlug = await resolveOrgSlug(deps.sql, c.get('orgId'), { - fresh: true, - }); - if (orgSlug === null) return c.json({ error: 'ORG_NOT_FOUND' }, 404); - const { readGovernancePolicySnapshot } = - await import('../../lib/governance-policy-write'); - const snapshot = await readGovernancePolicySnapshot(orgSlug, policyType); + throw error; + }; + + app.get('/policies/:policyType', async (c) => { + const member = { + organizationId: c.get('orgId'), + role: c.get('orgMember').role, + }; + try { + if (c.req.query('includeHash') === '1') { + return c.json( + await readGovernancePolicySnapshotFor( + deps.sql, + member, + c.req.param('policyType'), + ), + ); + } + const policyType = assertGovernancePolicyReadable( + member.role, + c.req.param('policyType'), + ); + const config = await readGovernancePolicyForOrg( + deps.sql, + member.organizationId, + policyType, + policyType === 'transcription_model' || + policyType === 'image_generation' || + policyType === 'standard_agent' + ? { strict: true } + : {}, + ); return c.json({ - policy: - snapshot.config === null - ? null - : { key: policyType, config: snapshot.config }, - hash: snapshot.hash, + policy: config === null ? null : { key: policyType, config }, }); + } catch (error) { + return policyErrorResponse(c, error); } - const config = await readGovernancePolicyForOrg( - deps.sql, - c.get('orgId'), - policyType, - policyType === 'transcription_model' || - policyType === 'image_generation' || - policyType === 'standard_agent' - ? { strict: true } - : {}, - ); - return c.json({ - policy: config === null ? null : { key: policyType, config }, - }); }); app.post('/policies/:policyType', async (c) => { - const policyType = c.req.param('policyType'); - if (!isFilePolicyType(policyType)) { - return c.json({ error: 'UNKNOWN_POLICY_TYPE' }, 400); - } - if (SPECIAL_WRITE_POLICY_TYPES.has(policyType)) { - return c.json( + const body: unknown = await c.req.json().catch(() => null); + const fields = body !== null && typeof body === 'object' ? body : null; + const user = c.get('sessionBundle').user; + try { + await saveGovernancePolicy( + deps.sql, { - error: 'use_special_action', - message: `${policyType} has a dedicated write door.`, + organizationId: c.get('orgId'), + userId: user.id, + email: user.email, + role: c.get('orgMember').role, }, - 400, - ); - } - if (!isAdmin(c.get('orgMember').role)) { - return c.json({ error: 'FORBIDDEN' }, 403); - } - const body: unknown = await c.req.json().catch(() => null); - const precondition = expectedConfigurationHashSchema - .optional() - .safeParse( - body !== null && typeof body === 'object' && 'expectedHash' in body - ? body.expectedHash - : undefined, - ); - if (!precondition.success) - return c.json({ error: 'INVALID_CONFIG_PRECONDITION' }, 400); - const parsed = POLICY_SCHEMAS[policyType].safeParse( - body !== null && typeof body === 'object' && 'config' in body - ? body.config - : body, - ); - if (!parsed.success) { - return c.json( + c.req.param('policyType'), { - error: 'validation', - message: `Invalid ${policyType} configuration: ${parsed.error.message}`, + config: fields !== null && 'config' in fields ? fields.config : body, + expectedHash: + fields !== null && 'expectedHash' in fields + ? fields.expectedHash + : undefined, }, - 400, - ); - } - if (policyType === 'standard_agent') { - // The runtime a project agent may run on is the managed lane's list, - // which only the platform knows; the shared schema cannot check it. - const { harness } = standardAgentConfigSchema.parse(parsed.data); - const harnesses = eligibleProjectAgentHarnesses(); - if (harness !== undefined && !harnesses.includes(harness)) { - return c.json( - { error: 'STANDARD_AGENT_HARNESS_INVALID', data: { harnesses } }, - 400, - ); - } - } - if (policyType === 'sandbox_quota') { - const total = sandboxQuotaTotal( - sandboxQuotaConfigSchema.parse(parsed.data), ); - // Read at save time; neither a client-supplied ceiling nor the UI's - // last snapshot can authorize a configuration against a changed host. - const limits = await getSandboxDeploymentLimits(c.get('orgId')); - if (limits.status === 'unavailable') { - // No readable ceiling: a total that does not grow is still saved. - // Lowering limits can never oversubscribe more than the saved - // configuration already does, and shedding load is the one edit an - // admin needs while the sandbox service is down; only raising the - // total needs the capacity. - const saved = sandboxQuotaConfigSchema.safeParse( - await readGovernancePolicyForOrg( - deps.sql, - c.get('orgId'), - 'sandbox_quota', - { fresh: true }, - ), - ); - const savedTotal = sandboxQuotaTotal( - saved.success ? saved.data : DEFAULT_SANDBOX_QUOTA, - ); - if (total > savedTotal) { - return c.json({ error: 'SANDBOX_CAPACITY_UNAVAILABLE' }, 503); - } - } else if (total > limits.maxSessions + (limits.deviceSessions ?? 0)) { - // The organization's connected devices add their own slots: a quota - // may use the deployment's capacity plus its own machines'. - return c.json( - { - error: 'SANDBOX_QUOTA_EXCEEDS_DEPLOYMENT', - data: { - total, - maxSessions: limits.maxSessions, - ...(limits.deviceSessions - ? { deviceSessions: limits.deviceSessions } - : {}), - }, - }, - 400, - ); - } + } catch (error) { + return policyErrorResponse(c, error); } - const organizationId = c.get('orgId'); - const orgSlug = await resolveOrgSlug(deps.sql, organizationId); - if (orgSlug === null) return c.json({ error: 'ORG_NOT_FOUND' }, 404); - // The file as it IS, not the TTL cache's view of it: two admins saving - // inside the cache window must each audit the config they replaced. - const previous = await readGovernancePolicyForOrg( - deps.sql, - organizationId, - policyType, - { fresh: true }, - ); - const { writeGovernancePolicyFile } = - await import('../../lib/governance-policy-write.ts'); - const session = c.get('sessionBundle'); - await transactSerializable(deps.sql, async (tx) => { - await createAuditLog(tx, { - organizationId, - actorId: session.user.id, - actorEmail: session.user.email, - actorType: 'user', - action: - previous === null - ? 'governance_policy.created' - : 'governance_policy.updated', - category: 'security', - resourceType: 'governance_policy', - resourceId: policyType, - ...(previous !== null ? { previousState: { config: previous } } : {}), - newState: { config: parsed.data }, - status: 'success', - }); - await emitHintInTx(tx, { - orgId: organizationId, - entity: 'governance_policy', - entityId: policyType, - }); - if ( - policyType === 'model_access' || - policyType === 'vision_model' || - policyType === 'transcription_model' || - policyType === 'image_generation' - ) { - // The serving catalog and resolved picks are provider-derived reads. - // Every open session must refresh them, not only the saving tab. - await emitHintInTx(tx, { - orgId: organizationId, - entity: PROVIDER_CREDENTIAL_HINT_ENTITY, - entityId: policyType, - }); - } - if (policyType === 'sandbox_workspaces') { - // The unused-workspace rule takes effect with this save: a rule - // turned (back) on or a shorter window starts its full window now, - // not at the next hourly sweep. - await recordUnusedWorkspaceRule( - tx, - organizationId, - sandboxWorkspacesConfigSchema.parse(parsed.data), - Date.now(), - ); - } - // The file LAST, inside the transaction: a write failure rolls the - // audit row back, and a transaction failure never leaves a policy in - // force that the tamper-evident chain knows nothing about. - if (precondition.data === undefined) - await writeGovernancePolicyFile(tx, orgSlug, policyType, parsed.data); - else - await writeGovernancePolicyFile( - tx, - orgSlug, - policyType, - parsed.data, - precondition.data, - ); - }); return c.json({ ok: true }); }); From de73fe435e5772b82c54499ea9aea1e22cb6e751 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:03:03 +0200 Subject: [PATCH 11/35] test(platform): hold who may change the branding The branding door had no test of its own: a characterization pins the role gate the Branding page meets (owners and admins; anyone else refused with ORG_FORBIDDEN and the capability named, before anything is read or saved), what a save hands the writer and how a writer's refusal is answered. The gate becomes BRAND-R5, out of the spec's Not yet. --- .../backend/domains/branding/routes.test.ts | 149 ++++++++++++++++++ .../platform/backend/domains/branding/spec.md | 17 +- 2 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 services/platform/backend/domains/branding/routes.test.ts diff --git a/services/platform/backend/domains/branding/routes.test.ts b/services/platform/backend/domains/branding/routes.test.ts new file mode 100644 index 0000000000..fddcb6b0d9 --- /dev/null +++ b/services/platform/backend/domains/branding/routes.test.ts @@ -0,0 +1,149 @@ +// @vitest-environment node + +/** + * The branding door as the Branding page drives it: who may read and change + * the branding behind a session, and what a save hands the writer. The + * writer itself — the bytes on disk, the compare-and-set, the audit row — + * is `service.test.ts`'s; here it is a double that records its calls. + */ + +import type { Context } from 'hono'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { OrgEnv } from '../../auth/org.ts'; + +const { member, readBrandingConfig, saveBranding } = vi.hoisted(() => ({ + // The role the mocked organization gate grants. + member: { role: 'admin' }, + readBrandingConfig: vi.fn(), + saveBranding: vi.fn(), +})); + +vi.mock('./service.ts', async (importOriginal) => ({ + ...(await importOriginal()), + readBrandingConfig, + saveBranding, +})); + +vi.mock('../../lib/org-config.ts', () => ({ + resolveOrgSlug: vi.fn(async () => 'acme'), +})); + +vi.mock('../../auth/session.ts', () => ({ + requireSession: + () => async (c: Context, next: () => Promise) => { + c.set('sessionBundle', { + user: { id: 'u1', email: 'ada@example.test' }, + } as never); + await next(); + }, +})); + +vi.mock('../../auth/org.ts', async (importOriginal) => ({ + ...(await importOriginal()), + requireOrgMember: + () => async (c: Context, next: () => Promise) => { + c.set('orgId', 'o1'); + c.set('orgMember', { role: member.role } as never); + await next(); + }, +})); + +import { ConfigurationError } from '../../core/lib/config_store/precondition'; +import { createBrandingRoutes } from './routes.ts'; + +function app() { + return createBrandingRoutes({ sql: {} as never, auth: {} as never }); +} + +async function save(body: unknown): Promise { + return await app().request('/save?orgId=o1', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); +} + +const HASH = 'a'.repeat(64); + +beforeEach(() => { + vi.clearAllMocks(); + member.role = 'admin'; + saveBranding.mockResolvedValue({ hash: HASH }); + readBrandingConfig.mockResolvedValue({ + config: { accentColor: '#112233' }, + hash: HASH, + }); +}); + +describe('who may change the branding [BRAND-R5]', () => { + it.each(['developer', 'editor', 'member'])( + 'refuses a %s, naming the capability, before anything is read or saved', + async (role) => { + member.role = role; + for (const response of [ + await save({ accentColor: '#445566' }), + await app().request('/config?orgId=o1'), + ]) { + expect(response.status).toBe(403); + expect(await response.json()).toEqual({ + error: 'ORG_FORBIDDEN', + message: `Role "${role}" lacks the org-settings capability required to modify branding.`, + }); + } + expect(saveBranding).not.toHaveBeenCalled(); + expect(readBrandingConfig).not.toHaveBeenCalled(); + }, + ); + + it.each(['owner', 'admin'])( + 'lets an %s save, handing the writer the fields, the hash and who saved', + async (role) => { + member.role = role; + const response = await save({ + accentColor: '#445566', + logoFilename: 'logo.png', + expectedHash: HASH, + }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ hash: HASH }); + expect(saveBranding).toHaveBeenCalledWith( + expect.anything(), + 'acme', + { accentColor: '#445566', logoFilename: 'logo.png' }, + HASH, + { organizationId: 'o1', userId: 'u1', email: 'ada@example.test' }, + ); + }, + ); +}); + +describe('the branding door', () => { + it('reads the stored branding with its hash', async () => { + const response = await app().request('/config?orgId=o1'); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + config: { accentColor: '#112233' }, + hash: HASH, + }); + expect(readBrandingConfig).toHaveBeenCalledWith('acme'); + }); + + it("answers a writer's refusal with its code, sentence and status", async () => { + saveBranding.mockRejectedValue( + new ConfigurationError( + 'CONFIG_VERSION_CONFLICT', + 'Configuration changed since it was reviewed.', + ), + ); + const response = await save({ + accentColor: '#445566', + expectedHash: HASH, + }); + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + error: 'CONFIG_VERSION_CONFLICT', + message: 'Configuration changed since it was reviewed.', + }); + }); +}); diff --git a/services/platform/backend/domains/branding/spec.md b/services/platform/backend/domains/branding/spec.md index 60011a2781..aca6d2b12d 100644 --- a/services/platform/backend/domains/branding/spec.md +++ b/services/platform/backend/domains/branding/spec.md @@ -3,8 +3,19 @@ > **Prefix** `BRAND-` · **Docs** [`admin/branding`](../../../../../docs/en/platform/admin/branding.md) An organization can carry its own logo, browser-tab icons and accent color. These rules cover -what can be uploaded as an image and what a save records. Who can change the branding and who -can read it are not covered; see Not yet. +who can change the branding, what can be uploaded as an image and what a save records. Who can +read it is not covered; see Not yet. + +## Who can change it + +### BRAND-R5 · Only owners and admins can change the branding + +Reading the stored branding for editing, saving it and uploading or deleting its images take the +owner or admin role. Anyone else is refused (`ORG_FORBIDDEN`) with the sentence naming the +capability their role lacks, before anything is read or saved. + +- **Example**: Noah is a developer. He saves a new accent color → refused, and the branding stays + as it was; Ada, an admin, saves the same color → it is saved. ## What can be uploaded @@ -46,8 +57,6 @@ The entry lists the fields that were added, removed or changed. ## Not yet -- **Who can change the branding**: owners and admins, as the user docs say. No test holds it - yet (`routes.ts`). - **Who can read the branding**: it is readable without signing in, because the sign-in page shows it. No test holds it yet (`routes.ts`). - **Limits on an image's size and type**, and the icon derived from a logo when none is From 053c26bc93b5061b716ce8ced8d2b084e1d11ab8 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:04:19 +0200 Subject: [PATCH 12/35] refactor(platform): lift the branding writer's role gate into its service assertBrandingWriter holds the org-settings capability check the branding door ran inline, with the same ORG_FORBIDDEN refusal and sentence, so any caller of the branding writer meets the gate the Branding page meets. --- .../backend/domains/branding/routes.ts | 21 +++++++------------ .../backend/domains/branding/service.ts | 17 +++++++++++++++ 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/services/platform/backend/domains/branding/routes.ts b/services/platform/backend/domains/branding/routes.ts index ceb70aeb4d..f792f37743 100644 --- a/services/platform/backend/domains/branding/routes.ts +++ b/services/platform/backend/domains/branding/routes.ts @@ -3,7 +3,6 @@ import { Hono, type Context } from 'hono'; import type { Sql } from 'postgres'; import { z } from 'zod'; -import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; import type { Auth } from '../../auth/auth.ts'; import { requireOrgMember, type OrgEnv } from '../../auth/org.ts'; import { requireSession } from '../../auth/session.ts'; @@ -11,6 +10,7 @@ import { ConfigurationError } from '../../core/lib/config_store/precondition'; import { invalidBodyResponse } from '../../lib/invalid-body-response.ts'; import { resolveOrgSlug } from '../../lib/org-config.ts'; import { + assertBrandingWriter, BrandingError, deleteBrandingImage, readBranding, @@ -24,8 +24,9 @@ import { * /api/app/branding — per-org theming. The READ is deliberately open (the * pre-auth login shell needs the `default` bucket before any session * exists; an org id that no longer resolves falls back to it too). Writes - * require the `orgSettings` capability in the org, matching the settings - * page's own gate. Image bytes are served by the shell's static handler. + * require the `orgSettings` capability in the org (`assertBrandingWriter`), + * matching the settings page's own gate. Image bytes are served by the + * shell's static handler. */ function handleError( @@ -53,16 +54,10 @@ export function createBrandingRoutes(deps: { const admin = new Hono(); admin.use(requireSession(deps.auth), requireOrgMember(deps.sql)); admin.use(async (c, next) => { - if ( - defineAbilityFor(c.get('orgMember').role).cannot('write', 'orgSettings') - ) { - return c.json( - { - error: 'ORG_FORBIDDEN', - message: `Role "${c.get('orgMember').role}" lacks the org-settings capability required to modify branding.`, - }, - 403, - ); + try { + assertBrandingWriter(c.get('orgMember').role); + } catch (error) { + return handleError(c, error); } return next(); }); diff --git a/services/platform/backend/domains/branding/service.ts b/services/platform/backend/domains/branding/service.ts index a280897aed..8d86533f96 100644 --- a/services/platform/backend/domains/branding/service.ts +++ b/services/platform/backend/domains/branding/service.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { brandingJsonSchema } from '@tale/shared/schemas/branding'; import type { Sql } from 'postgres'; +import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; import { buildBrandingImageUrl, MAX_FILE_SIZE_BYTES, @@ -101,6 +102,22 @@ export class BrandingError extends Error { } } +/** + * Who may change the organization's branding — read it for editing, save + * it, upload or delete its images: a role with the org-settings + * capability, which owners and admins hold. Anyone else is refused, with + * the capability named, before anything is read or written. + */ +export function assertBrandingWriter(role: string): void { + if (defineAbilityFor(role).cannot('write', 'orgSettings')) { + throw new BrandingError( + 'ORG_FORBIDDEN', + `Role "${role}" lacks the org-settings capability required to modify branding.`, + 403, + ); + } +} + async function readBrandingFile(orgSlug: string): Promise { const filePath = resolveBrandingFilePath(orgSlug); const result = await readJsonFile( From 54ae9c023fea3fa26addac2e8b4e2c055051daf2 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:05:50 +0200 Subject: [PATCH 13/35] refactor(platform): lift the embedding model's save and its follow-ups embedding-save.ts now holds who may manage the knowledge configuration, the save of the embedding model with its compare-and-set, and what follows it: the documents that failed for want of a model and those without a vector of the new width go back in the queue, and the websites scan again. The data-residency door answers exactly as before. --- .../domains/knowledge/embedding-save.ts | 141 ++++++++++++++++++ .../backend/domains/knowledge/routes.ts | 117 +++------------ 2 files changed, 160 insertions(+), 98 deletions(-) create mode 100644 services/platform/backend/domains/knowledge/embedding-save.ts diff --git a/services/platform/backend/domains/knowledge/embedding-save.ts b/services/platform/backend/domains/knowledge/embedding-save.ts new file mode 100644 index 0000000000..d5bffaa42d --- /dev/null +++ b/services/platform/backend/domains/knowledge/embedding-save.ts @@ -0,0 +1,141 @@ +import type { Sql } from 'postgres'; + +import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; +import { ConfigurationError } from '../../core/lib/config_store/precondition'; +import { websitesAfterEmbeddingChange } from '../websites/service.ts'; +import { deleteKnowledgeEmbedding, writeKnowledgeEmbedding } from './admin.ts'; +import { + requeueDocumentsWithoutVectors, + requeueEmbeddingBlockedDocuments, +} from './service.ts'; + +/** + * Choosing the organization's embedding model, and what follows a choice: + * the documents that failed for want of a model go back in the queue, so do + * the indexed documents that have no vector of the chosen width, and the + * websites scan again so their pages are embedded too. The data-residency + * page's door (`routes.ts`) saves through it, and so does every other + * caller that changes the model, so a change is followed the same way + * wherever it comes from. + */ + +/** The organization a model is chosen for, by id and by the slug its + * config tree is kept under. */ +export interface EmbeddingOrganization { + readonly organizationId: string; + readonly orgSlug: string; +} + +/** + * Who may manage the organization's knowledge configuration — its + * database connection and its embedding model: a role with the + * org-settings capability, which owners and admins hold. + */ +export function assertKnowledgeAdmin(role: string): void { + if (defineAbilityFor(role).cannot('write', 'orgSettings')) { + throw new ConfigurationError( + 'ORG_FORBIDDEN', + `Role "${role}" cannot manage the knowledge configuration.`, + 403, + ); + } +} + +// The websites follow the model too: their page says whether search can +// reach them, and a saved model is what embeds the pages crawled without +// one. Best-effort — the setting is saved either way; a site a failure +// here skipped is embedded by its next scheduled scan. +async function websitesFollowEmbedding( + sql: Sql, + org: EmbeddingOrganization, + change: 'saved' | 'removed', +): Promise { + try { + const { queued } = await websitesAfterEmbeddingChange( + sql, + org.organizationId, + change, + ); + if (queued > 0) { + console.info( + `[knowledge] embedding configured for ${org.orgSlug}: queued a scan of ${queued} website(s) to embed their pages`, + ); + } + } catch (error) { + console.warn( + `[knowledge] embedding ${change} for ${org.orgSlug}: the websites could not follow:`, + error instanceof Error ? error.message : error, + ); + } +} + +// So do the documents already indexed: vectors are kept per width, so a +// model of another width finds none of theirs, and each would be missing +// from search by meaning until someone indexed it again. Best-effort like +// the websites — the setting is saved either way, and saving it again +// picks up whatever a failure here left. +async function documentsFollowEmbedding( + sql: Sql, + org: EmbeddingOrganization, +): Promise { + try { + const { requeued } = await requeueDocumentsWithoutVectors(sql, { + organizationId: org.organizationId, + orgSlug: org.orgSlug, + }); + if (requeued > 0) { + console.info( + `[knowledge] embedding configured for ${org.orgSlug}: re-queued ${requeued} indexed document(s) that have no vector of the model's width`, + ); + } + return requeued; + } catch (error) { + console.warn( + `[knowledge] embedding saved for ${org.orgSlug}: the indexed documents could not follow:`, + error instanceof Error ? error.message : error, + ); + return 0; + } +} + +/** + * Save the organization's embedding model — compare-and-set on the hash a + * change names, when it names one — and have the corpus follow it. + * Answers how many documents went back in the queue. + */ +export async function saveKnowledgeEmbedding( + sql: Sql, + org: EmbeddingOrganization, + config: unknown, + expectedHash?: string | null, +): Promise<{ requeued: number }> { + if (expectedHash === undefined) + await writeKnowledgeEmbedding(sql, org.orgSlug, config); + else await writeKnowledgeEmbedding(sql, org.orgSlug, config, expectedHash); + // Configuring a model is only half the fix: every document that failed + // while there was none stays `failed` until something re-queues it, and + // the failure text tells the operator to configure one "then retry + // indexing" — one document at a time, by hand. Do it for them, and say + // how many, so the page can report the recovery instead of looking as + // though nothing happened. + const { requeued } = await requeueEmbeddingBlockedDocuments(sql, { + organizationId: org.organizationId, + }); + if (requeued > 0) { + console.info( + `[knowledge] embedding configured for ${org.orgSlug}: re-queued ${requeued} document(s) that had failed on the embedding model`, + ); + } + const reembedded = await documentsFollowEmbedding(sql, org); + await websitesFollowEmbedding(sql, org, 'saved'); + return { requeued: requeued + reembedded }; +} + +/** Remove the organization's embedding model; the websites follow. */ +export async function removeKnowledgeEmbedding( + sql: Sql, + org: EmbeddingOrganization, +): Promise { + await deleteKnowledgeEmbedding(sql, org.orgSlug); + await websitesFollowEmbedding(sql, org, 'removed'); +} diff --git a/services/platform/backend/domains/knowledge/routes.ts b/services/platform/backend/domains/knowledge/routes.ts index b20c3ca6a4..73f03ec055 100644 --- a/services/platform/backend/domains/knowledge/routes.ts +++ b/services/platform/backend/domains/knowledge/routes.ts @@ -7,7 +7,6 @@ import { Hono, type Context } from 'hono'; import type { Sql } from 'postgres'; import { z } from 'zod'; -import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; import { EMBEDDING_SLUG } from '../../../lib/shared/constants/usage.ts'; import type { Auth } from '../../auth/auth.ts'; import { requireOrgMember, type OrgEnv } from '../../auth/org.ts'; @@ -29,24 +28,24 @@ import { isCredentialSelectionResolvable, listCredentials, } from '../provider_credentials/service.ts'; -import { websitesAfterEmbeddingChange } from '../websites/service.ts'; import { KnowledgeAdminError, deleteKnowledgeConnection, - deleteKnowledgeEmbedding, listEmbeddingRecommendationsForOrg, probeKnowledgeConnection, readKnowledgeConnectionView, readKnowledgeEmbeddingView, writeKnowledgeConnection, - writeKnowledgeEmbedding, } from './admin.ts'; +import { + assertKnowledgeAdmin, + removeKnowledgeEmbedding, + saveKnowledgeEmbedding, +} from './embedding-save.ts'; import { fetchKnowledgeDocument, KnowledgeError, searchKnowledgeForOrg, - requeueDocumentsWithoutVectors, - requeueEmbeddingBlockedDocuments, } from './service.ts'; const searchSchema = z.object({ @@ -185,16 +184,10 @@ export function createKnowledgeRoutes(deps: { // ---- Admin config (data-residency page): connection + embedding ------- const requireKnowledgeAdmin = (c: Context): Response | null => { - if ( - defineAbilityFor(c.get('orgMember').role).cannot('write', 'orgSettings') - ) { - return c.json( - { - error: 'ORG_FORBIDDEN', - message: `Role "${c.get('orgMember').role}" cannot manage the knowledge configuration.`, - }, - 403, - ); + try { + assertKnowledgeAdmin(c.get('orgMember').role); + } catch (error) { + return handleAdminError(c, error); } return null; }; @@ -288,63 +281,6 @@ export function createKnowledgeRoutes(deps: { } }); - // The websites follow the model too: their page says whether search can - // reach them, and a saved model is what embeds the pages crawled without - // one. Best-effort — the setting is saved either way; a site a failure - // here skipped is embedded by its next scheduled scan. - const websitesFollowEmbedding = async ( - organizationId: string, - orgSlug: string, - change: 'saved' | 'removed', - ): Promise => { - try { - const { queued } = await websitesAfterEmbeddingChange( - deps.sql, - organizationId, - change, - ); - if (queued > 0) { - console.info( - `[knowledge] embedding configured for ${orgSlug}: queued a scan of ${queued} website(s) to embed their pages`, - ); - } - } catch (error) { - console.warn( - `[knowledge] embedding ${change} for ${orgSlug}: the websites could not follow:`, - error instanceof Error ? error.message : error, - ); - } - }; - - // So do the documents already indexed: vectors are kept per width, so a - // model of another width finds none of theirs, and each would be missing - // from search by meaning until someone indexed it again. Best-effort like - // the websites — the setting is saved either way, and saving it again - // picks up whatever a failure here left. - const documentsFollowEmbedding = async ( - organizationId: string, - orgSlug: string, - ): Promise => { - try { - const { requeued } = await requeueDocumentsWithoutVectors(deps.sql, { - organizationId, - orgSlug, - }); - if (requeued > 0) { - console.info( - `[knowledge] embedding configured for ${orgSlug}: re-queued ${requeued} indexed document(s) that have no vector of the model's width`, - ); - } - return requeued; - } catch (error) { - console.warn( - `[knowledge] embedding saved for ${orgSlug}: the indexed documents could not follow:`, - error instanceof Error ? error.message : error, - ); - return 0; - } - }; - app.get('/embedding', async (c) => { const denied = requireKnowledgeAdmin(c); if (denied) return denied; @@ -395,30 +331,13 @@ export function createKnowledgeRoutes(deps: { const orgSlug = await orgSlugOf(c); if (orgSlug === null) return c.json({ error: 'ORG_NOT_FOUND' }, 404); try { - if (expectedHash === undefined) - await writeKnowledgeEmbedding(deps.sql, orgSlug, config); - else - await writeKnowledgeEmbedding(deps.sql, orgSlug, config, expectedHash); - // Configuring a model is only half the fix: every document that failed - // while there was none stays `failed` until something re-queues it, and - // the failure text tells the operator to configure one "then retry - // indexing" — one document at a time, by hand. Do it for them, and say - // how many, so the page can report the recovery instead of looking as - // though nothing happened. - const { requeued } = await requeueEmbeddingBlockedDocuments(deps.sql, { - organizationId: c.get('orgId'), - }); - if (requeued > 0) { - console.info( - `[knowledge] embedding configured for ${orgSlug}: re-queued ${requeued} document(s) that had failed on the embedding model`, - ); - } - const reembedded = await documentsFollowEmbedding( - c.get('orgId'), - orgSlug, + const { requeued } = await saveKnowledgeEmbedding( + deps.sql, + { organizationId: c.get('orgId'), orgSlug }, + config, + expectedHash, ); - await websitesFollowEmbedding(c.get('orgId'), orgSlug, 'saved'); - return c.json({ ok: true, requeued: requeued + reembedded }); + return c.json({ ok: true, requeued }); } catch (error) { return handleAdminError(c, error); } @@ -429,8 +348,10 @@ export function createKnowledgeRoutes(deps: { if (denied) return denied; const orgSlug = await orgSlugOf(c); if (orgSlug === null) return c.json({ error: 'ORG_NOT_FOUND' }, 404); - await deleteKnowledgeEmbedding(deps.sql, orgSlug); - await websitesFollowEmbedding(c.get('orgId'), orgSlug, 'removed'); + await removeKnowledgeEmbedding(deps.sql, { + organizationId: c.get('orgId'), + orgSlug, + }); return c.json({ ok: true }); }); From feff26bfe67a1d22501cc6c4db0469e7402f41f4 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:07:17 +0200 Subject: [PATCH 14/35] test(platform): hold the provider catalog refresh door The AI providers page's refresh had no test: a characterization pins what it answers today. Every provider the organization resolves with a live model source is listed with its model count, fetched afresh with the organization's listing key; a failed fetch reads as zero models with its reason; a member is refused before any catalog is fetched. --- .../domains/providers/config-routes.test.ts | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/services/platform/backend/domains/providers/config-routes.test.ts b/services/platform/backend/domains/providers/config-routes.test.ts index b677577182..1628d4dcd7 100644 --- a/services/platform/backend/domains/providers/config-routes.test.ts +++ b/services/platform/backend/domains/providers/config-routes.test.ts @@ -8,6 +8,7 @@ import type { Sql } from 'postgres'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { OrgEnv } from '../../auth/org'; +import { resolveProvidersForOrg } from '../../core/lib/providers/org_providers'; import { createProviderSettingRoutes } from './routes'; const { caller, catalog, transcriptionState, bearer } = vi.hoisted(() => ({ @@ -339,6 +340,75 @@ describe('native custom provider definition HTTP door', () => { expect(second?.definitionHash).not.toBe(first?.definitionHash); }); + it('refreshes every live catalog the organization resolves, reporting each count or failure behind the role gate', async () => { + expect((await put({ config: definition, expectedHash: null })).status).toBe( + 200, + ); + // A shipped or custom provider whose models come from a live source; + // a static list or none has nothing to refresh. + const live = resolveProvidersForOrg(caller.slug) + .filter( + (provider) => + provider.catalog.source !== 'static' && + provider.catalog.source !== 'none', + ) + .map((provider) => provider.name); + expect(live).toContain('local-chat'); + const model = { + id: 'model-a', + provider: 'local-chat', + contextWindow: 4096, + supportsTools: true, + supportsVision: false, + tags: ['chat'], + }; + catalog.mockImplementation(async (provider: { name: string }) => + provider.name === 'local-chat' ? [model] : [], + ); + bearer.mockResolvedValue('sk-listing'); + const refresh = () => + app().request(`/catalogs/refresh?orgId=${caller.orgId}`, { + method: 'POST', + }); + type Results = { + results: Array<{ name: string; modelCount: number; error?: string }>; + }; + const refreshed = await refresh(); + expect(refreshed.status).toBe(200); + const { results } = (await refreshed.json()) as Results; + expect(results.map((entry) => entry.name)).toEqual(live); + expect(results.find((entry) => entry.name === 'local-chat')).toEqual({ + name: 'local-chat', + modelCount: 1, + }); + expect(bearer).toHaveBeenCalledWith( + expect.anything(), + 'org-a', + expect.objectContaining({ name: 'local-chat' }), + ); + for (const [, options] of catalog.mock.calls) { + expect(options).toEqual({ + forceRefresh: true, + bearerToken: 'sk-listing', + }); + } + + catalog.mockRejectedValue(new Error('upstream refused the listing')); + const failed = (await (await refresh()).json()) as Results; + expect(failed.results.find((entry) => entry.name === 'local-chat')).toEqual( + { + name: 'local-chat', + modelCount: 0, + error: 'upstream refused the listing', + }, + ); + + catalog.mockClear(); + caller.role = 'member'; + expect((await refresh()).status).toBe(403); + expect(catalog).not.toHaveBeenCalled(); + }); + it('marks organization-defined providers in the catalog listing', async () => { catalog.mockResolvedValue([]); expect((await put({ config: definition, expectedHash: null })).status).toBe( From 3002aadbe4dab0301ada4d51a866db3d85fb1145 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:08:37 +0200 Subject: [PATCH 15/35] refactor(platform): lift the provider gate and the catalog refresh management.ts holds who may manage an organization's AI providers and the refresh of every live model catalog the organization resolves, which the AI providers door ran inline. The door answers exactly as before. --- .../backend/domains/providers/management.ts | 68 +++++++++++++++++++ .../backend/domains/providers/routes.ts | 38 +++-------- 2 files changed, 76 insertions(+), 30 deletions(-) create mode 100644 services/platform/backend/domains/providers/management.ts diff --git a/services/platform/backend/domains/providers/management.ts b/services/platform/backend/domains/providers/management.ts new file mode 100644 index 0000000000..687f0815a9 --- /dev/null +++ b/services/platform/backend/domains/providers/management.ts @@ -0,0 +1,68 @@ +import type { Sql } from 'postgres'; + +import { isAdminOrDeveloperRole } from '../../auth/membership.ts'; +import { getProviderCatalog } from '../../core/lib/providers/catalog_fetch.ts'; +import { resolveProvidersForOrg } from '../../core/lib/providers/org_providers.ts'; +import { resolveCatalogBearer } from '../provider_credentials/service.ts'; + +/** + * Who manages an organization's AI providers, and the refresh of their + * model catalogs. The AI providers page's door (`routes.ts`) gates every + * provider setting on `mayManageProviders`, and every other caller that + * reads or changes a provider asks the same question. + */ + +/** Whether a role may manage the organization's AI providers — their + * definitions, catalogs and credentials: an owner, admin or developer. */ +export function mayManageProviders(role: string): boolean { + return isAdminOrDeveloperRole(role); +} + +/** One provider's refreshed catalog: how many models it lists now, or why + * it could not be read. */ +export interface CatalogRefreshResult { + readonly name: string; + readonly modelCount: number; + readonly error?: string; +} + +/** + * Fetch afresh the model catalog of every provider the organization + * resolves whose models come from a live source — a static list or none + * has nothing to refresh — with the organization's listing key for it, + * when it holds one. A provider whose catalog cannot be fetched reads as + * zero models with the reason; the others still refresh. + */ +export async function refreshProviderCatalogs( + sql: Sql, + org: { readonly organizationId: string; readonly orgSlug: string }, +): Promise { + const results: CatalogRefreshResult[] = []; + for (const provider of resolveProvidersForOrg(org.orgSlug)) { + if ( + provider.catalog.source === 'static' || + provider.catalog.source === 'none' + ) { + continue; + } + try { + const bearerToken = await resolveCatalogBearer( + sql, + org.organizationId, + provider, + ); + const entries = await getProviderCatalog(provider, { + forceRefresh: true, + ...(bearerToken !== undefined ? { bearerToken } : {}), + }); + results.push({ name: provider.name, modelCount: entries.length }); + } catch (error) { + results.push({ + name: provider.name, + modelCount: 0, + error: error instanceof Error ? error.message : String(error), + }); + } + } + return results; +} diff --git a/services/platform/backend/domains/providers/routes.ts b/services/platform/backend/domains/providers/routes.ts index 09af0d2717..38ad7d0ba9 100644 --- a/services/platform/backend/domains/providers/routes.ts +++ b/services/platform/backend/domains/providers/routes.ts @@ -12,7 +12,6 @@ import type { Sql } from 'postgres'; import { z } from 'zod'; import type { Auth } from '../../auth/auth.ts'; -import { isAdminOrDeveloperRole } from '../../auth/membership.ts'; import { requireOrgMember, type OrgEnv } from '../../auth/org.ts'; import { requireSession } from '../../auth/session.ts'; import { ConfigurationError } from '../../core/lib/config_store/precondition'; @@ -50,6 +49,7 @@ import { readProviderDefinition, saveProviderDefinition, } from './config'; +import { mayManageProviders, refreshProviderCatalogs } from './management.ts'; /** * /api/app/providers — the AI-providers SETTINGS surface (the 0.4 @@ -75,7 +75,7 @@ export function createProviderSettingRoutes(deps: { ); const requireDeveloper = (c: Context): Response | null => - isAdminOrDeveloperRole(c.get('orgMember').role) + mayManageProviders(c.get('orgMember').role) ? null : c.json({ error: 'FORBIDDEN' }, 403); @@ -275,34 +275,12 @@ export function createProviderSettingRoutes(deps: { if (denied) return denied; const orgSlug = await orgSlugOf(c); if (orgSlug === null) return c.json({ error: 'ORG_NOT_FOUND' }, 404); - const results = []; - for (const provider of resolveProvidersForOrg(orgSlug)) { - if ( - provider.catalog.source === 'static' || - provider.catalog.source === 'none' - ) { - continue; - } - try { - const bearerToken = await resolveCatalogBearer( - deps.sql, - c.get('orgId'), - provider, - ); - const entries = await getProviderCatalog(provider, { - forceRefresh: true, - ...(bearerToken !== undefined ? { bearerToken } : {}), - }); - results.push({ name: provider.name, modelCount: entries.length }); - } catch (error) { - results.push({ - name: provider.name, - modelCount: 0, - error: error instanceof Error ? error.message : String(error), - }); - } - } - return c.json({ results }); + return c.json({ + results: await refreshProviderCatalogs(deps.sql, { + organizationId: c.get('orgId'), + orgSlug, + }), + }); }); app.get('/harness-status', async (c) => { From 72397beca6a0800c9c14e14e81d62858d3a3d353 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:10:28 +0200 Subject: [PATCH 16/35] refactor(platform): lift what follows a credential the embedding model uses embedding-follow.ts holds which credential edits the resolver reads and what follows one the embedding model resolves (the documents that failed on it re-queued, the websites scanning again), which the AI providers door ran inline after each save. The door answers exactly as before. --- .../provider_credentials/embedding-follow.ts | 91 +++++++++++++++++++ .../domains/provider_credentials/routes.ts | 90 ++---------------- 2 files changed, 100 insertions(+), 81 deletions(-) create mode 100644 services/platform/backend/domains/provider_credentials/embedding-follow.ts diff --git a/services/platform/backend/domains/provider_credentials/embedding-follow.ts b/services/platform/backend/domains/provider_credentials/embedding-follow.ts new file mode 100644 index 0000000000..45359b52af --- /dev/null +++ b/services/platform/backend/domains/provider_credentials/embedding-follow.ts @@ -0,0 +1,91 @@ +import type { Sql } from 'postgres'; + +import { requeueEmbeddingBlockedDocuments } from '../knowledge/service.ts'; +import { websitesAfterEmbeddingChange } from '../websites/service.ts'; +import { + credentialDependents, + type CredentialScope, + type UpdateCredentialPatch, +} from './service.ts'; + +/** + * What follows a change to the credential the embedding model resolves. + * The AI providers door (`routes.ts`) calls it after every save of a + * credential, and so does every other caller that adds or edits one, so the + * documents and websites follow a credential however it was changed. + */ + +/** What the credential resolver reads off a row — an edit to any of these + * can lift a refusal the embedding model failed on. A rename or a model + * allowlist changes nothing an embedding call resolves. */ +const RESOLVED_FIELDS = [ + 'status', + 'isDefault', + 'secret', + 'envName', + 'endpointUrl', +] as const satisfies readonly (keyof UpdateCredentialPatch)[]; + +/** Whether an edit changes something the credential resolver reads. */ +export function patchReachesResolver(patch: UpdateCredentialPatch): boolean { + return RESOLVED_FIELDS.some((field) => patch[field] !== undefined); +} + +/** + * A credential the embedding model resolves was added or repaired: re-queue + * the documents that failed on the embedding model, as saving the + * embedding settings does. Their failure told an admin to add or fix the + * credential, and following it used to leave every document `failed` + * until someone retried each one by hand. After the credential's own + * commit, and best-effort: the save stands either way, and a document + * left behind keeps its Retry. + * + * The websites follow the same way: a scan that ended on "the embedding + * model couldn't process the pages" names this credential too, so the + * sites whose scan failed or whose pages still lack vectors are scanned + * again, and the Websites page reads again whether search reaches them. + */ +export async function followEmbeddingCredential( + sql: Sql, + scope: CredentialScope, + credentialId: string, +): Promise { + let resolvedByEmbedding = false; + try { + const { usedBy } = await credentialDependents(sql, scope, credentialId); + if (!usedBy.includes('embedding')) return; + resolvedByEmbedding = true; + const { requeued } = await requeueEmbeddingBlockedDocuments(sql, { + organizationId: scope.organizationId, + }); + if (requeued > 0) { + console.info( + `[provider-credentials] the embedding model's credential changed: re-queued ${requeued} document(s) that had failed on the embedding model`, + ); + } + } catch (error) { + console.warn( + '[provider-credentials] could not re-queue the documents that failed on the embedding model:', + error instanceof Error ? error.message : error, + ); + } + // The documents' trouble is not the websites': they follow either way. + if (!resolvedByEmbedding) return; + try { + const { queued } = await websitesAfterEmbeddingChange( + sql, + scope.organizationId, + 'saved', + ); + if (queued > 0) { + console.info( + `[provider-credentials] the embedding model's credential changed: queued a scan of ${queued} website(s)`, + ); + } + } catch (error) { + console.warn( + '[provider-credentials] the websites could not follow the embedding credential:', + error instanceof Error ? error.message : error, + ); + } +} diff --git a/services/platform/backend/domains/provider_credentials/routes.ts b/services/platform/backend/domains/provider_credentials/routes.ts index 2e169e90b8..f6a09097dd 100644 --- a/services/platform/backend/domains/provider_credentials/routes.ts +++ b/services/platform/backend/domains/provider_credentials/routes.ts @@ -18,10 +18,12 @@ import { loadOrgCustomProviders } from '../../core/lib/providers/org_providers.t import { invalidBodyResponse } from '../../lib/invalid-body-response.ts'; import { parseNativeJsonBody } from '../../lib/native-json-body.ts'; import { resolveOrgSlug } from '../../lib/org-config.ts'; -import { requeueEmbeddingBlockedDocuments } from '../knowledge/service.ts'; import { deleteProviderDefinition } from '../providers/config.ts'; -import { websitesAfterEmbeddingChange } from '../websites/service.ts'; import { updateCredentialWithDefinition } from './custom-provider-edit.ts'; +import { + followEmbeddingCredential, + patchReachesResolver, +} from './embedding-follow.ts'; import { CredentialAdminError, createCredential, @@ -30,7 +32,6 @@ import { listCredentials, updateCredential, type CredentialScope, - type UpdateCredentialPatch, } from './service.ts'; const createSchema = providerCredentialCreateSchema.extend({ @@ -56,17 +57,6 @@ const updateWithDefinitionSchema = z.strictObject({ }), }); -/** What the credential resolver reads off a row — an edit to any of these - * can lift a refusal the embedding model failed on. A rename or a model - * allowlist changes nothing an embedding call resolves. */ -const RESOLVED_FIELDS = [ - 'status', - 'isDefault', - 'secret', - 'envName', - 'endpointUrl', -] as const satisfies readonly (keyof UpdateCredentialPatch)[]; - function handleError( c: Context, error: unknown, @@ -137,68 +127,6 @@ export function createProviderCredentialRoutes(deps: { } }); - /** - * A credential the embedding model resolves was added or repaired: re-queue - * the documents that failed on the embedding model, as saving the - * embedding settings does. Their failure told an admin to add or fix the - * credential, and following it used to leave every document `failed` - * until someone retried each one by hand. After the credential's own - * commit, and best-effort: the save stands either way, and a document - * left behind keeps its Retry. - * - * The websites follow the same way: a scan that ended on "the embedding - * model couldn't process the pages" names this credential too, so the - * sites whose scan failed or whose pages still lack vectors are scanned - * again, and the Websites page reads again whether search reaches them. - */ - async function requeueEmbeddingBlocked( - scope: CredentialScope, - credentialId: string, - ): Promise { - let resolvedByEmbedding = false; - try { - const { usedBy } = await credentialDependents( - deps.sql, - scope, - credentialId, - ); - if (!usedBy.includes('embedding')) return; - resolvedByEmbedding = true; - const { requeued } = await requeueEmbeddingBlockedDocuments(deps.sql, { - organizationId: scope.organizationId, - }); - if (requeued > 0) { - console.info( - `[provider-credentials] the embedding model's credential changed: re-queued ${requeued} document(s) that had failed on the embedding model`, - ); - } - } catch (error) { - console.warn( - '[provider-credentials] could not re-queue the documents that failed on the embedding model:', - error instanceof Error ? error.message : error, - ); - } - // The documents' trouble is not the websites': they follow either way. - if (!resolvedByEmbedding) return; - try { - const { queued } = await websitesAfterEmbeddingChange( - deps.sql, - scope.organizationId, - 'saved', - ); - if (queued > 0) { - console.info( - `[provider-credentials] the embedding model's credential changed: queued a scan of ${queued} website(s)`, - ); - } - } catch (error) { - console.warn( - '[provider-credentials] the websites could not follow the embedding credential:', - error instanceof Error ? error.message : error, - ); - } - } - app.post('/', async (c) => { const body = createSchema.safeParse(await c.req.json().catch(() => null)); if (!body.success) { @@ -210,7 +138,7 @@ export function createProviderCredentialRoutes(deps: { const credentialId = await transactSerializable(deps.sql, (tx) => createCredential(tx, scope, config, expectedHash), ); - await requeueEmbeddingBlocked(scope, credentialId); + await followEmbeddingCredential(deps.sql, scope, credentialId); return c.json({ credentialId }); } catch (error) { return handleError(c, error); @@ -229,8 +157,8 @@ export function createProviderCredentialRoutes(deps: { await transactSerializable(deps.sql, (tx) => updateCredential(tx, scope, credentialId, config, expectedHash), ); - if (RESOLVED_FIELDS.some((field) => config[field] !== undefined)) { - await requeueEmbeddingBlocked(scope, credentialId); + if (patchReachesResolver(config)) { + await followEmbeddingCredential(deps.sql, scope, credentialId); } return c.json({ ok: true }); } catch (error) { @@ -277,9 +205,9 @@ export function createProviderCredentialRoutes(deps: { expectedHash, definition, ); - // The one field here the credential resolver reads (RESOLVED_FIELDS). + // The one field here the credential resolver reads. if (patch.endpointUrl !== undefined) { - await requeueEmbeddingBlocked(scope, credentialId); + await followEmbeddingCredential(deps.sql, scope, credentialId); } return c.json({ ok: true }); } catch (error) { From bf16170a0d623c96538441a74db812269a647811 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:14:58 +0200 Subject: [PATCH 17/35] feat(platform): audit every change to the embedding model Saving an embedding model that differs from the stored one, and removing a stored one, now each leave one audit row naming the person, with the model before and after (knowledge_embedding.saved / .removed), written in the transaction that writes the file, so a failed row writes nothing. A save of the stored model, or a removal of none, leaves no row. Until now a change of the model left no trace in the audit log. KNOW-R19, with the labels in en, de and fr. --- .../backend/domains/knowledge/admin.ts | 109 ++++++++++--- .../domains/knowledge/embedding-audit.test.ts | 150 ++++++++++++++++++ .../domains/knowledge/embedding-save.ts | 24 +-- .../backend/domains/knowledge/routes.test.ts | 1 + .../backend/domains/knowledge/routes.ts | 19 ++- .../backend/domains/knowledge/spec.md | 20 ++- services/platform/messages/de/settings.yml | 3 + services/platform/messages/en/settings.yml | 3 + services/platform/messages/fr/settings.yml | 3 + .../tests/manual/reference/automation.md | 1 + 10 files changed, 300 insertions(+), 33 deletions(-) create mode 100644 services/platform/backend/domains/knowledge/embedding-audit.test.ts diff --git a/services/platform/backend/domains/knowledge/admin.ts b/services/platform/backend/domains/knowledge/admin.ts index 5e87dafe75..b3f0a2835d 100644 --- a/services/platform/backend/domains/knowledge/admin.ts +++ b/services/platform/backend/domains/knowledge/admin.ts @@ -59,6 +59,7 @@ import { hasSopsKey, invalidateSecretsCache, } from '../../core/lib/sops.ts'; +import { createAuditLog } from '../audit_logs/service.ts'; /** * The knowledge-DB + embedding ADMIN config (the 0.4 `knowledge/actions` + @@ -424,11 +425,42 @@ function assertProviderCanEmbed(orgSlug: string, providerSlug: string): void { } } +/** Who changes the embedding model, recorded on its audit row. */ +export interface KnowledgeAuditActor { + readonly organizationId: string; + readonly userId: string; + readonly email?: string; +} + +/** The fields every audit row of the embedding model carries. */ +function embeddingAuditFields(actor: KnowledgeAuditActor) { + return { + organizationId: actor.organizationId, + actorId: actor.userId, + ...(actor.email !== undefined ? { actorEmail: actor.email } : {}), + actorType: 'user' as const, + category: 'admin' as const, + resourceType: 'knowledge_embedding', + resourceId: KNOWLEDGE_EMBEDDING_KEY, + status: 'success' as const, + }; +} + +/** + * Save the organization's embedding model, compare-and-set on the hash a + * change names. With an actor, a save that changes the stored model leaves + * one audit row (`knowledge_embedding.saved`) with the model before and + * after, written in the transaction that holds the knowledge config's + * write lock and before the file, so a failed write takes the row back; a + * save of what is stored leaves none. `sql` is the root handle: the write + * opens its own transaction. + */ export async function writeKnowledgeEmbedding( sql: Sql, orgSlug: string, config: unknown, expectedHash?: string | null, + actor?: KnowledgeAuditActor, ): Promise { // The similarity floor and the serving limits are settings the Settings // form does not carry (see `resolveKeptEmbeddingSettings`), so the body @@ -444,20 +476,31 @@ export async function writeKnowledgeEmbedding( assertHostAllowed(parsed.data.baseUrl); } assertProviderCanEmbed(orgSlug, parsed.data.providerSlug); - await withConfigWriteLock(sql, orgSlug, 'knowledge', async () => { - const current = await readKnowledgeEmbeddingView(orgSlug); - if (expectedHash !== undefined) - assertExpectedHash(current.hash, expectedHash); - const filePath = embeddingFilePath(orgSlug); - const serialized = serializeEmbeddingJson( - resolveKeptEmbeddingSettings(parsed.data, current.config), - ); - const currentContent = await readFileSafe(filePath); - if (currentContent) { - await snapshotHistory(orgSlug, KNOWLEDGE_EMBEDDING_KEY, currentContent); - } - await atomicWrite(filePath, serialized); - }); + await sql.begin((tx) => + withConfigWriteLock(tx, orgSlug, 'knowledge', async () => { + const current = await readKnowledgeEmbeddingView(orgSlug); + if (expectedHash !== undefined) + assertExpectedHash(current.hash, expectedHash); + const filePath = embeddingFilePath(orgSlug); + const next = resolveKeptEmbeddingSettings(parsed.data, current.config); + const serialized = serializeEmbeddingJson(next); + const currentContent = await readFileSafe(filePath); + if (actor !== undefined && currentContent !== serialized) { + await createAuditLog(tx, { + ...embeddingAuditFields(actor), + action: 'knowledge_embedding.saved', + ...(current.config !== null + ? { previousState: { ...current.config } } + : {}), + newState: { ...next }, + }); + } + if (currentContent) { + await snapshotHistory(orgSlug, KNOWLEDGE_EMBEDDING_KEY, currentContent); + } + await atomicWrite(filePath, serialized); + }), + ); } /** @@ -482,14 +525,44 @@ export function resolveKeptEmbeddingSettings( return knowledgeEmbeddingSchema.parse(next); } +/** + * Remove the organization's embedding model and its history. With an + * actor, removing a stored model leaves one audit row + * (`knowledge_embedding.removed`) with the model removed, written in the + * same transaction before the file goes; removing none leaves none. + * `sql` is the root handle: the removal opens its own transaction. + */ export async function deleteKnowledgeEmbedding( sql: Sql, orgSlug: string, + actor?: KnowledgeAuditActor, ): Promise { - await withConfigWriteLock(sql, orgSlug, 'knowledge', async () => { - await removeFileSafe(embeddingFilePath(orgSlug)); - await removeDirSafe(historyDir(orgSlug, KNOWLEDGE_EMBEDDING_KEY)); - }); + await sql.begin((tx) => + withConfigWriteLock(tx, orgSlug, 'knowledge', async () => { + const filePath = embeddingFilePath(orgSlug); + if (actor !== undefined && (await readFileSafe(filePath)) !== null) { + // A model that no longer parses is still removed, and the row says + // so without it: a broken file is exactly what someone removes. + let removed: Record | undefined; + try { + const { config } = await readKnowledgeEmbeddingView(orgSlug); + if (config !== null) removed = { ...config }; + } catch (error) { + console.warn( + `[knowledge] the embedding model removed for ${orgSlug} was unreadable; its audit row names none:`, + error instanceof Error ? error.message : error, + ); + } + await createAuditLog(tx, { + ...embeddingAuditFields(actor), + action: 'knowledge_embedding.removed', + ...(removed !== undefined ? { previousState: removed } : {}), + }); + } + await removeFileSafe(filePath); + await removeDirSafe(historyDir(orgSlug, KNOWLEDGE_EMBEDDING_KEY)); + }), + ); } export interface EmbeddingRecommendation { diff --git a/services/platform/backend/domains/knowledge/embedding-audit.test.ts b/services/platform/backend/domains/knowledge/embedding-audit.test.ts new file mode 100644 index 0000000000..2a11d9ae18 --- /dev/null +++ b/services/platform/backend/domains/knowledge/embedding-audit.test.ts @@ -0,0 +1,150 @@ +// @vitest-environment node + +/** + * The embedding model's audit rows: a save that changes the model and a + * removal of a stored one each leave one row naming who made it, written + * in the transaction that writes the file; a save of what is stored, or a + * removal of nothing, leaves none. The config store is a temporary + * directory; the database is a double that runs the transaction's callback + * and answers the write lock's statement. + */ + +import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { createAuditLog } = vi.hoisted(() => ({ createAuditLog: vi.fn() })); +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog })); + +import { deleteKnowledgeEmbedding, writeKnowledgeEmbedding } from './admin.ts'; + +const ADA = { + organizationId: 'org-1', + userId: 'user-ada', + email: 'ada@example.test', +}; + +const MODEL = { + providerSlug: 'local-embedding', + model: 'example-embedding', + dimensions: 1024, +}; + +/** A database whose transaction runs its callback on a tag that answers + * every statement with no rows. */ +function fakeSql(): { sql: Sql; tx: unknown } { + const tx = async () => []; + const begin = (callback: (handle: unknown) => Promise) => + callback(tx); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: { begin } as unknown as Sql, tx }; +} + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(path.join(tmpdir(), 'tale-embedding-audit-')); + vi.stubEnv('TALE_CONFIG_DIR', dir); + createAuditLog.mockReset(); + createAuditLog.mockResolvedValue('row-1'); +}); + +afterEach(async () => { + vi.unstubAllEnvs(); + await rm(dir, { recursive: true, force: true }); +}); + +describe('a change to the embedding model is audited [KNOW-R19]', () => { + it('records a save that changes the model once, with the model before and after, in the write transaction', async () => { + const { sql, tx } = fakeSql(); + await writeKnowledgeEmbedding(sql, 'acme', MODEL, null, ADA); + expect(createAuditLog).toHaveBeenCalledOnce(); + expect(createAuditLog).toHaveBeenLastCalledWith( + tx, + expect.objectContaining({ + organizationId: 'org-1', + actorId: 'user-ada', + actorEmail: 'ada@example.test', + action: 'knowledge_embedding.saved', + category: 'admin', + resourceType: 'knowledge_embedding', + newState: MODEL, + }), + ); + expect(createAuditLog.mock.lastCall?.[1]).not.toHaveProperty( + 'previousState', + ); + + // The same model again changes nothing, and records nothing. + await writeKnowledgeEmbedding(sql, 'acme', MODEL, undefined, ADA); + expect(createAuditLog).toHaveBeenCalledOnce(); + + const next = { ...MODEL, model: 'example-embedding-2' }; + await writeKnowledgeEmbedding(sql, 'acme', next, undefined, ADA); + expect(createAuditLog).toHaveBeenCalledTimes(2); + expect(createAuditLog.mock.lastCall?.[1]).toMatchObject({ + action: 'knowledge_embedding.saved', + previousState: MODEL, + newState: next, + }); + }); + + it('writes no file when the audit row cannot be written', async () => { + const { sql } = fakeSql(); + createAuditLog.mockRejectedValue(new Error('audit chain unavailable')); + await expect( + writeKnowledgeEmbedding(sql, 'acme', MODEL, null, ADA), + ).rejects.toThrow('audit chain unavailable'); + createAuditLog.mockResolvedValue('row-2'); + // Nothing was stored: the same save still creates the model. + await writeKnowledgeEmbedding(sql, 'acme', MODEL, null, ADA); + expect(createAuditLog).toHaveBeenCalledTimes(2); + }); + + it('records the removal of a stored model, and nothing when none is stored', async () => { + const { sql, tx } = fakeSql(); + await deleteKnowledgeEmbedding(sql, 'acme', ADA); + expect(createAuditLog).not.toHaveBeenCalled(); + + await writeKnowledgeEmbedding(sql, 'acme', MODEL, null, ADA); + createAuditLog.mockClear(); + await deleteKnowledgeEmbedding(sql, 'acme', ADA); + expect(createAuditLog).toHaveBeenCalledOnce(); + expect(createAuditLog).toHaveBeenLastCalledWith( + tx, + expect.objectContaining({ + action: 'knowledge_embedding.removed', + actorId: 'user-ada', + resourceType: 'knowledge_embedding', + previousState: MODEL, + }), + ); + }); + + it('still removes a model whose file no longer parses, and records the removal without it', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const { sql } = fakeSql(); + const knowledge = path.join(dir, 'acme', 'knowledge'); + await mkdir(knowledge, { recursive: true }); + await writeFile(path.join(knowledge, 'embedding.json'), '{ not json'); + await deleteKnowledgeEmbedding(sql, 'acme', ADA); + expect(createAuditLog).toHaveBeenCalledOnce(); + expect(createAuditLog.mock.lastCall?.[1]).toMatchObject({ + action: 'knowledge_embedding.removed', + }); + expect(createAuditLog.mock.lastCall?.[1]).not.toHaveProperty( + 'previousState', + ); + warn.mockRestore(); + }); + + it('records nothing for a write that names no one', async () => { + const { sql } = fakeSql(); + await writeKnowledgeEmbedding(sql, 'acme', MODEL); + await deleteKnowledgeEmbedding(sql, 'acme'); + expect(createAuditLog).not.toHaveBeenCalled(); + }); +}); diff --git a/services/platform/backend/domains/knowledge/embedding-save.ts b/services/platform/backend/domains/knowledge/embedding-save.ts index d5bffaa42d..8755bfce31 100644 --- a/services/platform/backend/domains/knowledge/embedding-save.ts +++ b/services/platform/backend/domains/knowledge/embedding-save.ts @@ -3,7 +3,11 @@ import type { Sql } from 'postgres'; import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; import { ConfigurationError } from '../../core/lib/config_store/precondition'; import { websitesAfterEmbeddingChange } from '../websites/service.ts'; -import { deleteKnowledgeEmbedding, writeKnowledgeEmbedding } from './admin.ts'; +import { + deleteKnowledgeEmbedding, + writeKnowledgeEmbedding, + type KnowledgeAuditActor, +} from './admin.ts'; import { requeueDocumentsWithoutVectors, requeueEmbeddingBlockedDocuments, @@ -100,18 +104,18 @@ async function documentsFollowEmbedding( /** * Save the organization's embedding model — compare-and-set on the hash a - * change names, when it names one — and have the corpus follow it. - * Answers how many documents went back in the queue. + * change names, when it names one, and audited under the person who saved + * it — and have the corpus follow it. Answers how many documents went back + * in the queue. */ export async function saveKnowledgeEmbedding( sql: Sql, org: EmbeddingOrganization, config: unknown, - expectedHash?: string | null, + expectedHash: string | null | undefined, + actor: KnowledgeAuditActor, ): Promise<{ requeued: number }> { - if (expectedHash === undefined) - await writeKnowledgeEmbedding(sql, org.orgSlug, config); - else await writeKnowledgeEmbedding(sql, org.orgSlug, config, expectedHash); + await writeKnowledgeEmbedding(sql, org.orgSlug, config, expectedHash, actor); // Configuring a model is only half the fix: every document that failed // while there was none stays `failed` until something re-queues it, and // the failure text tells the operator to configure one "then retry @@ -131,11 +135,13 @@ export async function saveKnowledgeEmbedding( return { requeued: requeued + reembedded }; } -/** Remove the organization's embedding model; the websites follow. */ +/** Remove the organization's embedding model, audited under the person + * who removed it; the websites follow. */ export async function removeKnowledgeEmbedding( sql: Sql, org: EmbeddingOrganization, + actor: KnowledgeAuditActor, ): Promise { - await deleteKnowledgeEmbedding(sql, org.orgSlug); + await deleteKnowledgeEmbedding(sql, org.orgSlug, actor); await websitesFollowEmbedding(sql, org, 'removed'); } diff --git a/services/platform/backend/domains/knowledge/routes.test.ts b/services/platform/backend/domains/knowledge/routes.test.ts index 96bb3844b7..9284160f79 100644 --- a/services/platform/backend/domains/knowledge/routes.test.ts +++ b/services/platform/backend/domains/knowledge/routes.test.ts @@ -180,6 +180,7 @@ describe('reviewed embedding HTTP updates', () => { 'acme', config, null, + { organizationId: 'o1', userId: 'u1', email: 'u@example.test' }, ); expect(requeueEmbeddingBlockedDocuments).toHaveBeenCalledWith( expect.anything(), diff --git a/services/platform/backend/domains/knowledge/routes.ts b/services/platform/backend/domains/knowledge/routes.ts index 73f03ec055..3ad530f4fe 100644 --- a/services/platform/backend/domains/knowledge/routes.ts +++ b/services/platform/backend/domains/knowledge/routes.ts @@ -193,6 +193,15 @@ export function createKnowledgeRoutes(deps: { }; const orgSlugOf = async (c: Context): Promise => resolveOrgSlug(deps.sql, c.get('orgId')); + /** The admin a change of the knowledge configuration is recorded under. */ + const actorOf = (c: Context) => { + const user = c.get('sessionBundle').user; + return { + organizationId: c.get('orgId'), + userId: user.id, + ...(user.email !== undefined ? { email: user.email } : {}), + }; + }; const handleAdminError = (c: Context, error: unknown): Response => { if ( error instanceof KnowledgeAdminError || @@ -336,6 +345,7 @@ export function createKnowledgeRoutes(deps: { { organizationId: c.get('orgId'), orgSlug }, config, expectedHash, + actorOf(c), ); return c.json({ ok: true, requeued }); } catch (error) { @@ -348,10 +358,11 @@ export function createKnowledgeRoutes(deps: { if (denied) return denied; const orgSlug = await orgSlugOf(c); if (orgSlug === null) return c.json({ error: 'ORG_NOT_FOUND' }, 404); - await removeKnowledgeEmbedding(deps.sql, { - organizationId: c.get('orgId'), - orgSlug, - }); + await removeKnowledgeEmbedding( + deps.sql, + { organizationId: c.get('orgId'), orgSlug }, + actorOf(c), + ); return c.json({ ok: true }); }); diff --git a/services/platform/backend/domains/knowledge/spec.md b/services/platform/backend/domains/knowledge/spec.md index d8df818087..14e8e7d9d5 100644 --- a/services/platform/backend/domains/knowledge/spec.md +++ b/services/platform/backend/domains/knowledge/spec.md @@ -5,8 +5,8 @@ The knowledge base holds an organization's documents and the pages of the websites it added, prepared for search (indexed). These rules cover whose content a search reads, what it finds for the person asking, what is indexed and what is refused, what happens when the embedding -model is missing or fails, how much a search returns, and what the website crawler will not -fetch. The settings pages, the repair of the search index, the removal of indexed content, +model is missing or fails, who changed the embedding model, how much a search returns, and +what the website crawler will not fetch. The settings pages, the repair of the search index, the removal of indexed content, ranking and most of the crawler are not covered; see Not yet. ## One organization's knowledge base @@ -267,6 +267,22 @@ is raised, after what it had already stored. - **Example**: A REST client searches with a key whose daily request limit is reached → 429 `BUDGET_EXCEEDED`, naming the key's limit and when it resets. +## Who changed the embedding model + +### KNOW-R19 · Every change to the embedding model leaves an audit entry naming who made it + +Saving a model that differs from the stored one, and removing a stored model, each leave one +entry in the organization's audit log naming the person, with the model before and after. The +entry is written together with the change: a change that fails leaves none, and an entry never +names a change that did not happen. Saving the model that is already stored, or removing a +model when none is set, leaves none. A model whose settings no longer read is still removed, +and its entry then names no model. + +- **Example**: Ada switches the embedding model from `text-embedding-3-small` to + `text-embedding-3-large` → the audit log shows **Embedding model saved** by Ada with both + models. She saves the page again without changing it → no new entry. Noah, also an admin, + removes the model → **Embedding model removed** by Noah. + ## How much a search returns ### KNOW-R13 · A search returns at most 50 passages, and 10 unless asked otherwise diff --git a/services/platform/messages/de/settings.yml b/services/platform/messages/de/settings.yml index 98c69826b3..3262ac550c 100644 --- a/services/platform/messages/de/settings.yml +++ b/services/platform/messages/de/settings.yml @@ -1325,6 +1325,8 @@ logs: folder.deleted: Ordner gelöscht knowledge_entry.created: Wissenseintrag erstellt knowledge_entry.updated: Wissenseintrag aktualisiert + knowledge_embedding.saved: Embedding-Modell gespeichert + knowledge_embedding.removed: Embedding-Modell entfernt branding.updated: Branding aktualisiert branding.image_uploaded: Branding-Bild hochgeladen branding.image_deleted: Branding-Bild entfernt @@ -1538,6 +1540,7 @@ logs: document: Dokument folder: Ordner knowledge_entry: Wissenseintrag + knowledge_embedding: Embedding-Modell agent: Agent workflow: Automatisierung workflow_run: Automatisierungslauf diff --git a/services/platform/messages/en/settings.yml b/services/platform/messages/en/settings.yml index 3a5eb89ee8..ea94c9a25a 100644 --- a/services/platform/messages/en/settings.yml +++ b/services/platform/messages/en/settings.yml @@ -1268,6 +1268,8 @@ logs: folder.deleted: Folder deleted knowledge_entry.created: Knowledge entry created knowledge_entry.updated: Knowledge entry updated + knowledge_embedding.saved: Embedding model saved + knowledge_embedding.removed: Embedding model removed branding.updated: Branding updated branding.image_uploaded: Branding image uploaded branding.image_deleted: Branding image removed @@ -1481,6 +1483,7 @@ logs: document: Document folder: Folder knowledge_entry: Knowledge entry + knowledge_embedding: Embedding model agent: Agent workflow: Automation workflow_run: Automation run diff --git a/services/platform/messages/fr/settings.yml b/services/platform/messages/fr/settings.yml index 94da371ad1..527b29fa5b 100644 --- a/services/platform/messages/fr/settings.yml +++ b/services/platform/messages/fr/settings.yml @@ -1355,6 +1355,8 @@ logs: folder.deleted: Dossier supprimé knowledge_entry.created: Entrée de connaissances créée knowledge_entry.updated: Entrée de connaissances mise à jour + knowledge_embedding.saved: Modèle d’embedding enregistré + knowledge_embedding.removed: Modèle d’embedding supprimé branding.updated: Branding mis à jour branding.image_uploaded: Image de branding chargée branding.image_deleted: Image de branding retirée @@ -1568,6 +1570,7 @@ logs: document: Document folder: Dossier knowledge_entry: Entrée de connaissances + knowledge_embedding: Modèle d’embedding agent: Agent workflow: Automatisation workflow_run: Exécution d'automatisation diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 64fcd50a04..1016eab9ac 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -945,6 +945,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [automations](../suites/automations.md) | Automation documents are analysed before they run (the validator's fifth pass): every value is typed — a node's output from its connector signature, its `outputSchema`, the llm or agent envelope, a transform's return literals or the automation it calls, the run input from `inputs` — and every way a run can go is enumerated from the `when` conditions and the `onError: continue` failures. Warnings, each with `at` and `params`: a field the data cannot have (`REF_UNKNOWN_FIELD`), a value of a kind its consumer refuses (`TYPE_MISMATCH`), an optional or nullable value placed inside text (`TEMPLATE_NULL_INTERPOLATION`), a name nothing declares (`EXPR_UNKNOWN_NAME`), a field of a node that may be skipped read in a condition or the output (`MAYBE_NULL`, with `?.`, `&&`, `?:` and merged elseOf branches recognised as guards and `??` after a member read not), a tolerated failure that resurfaces there (`UNCAUGHT_FAILURE`), a node that can never run (`UNREACHABLE`) and the node only it reads (`UNUSED_NODE`), an output that may be empty (`OUTPUT_MAYBE_EMPTY`), a constant condition and a loop that never stops early or ignores its pass, a subautomation input the called version refuses, a test input, effect or output that cannot pass, and a schedule trigger the inputs schema refuses (`TRIGGER_INPUT_MISMATCH`). Errors: `forEach` that is not one list-valued template, an agent that iterates, and `item`/`index` where nothing declares them (`ITEM_OUT_OF_SCOPE`, `ITEM_WITHOUT_FOREACH` in templates). A subautomation is checked as the version a run calls; every shipped document validates without an error, its warnings match a reviewed snapshot, and the flow model predicts the real runs of the shipped tests; `detail` returns the per-node summary, the paths and the types | ✅ unit + golden + corpus | `lib/engine/core/analysis/rules/names.test.ts`, `types.test.ts`, `iteration.test.ts`, `conditions.test.ts`, `flow.test.ts`, `tests.test.ts`, `lib/engine/core/analysis/summary.test.ts`, `corpus.test.ts` (`corpus.snapshot.yml`), `lib/engine/core/validate/golden-errors.test.ts` (`golden-errors.yml`), `lib/engine/core/validate/validate.test.ts`, `backend/domains/automations/dispatch-store.list-triggers.test.ts`; the editor shows them in Problems (the Problems row below) | | [automations](../suites/automations.md) | Validation results for agents and people: `validate_automation` answers the `analysis` (the per-node summary and the possible paths) and the `types` beside its issues — a host may ask for less with `detail`, the MCP door always gets both; a save answers the warnings the saved version keeps, a refused save names its warnings beside its errors, the deploy refusal keeps its keys, and `get_catalog` gives each capability its output as an `outputSchema`; `get_docs` explains an issue's `at`, `params` and `related`, the analysis and the types. Every engine code has a title, an explanation, a cause and a fix in EN/DE/FR (the Swiss German without ß or „“): a sentence reads only its code's params and the derived ones (node names the way the canvas shows them, field labels the way the inspector shows them, quoted lists of at most six and a count), never a technical one, and a code the build does not know reads as words, never as a key | ✅ unit + MCP wire + catalog guard | `lib/engine/selftest/dispatch.test.ts`, `lib/engine/api/dispatch.refusals.test.ts`, `backend/domains/mcp/protocol.test.ts`, `lib/i18n/automation-issue-keys.test.ts`, `app/features/automations/lib/issue-text.test.ts` (every golden issue rendered in every locale); the editor shows them in Problems (the Problems row below) | | CI workflow operations | A same-head duplicate may release only its predecessor’s sole unallocated final-check tail after canceled actual work; complete fresh PR, run and paged job identities are required. Default reads do not mutate; explicit apply journals at most one cancellation and preserves unknown outcomes without retry. | ✅ pure policy + bounded adapter | `tools/cli/scripts/ci-retire-tail.test.ts`; native runner admission and terminal cancellation remain live observations | +| [data-residency](../suites/data-residency.md) / [knowledge](../suites/knowledge.md) | Every change to the embedding model is audited (KNOW-R19): a save that changes the stored model and the removal of a stored one each write one `knowledge_embedding.saved` / `knowledge_embedding.removed` row naming the person, with the model before and after, inside the transaction that writes the file — a failed audit row writes no file; a save of the stored model and a removal of none write no row; a model whose file no longer parses is still removed, its row naming none | ✅ backend | `backend/domains/knowledge/embedding-audit.test.ts`, `backend/domains/knowledge/routes.test.ts`; the row as the audit log shows it stays manual | ## Documentation rebase regressions From afa1e343ab4100a850eb09e0bbf7d6d6fa9fbb01 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:20:14 +0200 Subject: [PATCH 18/35] refactor(platform): give the settings handlers a shared kit A kind's handler now answers what the caller may do through the database when its gate needs it (access takes the call's context), and the kinds share one kit beside the registry: the refusal a handler throws, a config read through the kind's schema that names a field the schema would drop, the identity of a resource, pages of a listing and the caller as the writers record them. The handlers are composed in handlers.ts, which serves none yet. --- .../backend/domains/mcp/settings/get.ts | 15 +- .../backend/domains/mcp/settings/handlers.ts | 10 + .../backend/domains/mcp/settings/kit.test.ts | 170 +++++++++++ .../backend/domains/mcp/settings/kit.ts | 271 ++++++++++++++++++ .../backend/domains/mcp/settings/registry.ts | 15 +- .../domains/mcp/settings/settings.test.ts | 2 +- .../backend/domains/mcp/settings/tools.ts | 3 +- 7 files changed, 470 insertions(+), 16 deletions(-) create mode 100644 services/platform/backend/domains/mcp/settings/handlers.ts create mode 100644 services/platform/backend/domains/mcp/settings/kit.test.ts create mode 100644 services/platform/backend/domains/mcp/settings/kit.ts diff --git a/services/platform/backend/domains/mcp/settings/get.ts b/services/platform/backend/domains/mcp/settings/get.ts index 1ae846990c..ac2bde82be 100644 --- a/services/platform/backend/domains/mcp/settings/get.ts +++ b/services/platform/backend/domains/mcp/settings/get.ts @@ -43,13 +43,13 @@ export async function getSettings( query: SettingsQuery, ): Promise> { if (query.kinds === undefined) { - return { - kinds: SETTINGS_KINDS.map((descriptor) => { + const kinds = await Promise.all( + SETTINGS_KINDS.map(async (descriptor) => { const handler = registry[descriptor.kind]; - const access = handler?.access(ctx.caller) ?? { - read: false, - write: false, - }; + const access = + handler === undefined + ? { read: false, write: false } + : await handler.access(ctx); return { kind: descriptor.kind, scope: descriptor.scope, @@ -63,6 +63,9 @@ export async function getSettings( write: access.write, }; }), + ); + return { + kinds, resources: [], refused: [], nextCursor: null, diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts new file mode 100644 index 0000000000..f0183049b9 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -0,0 +1,10 @@ +/** + * The settings kinds this deployment serves over MCP: each kind's handler, + * registered beside the native writer it calls (`backend/domains// + * settings-resource.ts`). A kind the shared descriptors name without a + * handler here is answered as not available on this deployment. + */ + +import type { SettingsRegistry } from './registry.ts'; + +export const SETTINGS_HANDLERS: SettingsRegistry = {}; diff --git a/services/platform/backend/domains/mcp/settings/kit.test.ts b/services/platform/backend/domains/mcp/settings/kit.test.ts new file mode 100644 index 0000000000..6fe579af8e --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/kit.test.ts @@ -0,0 +1,170 @@ +// @vitest-environment node + +import { describe, expect, it } from 'vitest'; +import { z } from 'zod'; + +import { refusalFromThrown } from '../refusals.ts'; +import { + droppedMembers, + identifySingle, + identityOf, + pageOf, + parseSettingsConfig, + SettingsRefusalError, +} from './kit.ts'; + +function refused(run: () => unknown): SettingsRefusalError { + try { + run(); + } catch (error) { + if (error instanceof SettingsRefusalError) return error; + throw error; + } + throw new Error('expected a refusal'); +} + +describe('a handler refusal', () => { + it('reaches the agent as a refusal with its code, sentence, hint and data', () => { + expect( + refusalFromThrown( + new SettingsRefusalError('SETTINGS_TALE_ONLY', 'made in Tale', { + hint: 'open Settings', + data: { area: 'branding' }, + }), + ), + ).toEqual({ + error: 'made in Tale', + code: 'SETTINGS_TALE_ONLY', + hint: 'open Settings', + data: { area: 'branding' }, + }); + }); +}); + +describe('reading a change through its kind', () => { + const policy = z.object({ + minLength: z.number().int().min(8), + rules: z.array(z.object({ name: z.string() })).default([]), + }); + + it('answers what the writer would store, defaults included', () => { + expect( + parseSettingsConfig(policy, { minLength: 12 }, 'the policy'), + ).toEqual({ minLength: 12, rules: [] }); + }); + + it('names every problem by where it is, never by what was sent', () => { + const error = refused(() => + parseSettingsConfig( + policy, + { minLength: 'sk-not-a-number', rules: [{ name: 4 }] }, + 'the policy', + ), + ); + expect(error.code).toBe('SETTINGS_INVALID'); + expect(error.data?.issues).toEqual([ + { + path: '/config/minLength', + code: 'invalid_type', + message: expect.any(String), + }, + { + path: '/config/rules/0/name', + code: 'invalid_type', + message: expect.any(String), + }, + ]); + expect(JSON.stringify(error.data)).not.toContain('sk-not-a-number'); + expect(error.message).toMatch( + /^the policy is not valid: \/config\/minLength /, + ); + }); + + it('refuses a field the setting does not have instead of dropping it', () => { + const error = refused(() => + parseSettingsConfig( + policy, + { minLength: 12, minLenght: 14, rules: [{ name: 'a', nmae: 'b' }] }, + 'the policy', + ), + ); + expect(error.data?.issues).toEqual([ + { + path: '/config/minLenght', + code: 'unrecognized_key', + message: 'is not a field of this setting', + }, + { + path: '/config/rules/0/nmae', + code: 'unrecognized_key', + message: 'is not a field of this setting', + }, + ]); + }); + + it('escapes a member name in its pointer', () => { + expect(droppedMembers({ 'a/b~c': 1 }, {})).toEqual([ + { + path: '/config/a~1b~0c', + code: 'unrecognized_key', + message: 'is not a field of this setting', + }, + ]); + }); +}); + +describe('the identity of a resource', () => { + it('takes no id for a kind with one resource', () => { + expect(identifySingle('branding')({ kind: 'branding', op: 'set' })).toBe( + null, + ); + expect( + refused(() => + identifySingle('branding')({ kind: 'branding', id: 'x', op: 'set' }), + ).code, + ).toBe('SETTINGS_ID_INVALID'); + }); + + it('takes the id named, the one the config carries, or both when they agree', () => { + expect(identityOf('provider', 'vendor', undefined, 'its name')).toBe( + 'vendor', + ); + expect(identityOf('provider', undefined, 'vendor', 'its name')).toBe( + 'vendor', + ); + expect(identityOf('provider', 'vendor', 'vendor', 'its name')).toBe( + 'vendor', + ); + expect( + refused(() => identityOf('provider', 'vendor', 'other', 'its name')).code, + ).toBe('SETTINGS_ID_INVALID'); + expect( + refused(() => identityOf('provider', undefined, undefined, 'its name')) + .code, + ).toBe('SETTINGS_ID_REQUIRED'); + }); +}); + +describe('pages of a listing', () => { + const items = Array.from({ length: 5 }, (_, index) => index); + + it('walks a listing page by page with the cursor each page answers', () => { + const first = pageOf(items, undefined, 2); + expect(first).toEqual({ items: [0, 1], nextCursor: 'p2' }); + const second = pageOf(items, first.nextCursor ?? undefined, 2); + expect(second).toEqual({ items: [2, 3], nextCursor: 'p4' }); + expect(pageOf(items, second.nextCursor ?? undefined, 2)).toEqual({ + items: [4], + nextCursor: null, + }); + }); + + it.each(['', '2', 'p0', 'p-1', 'p01', 'pp2'])( + 'refuses the cursor %j, which no page answered', + (cursor) => { + expect(refused(() => pageOf(items, cursor, 2)).code).toBe( + 'INVALID_CURSOR', + ); + }, + ); +}); diff --git a/services/platform/backend/domains/mcp/settings/kit.ts b/services/platform/backend/domains/mcp/settings/kit.ts new file mode 100644 index 0000000000..d215aafc53 --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/kit.ts @@ -0,0 +1,271 @@ +/** + * What every settings kind's handler shares: the refusal a handler throws, + * a change's config read through its kind's schema without a field lost to + * normalization, the identity of a resource, pages of a listing, and the + * person a change is recorded under. A handler (`backend/domains// + * settings-resource.ts`) adds only its kind's native reads and writers. + */ + +import type { SettingsKind } from '@tale/shared/schemas/settings-kinds'; + +import { isRecord } from '../../../../lib/utils/type-utils.ts'; +import type { SettingsChange, SettingsContext } from './registry.ts'; + +/** One problem with a change, as a refusal lists it: where (a pointer into + * the change), what kind of problem, and why — never the value sent. */ +export interface SettingsIssue { + readonly path: string; + readonly code: string; + readonly message: string; +} + +/** + * A refusal a settings handler throws: a stable code, its own sentence, a + * hint naming what to do instead, and data. `refusalFromThrown` answers it + * as the agent reads every refusal, with a 4xx status that marks it as one. + */ +export class SettingsRefusalError extends Error { + readonly code: string; + readonly status: 400 | 403 | 404 | 409; + readonly hint?: string; + readonly data?: Record; + + constructor( + code: string, + message: string, + options: { + readonly status?: 400 | 403 | 404 | 409; + readonly hint?: string; + readonly data?: Record; + } = {}, + ) { + super(message); + this.name = 'SettingsRefusalError'; + this.code = code; + this.status = options.status ?? 400; + if (options.hint !== undefined) this.hint = options.hint; + if (options.data !== undefined) this.data = options.data; + } +} + +/** How many problems one refusal lists. */ +const MAX_ISSUES = 20; + +function escapeToken(token: string): string { + return token.replaceAll('~', '~0').replaceAll('/', '~1'); +} + +/** An RFC 6901 pointer into the change's config. */ +function configPointer(path: readonly PropertyKey[]): string { + return `/config${path.map((part) => `/${escapeToken(String(part))}`).join('')}`; +} + +/** A parse's failure as a schema library reports it. */ +interface ParseFailure { + readonly issues: ReadonlyArray<{ + readonly path: readonly PropertyKey[]; + readonly code: string; + readonly message: string; + }>; +} + +/** The problems of a failed parse, as issues of the change. */ +export function configIssues(error: ParseFailure): SettingsIssue[] { + return error.issues.map((issue) => ({ + path: configPointer(issue.path), + code: issue.code, + message: issue.message, + })); +} + +/** + * The members of what a change sent that its kind's parse dropped: a field + * the setting does not have would otherwise vanish without a word, and the + * change would read as made. + */ +export function droppedMembers( + sent: unknown, + parsed: unknown, + at: readonly PropertyKey[] = [], +): SettingsIssue[] { + if (Array.isArray(sent)) { + if (!Array.isArray(parsed)) return []; + return sent.flatMap((item, index) => + droppedMembers(item, parsed[index], [...at, index]), + ); + } + if (!isRecord(sent) || !isRecord(parsed)) return []; + return Object.entries(sent).flatMap(([name, value]) => + Object.hasOwn(parsed, name) + ? droppedMembers(value, parsed[name], [...at, name]) + : [ + { + path: configPointer([...at, name]), + code: 'unrecognized_key', + message: 'is not a field of this setting', + }, + ], + ); +} + +/** The refusal of a change whose config its kind does not take. */ +export function invalidSettings( + what: string, + issues: readonly SettingsIssue[], +): SettingsRefusalError { + const listed = issues.slice(0, MAX_ISSUES); + const [first] = listed; + const more = + issues.length > 1 ? ` (and ${issues.length - 1} more problems)` : ''; + return new SettingsRefusalError( + 'SETTINGS_INVALID', + `${what} is not valid${first === undefined ? '' : `: ${first.path} ${first.message}`}${more}`, + { + hint: 'fix every problem in data.issues and plan again; tale://docs/settings names the fields of each kind', + data: { issues: listed }, + }, + ); +} + +/** A schema as a handler reads a change's config through it. */ +interface ConfigSchema { + safeParse( + value: unknown, + ): { success: true; data: T } | { success: false; error: ParseFailure }; +} + +/** + * A change's config read through its kind's schema: what the native writer + * would store, or a refusal naming every problem — a field the schema does + * not have among them. + */ +export function parseSettingsConfig( + schema: ConfigSchema, + config: unknown, + what: string, +): T { + const parsed = schema.safeParse(config); + const issues = parsed.success + ? droppedMembers(config, parsed.data) + : configIssues(parsed.error); + if (!parsed.success || issues.length > 0) { + throw invalidSettings(what, issues); + } + return parsed.data; +} + +/** The identity of a kind with one resource: a change names none. */ +export function identifySingle( + kind: SettingsKind, +): (change: SettingsChange) => null { + return (change) => { + if (change.id !== undefined) { + throw new SettingsRefusalError( + 'SETTINGS_ID_INVALID', + `${kind} has a single resource, so a change names no id`, + { hint: 'leave id out' }, + ); + } + return null; + }; +} + +/** + * The id of a resource a change names — by `id`, by what its config + * carries, or both when they agree. + */ +export function identityOf( + kind: SettingsKind, + named: string | undefined, + carried: string | undefined, + form: string, +): string { + if (named !== undefined && carried !== undefined && named !== carried) { + throw new SettingsRefusalError( + 'SETTINGS_ID_INVALID', + `the id of this ${kind} change names another resource than its config does`, + { + hint: `the id is ${form}; send the id get_settings answered, with the config of that same resource`, + }, + ); + } + const id = named ?? carried; + if (id === undefined) { + throw new SettingsRefusalError( + 'SETTINGS_ID_REQUIRED', + `a ${kind} change names the resource it changes`, + { hint: `the id is ${form}; get_settings with kinds lists them` }, + ); + } + return id; +} + +/** A cursor this listing answered: the place its next page starts. */ +const CURSOR = /^p([1-9]\d{0,6})$/; + +/** + * One page of a listing that reads everything it lists at once: `size` + * resources from where the cursor says, and the cursor of the next page + * when there is one. + */ +export function pageOf( + items: readonly T[], + cursor: string | undefined, + size: number, +): { items: T[]; nextCursor: string | null } { + let offset = 0; + if (cursor !== undefined) { + const match = CURSOR.exec(cursor); + if (match === null) { + throw new SettingsRefusalError( + 'INVALID_CURSOR', + 'the cursor is not one this listing answered', + { + hint: 'pass the nextCursor get_settings answered for this kind, or none for its first page', + }, + ); + } + offset = Number(match[1]); + } + const end = offset + size; + return { + items: items.slice(offset, end), + nextCursor: end < items.length ? `p${end}` : null, + }; +} + +/** The person a change acts as and is recorded under. */ +export interface SettingsActor { + readonly organizationId: string; + readonly userId: string; + readonly email?: string; + readonly role: string; +} + +const EMAILS = new WeakMap>(); + +/** The caller's sign-in address, read once per call: the writers record it + * on their audit rows, and the deployment's editors are listed by it. */ +export function callerEmail(ctx: SettingsContext): Promise { + let email = EMAILS.get(ctx); + if (email === undefined) { + email = ctx.sql<{ email: string | null }[]>` + SELECT "email" FROM "user" WHERE "id" = ${ctx.caller.userId} LIMIT 1 + `.then((rows) => rows[0]?.email ?? undefined); + EMAILS.set(ctx, email); + } + return email; +} + +/** The caller as the native writers take an actor. */ +export async function settingsActor( + ctx: SettingsContext, +): Promise { + const email = await callerEmail(ctx); + return { + organizationId: ctx.caller.organizationId, + userId: ctx.caller.userId, + ...(email === undefined ? {} : { email }), + role: ctx.caller.role, + }; +} diff --git a/services/platform/backend/domains/mcp/settings/registry.ts b/services/platform/backend/domains/mcp/settings/registry.ts index 5d2cd7ab89..c5084bd290 100644 --- a/services/platform/backend/domains/mcp/settings/registry.ts +++ b/services/platform/backend/domains/mcp/settings/registry.ts @@ -79,7 +79,10 @@ export interface SettingsPage { export interface SettingsKindHandler { readonly kind: SettingsKind; - access(caller: McpCaller): SettingsAccess; + /** What the caller may do with the kind, read through the same gates + * the kind's writers apply — some need the database (who is an admin + * anywhere, the caller's address for an allowlist). */ + access(ctx: SettingsContext): Promise; /** The id a change names — its `id`, or the one its config carries; null * for a kind with a single resource. Throws a coded refusal when the * change names none. */ @@ -113,17 +116,13 @@ export interface SettingsKindHandler { ): Promise<{ readonly hash: string | null }>; } +/** The kinds a deployment serves over MCP, by kind (`handlers.ts`). A kind + * the shared descriptors name without a handler here is answered as not + * available on the deployment. */ export type SettingsRegistry = Readonly< Partial> >; -/** - * The kinds this deployment serves over MCP, each handler registered beside - * its native writer. A kind the shared descriptors name without a handler - * here is answered as not available on this deployment. - */ -export const SETTINGS_HANDLERS: SettingsRegistry = {}; - /** A resource's address in a call — the key `expected` names it by: its * kind, then its id when it has one, the form a declaration's resource id * takes. */ diff --git a/services/platform/backend/domains/mcp/settings/settings.test.ts b/services/platform/backend/domains/mcp/settings/settings.test.ts index 3860aa50b6..2536db6754 100644 --- a/services/platform/backend/domains/mcp/settings/settings.test.ts +++ b/services/platform/backend/domains/mcp/settings/settings.test.ts @@ -90,7 +90,7 @@ function fake(): Fake { }; return { kind, - access: (caller) => ({ + access: async ({ caller }) => ({ read: true, write: caller.role === 'admin' || caller.role === 'owner', }), diff --git a/services/platform/backend/domains/mcp/settings/tools.ts b/services/platform/backend/domains/mcp/settings/tools.ts index 3e700dfd99..9baafed18b 100644 --- a/services/platform/backend/domains/mcp/settings/tools.ts +++ b/services/platform/backend/domains/mcp/settings/tools.ts @@ -12,8 +12,9 @@ import { PLATFORM_TOOL_ARGS } from '../../../../lib/mcp/args.ts'; import type { McpCaller } from '../caller.ts'; import { applySettings } from './apply.ts'; import { getSettings } from './get.ts'; +import { SETTINGS_HANDLERS } from './handlers.ts'; import { planSettings } from './plan.ts'; -import { SETTINGS_HANDLERS, type SettingsRegistry } from './registry.ts'; +import type { SettingsRegistry } from './registry.ts'; /** One settings tool, acting as the caller in the caller's organization. */ export async function dispatchSettingsTool( From 22081a54467fbff5f0202e7daa232e694a2a0308 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:21:54 +0200 Subject: [PATCH 19/35] feat(platform): mask a credential stored anywhere in a setting an agent reads A settings read masked only the places a kind declares secret, but a person can paste a key into a policy's header or an instruction in Tale, and those settings declare none. A read now also masks every string the credential detector recognises, the detector that already refuses one on the way in, and a change may send such a mask back to keep what is stored there; a mask anywhere Tale masked nothing is refused. MCP-R12 says so. --- .../domains/mcp/settings/secrets.test.ts | 55 ++++++++++++++++ .../backend/domains/mcp/settings/secrets.ts | 64 +++++++++++++++---- services/platform/backend/domains/mcp/spec.md | 27 ++++---- 3 files changed, 121 insertions(+), 25 deletions(-) diff --git a/services/platform/backend/domains/mcp/settings/secrets.test.ts b/services/platform/backend/domains/mcp/settings/secrets.test.ts index 0d0530db6f..6af244a721 100644 --- a/services/platform/backend/domains/mcp/settings/secrets.test.ts +++ b/services/platform/backend/domains/mcp/settings/secrets.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { isMaskedSecret, + maskedPlaces, maskSecrets, restoreMaskedSecrets, secretArgumentRefusal, @@ -171,3 +172,57 @@ describe('keeping a stored secret through a masked value', () => { }); }); }); + +describe('a credential stored where no secret belongs', () => { + // A person can paste a key into a policy's header or an instruction in + // Tale; a read over MCP never answers it. + const policy = { + enabled: true, + endpoint: { + url: 'https://moderation.example.invalid', + headers: { Authorization: `Bearer ${PASTED}`, Accept: 'json' }, + }, + note: `the old key was ${PASTED}`, + }; + + it('is masked wherever the detector finds it, beside the secrets a path names [MCP-R12]', () => { + expect(maskedPlaces(policy, []).sort()).toEqual([ + '/endpoint/headers/Authorization', + '/note', + ]); + const masked = maskSecrets(policy, []); + expect(JSON.stringify(masked)).not.toContain(PASTED); + expect(masked).toMatchObject({ + enabled: true, + endpoint: { + url: 'https://moderation.example.invalid', + headers: { + Authorization: { masked: true }, + Accept: 'json', + }, + }, + note: { masked: true }, + }); + }); + + it('is kept when a change sends its mask back, and its mask is taken nowhere else [MCP-R12]', () => { + const sent = maskSecrets({ ...policy, enabled: false }, []); + expect(restoreMaskedSecrets(sent, policy, [])).toEqual({ + config: { ...policy, enabled: false }, + }); + const elsewhere = { + ...policy, + endpoint: { ...policy.endpoint, url: { masked: true } }, + }; + expect(restoreMaskedSecrets(elsewhere, policy, [])).toEqual({ + refusal: expect.objectContaining({ + code: 'SECRET_ARGUMENT_REFUSED', + data: { + places: [ + { pointer: '/config/endpoint/url', kind: 'nothing stored to keep' }, + ], + }, + }), + }); + }); +}); diff --git a/services/platform/backend/domains/mcp/settings/secrets.ts b/services/platform/backend/domains/mcp/settings/secrets.ts index 43e30e2310..eb232c816a 100644 --- a/services/platform/backend/domains/mcp/settings/secrets.ts +++ b/services/platform/backend/domains/mcp/settings/secrets.ts @@ -1,7 +1,9 @@ /** * No secret crosses MCP, in or out. A secret a resource stores reads as a - * masked value wherever a settings tool answers it. A change may carry that - * masked value back unchanged, which keeps what is stored, and nothing else + * masked value wherever a settings tool answers it, and so does any string + * the credential detector recognises elsewhere in a stored config — a key + * someone pasted into an instruction in Tale. A change may carry a masked + * value back unchanged, which keeps what is stored there, and nothing else * in a secret's place; every string a change carries also goes through the * credential detector, so a key pasted into a description is refused the * same way. A refusal names where a secret was found and what it looked @@ -127,13 +129,30 @@ export function secretPlaces( return [...places]; } +/** + * Every place a settings tool masks in a stored config: each place a + * secret path names, and every string the credential detector recognises + * wherever it sits — a key someone pasted into a description or a header + * in Tale is masked on the way out, as it is refused on the way in. + */ +export function maskedPlaces( + value: unknown, + secretPaths: readonly string[], +): string[] { + const places = new Set(secretPlaces(value, secretPaths)); + for (const hit of findSecrets(value)) { + if (hit.pointer !== '') places.add(hit.pointer); + } + return [...places]; +} + /** A config with every secret it holds masked — what a settings tool * answers in place of what is stored. */ export function maskSecrets( config: unknown, secretPaths: readonly string[], ): unknown { - const places = secretPlaces(config, secretPaths); + const places = maskedPlaces(config, secretPaths); if (places.length === 0) return config; const masked = structuredClone(config); for (const place of places) { @@ -195,34 +214,51 @@ export function secretArgumentRefusal( return places.size === 0 ? null : secretRefusal([...places.values()]); } +/** Every place in a value that holds a masked value. */ +function maskedValuePlaces(value: unknown): string[] { + const places: string[] = []; + const walk = (node: unknown, at: string): void => { + if (isMaskedSecret(node)) { + places.push(at); + } else if (Array.isArray(node)) { + node.forEach((item, index) => walk(item, `${at}/${index}`)); + } else if (isRecord(node)) { + for (const [name, item] of Object.entries(node)) { + walk(item, `${at}/${escapeToken(name)}`); + } + } + }; + walk(value, ''); + return places.filter((place) => place !== ''); +} + /** * The config a change asks for, with every masked value put back to what - * is stored at the same place, so the native writer keeps it. Where the + * is stored at the same place, so the native writer keeps it — at a + * secret's place and wherever else a read masked a credential. Where the * native read itself answers only a mask, the masked value stays for the - * writer, which keeps its stored secret; a masked value where nothing is - * stored keeps nothing, and is refused. + * writer, which keeps its stored secret; a masked value where nothing + * masked is stored keeps nothing, and is refused. */ export function restoreMaskedSecrets( config: unknown, stored: unknown, secretPaths: readonly string[], ): { readonly config: unknown } | { readonly refusal: McpRefusal } { - const places = secretPlaces(config, secretPaths).filter((place) => { - const sent = valueAt(config, place); - return sent.found && isMaskedSecret(sent.value); - }); + const places = maskedValuePlaces(config); if (places.length === 0) return { config }; + const kept = new Set(maskedPlaces(stored, secretPaths)); const restored = structuredClone(config); const missing: SecretPlace[] = []; for (const place of places) { - const kept = valueAt(stored, place); - if (!kept.found || kept.value === null) { + const value = valueAt(stored, place); + if (!kept.has(place) || !value.found || value.value === null) { missing.push({ pointer: `/config${place}`, kind: 'nothing stored to keep', }); - } else if (!isMaskedSecret(kept.value)) { - replaceAt(restored, place, kept.value); + } else if (!isMaskedSecret(value.value)) { + replaceAt(restored, place, value.value); } } if (missing.length > 0) { diff --git a/services/platform/backend/domains/mcp/spec.md b/services/platform/backend/domains/mcp/spec.md index b5b0fe36a1..3509c2e9f5 100644 --- a/services/platform/backend/domains/mcp/spec.md +++ b/services/platform/backend/domains/mcp/spec.md @@ -16,13 +16,13 @@ the Tale skill is the one file an agent installs to work here. A call acts as the person who holds the API key, in the organization the key names, with that person's role in it at the time of the request. -| | Owner, admin or developer | Any other member | -| --- | --- | --- | -| Save a version, deploy one, delete an automation, set or remove a trigger | yes | no | -| Install an automation in projects or remove it from them | yes | no | -| Start or stop a live run | yes | no | -| Read, validate and test automations, run them on the mocks, start a mock run | yes | yes | -| Answer a run's question | yes | yes, in a project they can edit | +| | Owner, admin or developer | Any other member | +| ---------------------------------------------------------------------------- | ------------------------- | ------------------------------- | +| Save a version, deploy one, delete an automation, set or remove a trigger | yes | no | +| Install an automation in projects or remove it from them | yes | no | +| Start or stop a live run | yes | no | +| Read, validate and test automations, run them on the mocks, start a mock run | yes | yes | +| Answer a run's question | yes | yes, in a project they can edit | Reads and runs reach only the automations the app would show the person (MCP-R9). @@ -197,14 +197,19 @@ applied, what failed and what was skipped. ### MCP-R12 · No secret goes into or comes out of a settings call -A stored secret reads as masked, with a short excerpt at most. A change may send that masked -value back to keep the stored secret, and nothing else in its place; a credential anywhere else -in a change — a key pasted into a description — refuses the change, naming where it was found -and never the value (`SECRET_ARGUMENT_REFUSED`). A person enters a new secret in Tale. +A stored secret reads as masked, with a short excerpt at most, and so does a credential found +anywhere else in a stored setting — a key someone pasted into an instruction or a header in +Tale. A change may send a masked value back to keep what is stored there, and nothing else in +its place; a credential anywhere else in a change — a key pasted into a description — refuses +the change, naming where it was found and never the value (`SECRET_ARGUMENT_REFUSED`). A person +enters a new secret in Tale. - **Example**: Ada's agent reads a provider whose key is stored → the key reads as masked; it changes the address and sends the masked key back → the stored key is kept; it sends a key it typed instead → refused, and the answer names the field, not the key. +- **Example**: Ben once pasted an API key into the organization's system prompt in Tale. Ada's + agent reads the policy → the prompt reads as masked; the agent changes another field and sends + the masked prompt back → the prompt is kept as Ben wrote it. ## Answers and refusals From 99a6e7c319b8793177c3973a51fee6bfdfa91609 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 23:27:56 +0200 Subject: [PATCH 20/35] feat(platform): change organization policies over MCP The governance kind reads and changes one policy per key through the policy writer the Settings pages use: a member reads the policies any member may read and changes none, an owner or admin every one; a change is checked as the save checks it (schema, a field the policy lacks, the standard agent's runtime, the sandbox capacity) and audited by the writer. A plan says who a change may lock out or sign out and which human approval it removes. The retention and data subject request policies stay with their staged workflows in Tale. MCP-R10. --- packages/shared/src/schemas/settings-kinds.ts | 14 + .../domains/governance/policy-writer.ts | 23 +- .../governance/settings-resource.test.ts | 474 ++++++++++++++++++ .../domains/governance/settings-resource.ts | 305 +++++++++++ .../backend/domains/mcp/settings/handlers.ts | 5 +- services/platform/backend/domains/mcp/spec.md | 19 +- 6 files changed, 830 insertions(+), 10 deletions(-) create mode 100644 services/platform/backend/domains/governance/settings-resource.test.ts create mode 100644 services/platform/backend/domains/governance/settings-resource.ts diff --git a/packages/shared/src/schemas/settings-kinds.ts b/packages/shared/src/schemas/settings-kinds.ts index 98c4d7bab0..26a6abbd67 100644 --- a/packages/shared/src/schemas/settings-kinds.ts +++ b/packages/shared/src/schemas/settings-kinds.ts @@ -292,6 +292,20 @@ export const SETTINGS_KINDS_NOT_OVER_MCP = [ reason: string; }>; +/** + * Organization policies the `governance` kind does not take, each with + * the reason an agent is told: two change through staged workflows of + * their own in Tale, and one is retired. + */ +export const GOVERNANCE_KEYS_NOT_OVER_MCP = { + retention_policy: + 'changes through its staged workflow in Tale, under Settings > Governance > Policies & limits', + dsar_governance: + 'changes through its staged workflow in Tale, under Settings > Governance > Data subject requests', + conversation_access: + 'is retired: conversation privacy is always on, and nothing reads it', +} as const satisfies Readonly>; + const BY_KIND: ReadonlyMap = new Map( SETTINGS_KINDS.map((descriptor) => [descriptor.kind, descriptor]), ); diff --git a/services/platform/backend/domains/governance/policy-writer.ts b/services/platform/backend/domains/governance/policy-writer.ts index 171bd3de62..24af546a7f 100644 --- a/services/platform/backend/domains/governance/policy-writer.ts +++ b/services/platform/backend/domains/governance/policy-writer.ts @@ -78,6 +78,12 @@ export interface GovernancePolicyActor { readonly role: string; } +/** Whether a role may change the organization's policies: an owner or an + * admin. */ +export function mayChangeGovernancePolicies(role: string): boolean { + return isAdmin(role); +} + function unknownPolicy(policyType: string): GovernancePolicyError { return new GovernancePolicyError( 'UNKNOWN_POLICY_TYPE', @@ -115,20 +121,25 @@ export function assertGovernancePolicyReadable( /** * A policy as its file holds it now, past every cache, with the hash its * writer checks a change against: no policy and a null hash when the - * organization has never saved one. + * organization has never saved one. The organization's slug is resolved + * afresh unless the caller already read it for this request. */ export async function readGovernancePolicySnapshotFor( sql: Sql, - member: { readonly organizationId: string; readonly role: string }, + member: { + readonly organizationId: string; + readonly role: string; + readonly orgSlug?: string; + }, policyType: string, ): Promise<{ policy: { key: FilePolicyType; config: unknown } | null; hash: string | null; }> { const type = assertGovernancePolicyReadable(member.role, policyType); - const orgSlug = await resolveOrgSlug(sql, member.organizationId, { - fresh: true, - }); + const orgSlug = + member.orgSlug ?? + (await resolveOrgSlug(sql, member.organizationId, { fresh: true })); if (orgSlug === null) throw organizationGone(); const { readGovernancePolicySnapshot } = await import('../../lib/governance-policy-write'); @@ -172,7 +183,7 @@ export async function checkGovernancePolicy( { answersMessage: true }, ); } - if (!isAdmin(actor.role)) { + if (!mayChangeGovernancePolicies(actor.role)) { throw new GovernancePolicyError( 'FORBIDDEN', 'Only owners and admins can change organization policies.', diff --git a/services/platform/backend/domains/governance/settings-resource.test.ts b/services/platform/backend/domains/governance/settings-resource.test.ts new file mode 100644 index 0000000000..01285921cc --- /dev/null +++ b/services/platform/backend/domains/governance/settings-resource.test.ts @@ -0,0 +1,474 @@ +// @vitest-environment node + +/** + * Organization policies over MCP, through the policy writer the Settings + * pages use: the files, the audit chain and the sandbox service are + * doubles, the gates and checks are the writer's own. + */ + +import { POLICY_SCHEMAS } from '@tale/shared/schemas/governance'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { + createAuditLog, + emitHintInTx, + getSandboxDeploymentLimits, + readGovernancePolicyForOrg, + readGovernancePolicySnapshot, + resolveOrgSlug, + stored, + writeGovernancePolicyFile, +} = vi.hoisted(() => ({ + createAuditLog: vi.fn(), + emitHintInTx: vi.fn(), + getSandboxDeploymentLimits: vi.fn(), + readGovernancePolicyForOrg: vi.fn(), + readGovernancePolicySnapshot: vi.fn(), + resolveOrgSlug: vi.fn(async () => 'acme'), + // The policy files of organization "acme", by policy. + stored: new Map(), + writeGovernancePolicyFile: vi.fn(), +})); + +vi.mock('@tale/shared/db/serializable', () => ({ + transactSerializable: ( + _sql: unknown, + work: (tx: unknown) => Promise, + ) => work({ tx: true }), +})); +vi.mock('../../lib/org-config.ts', () => ({ + readGovernancePolicyForOrg, + resolveOrgSlug, +})); +vi.mock('../../lib/governance-policy-write.ts', () => ({ + readGovernancePolicySnapshot, + writeGovernancePolicyFile, +})); +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog })); +vi.mock('../../realtime/outbox.ts', () => ({ emitHintInTx })); +vi.mock('../sandbox/limits.ts', () => ({ getSandboxDeploymentLimits })); +vi.mock('../sandbox/unused-rule.ts', () => ({ + recordUnusedWorkspaceRule: vi.fn(), +})); + +import { ConfigurationError } from '../../core/lib/config_store/precondition'; +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { governanceEffects, governanceSettings } from './settings-resource.ts'; + +const registry = { governance: governanceSettings }; + +function caller(role: string): McpCaller { + return { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; +} + +/** A database that knows each caller's address and nothing else. */ +function sqlDouble(): Sql { + const tag = async () => [{ email: 'person@example.test' }]; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return tag as unknown as Sql; +} + +function contextOf(role: string): SettingsContext { + return { sql: sqlDouble(), caller: caller(role) }; +} + +const hashOf = (config: unknown) => configurationHash(config); + +beforeEach(() => { + vi.clearAllMocks(); + stored.clear(); + stored.set('password_policy', { + minLength: 12, + requireUpper: true, + requireLower: true, + requireDigit: true, + requireSpecial: true, + rotationDays: 0, + }); + stored.set('feature_flags', { rules: [], enabled: true }); + // The file read through the policy's own schema, as the writer reads it. + readGovernancePolicySnapshot.mockImplementation( + async (_slug: string, key: keyof typeof POLICY_SCHEMAS) => { + const file = stored.get(key); + return file === undefined + ? { config: null, hash: null } + : { config: POLICY_SCHEMAS[key].parse(file), hash: hashOf(file) }; + }, + ); + readGovernancePolicyForOrg.mockImplementation( + async (_sql: unknown, _org: string, key: string) => stored.get(key) ?? null, + ); + writeGovernancePolicyFile.mockImplementation( + async ( + _tx: unknown, + _slug: string, + key: string, + config: unknown, + expected?: string | null, + ) => { + const current = stored.get(key); + if ( + expected !== undefined && + (current === undefined ? null : hashOf(current)) !== expected + ) { + throw new ConfigurationError( + 'CONFIG_VERSION_CONFLICT', + 'Configuration changed since it was reviewed.', + ); + } + stored.set(key, config); + }, + ); + getSandboxDeploymentLimits.mockResolvedValue({ + status: 'available', + maxSessions: 16, + }); +}); + +describe('who reads and changes the policies', () => { + it('lets every member read and only an owner or admin change', async () => { + expect(await governanceSettings.access(contextOf('member'))).toEqual({ + read: true, + write: false, + }); + expect(await governanceSettings.access(contextOf('admin'))).toEqual({ + read: true, + write: true, + }); + }); + + it('lists to a member only the policies any member may read', async () => { + const page = await governanceSettings.list(contextOf('member'), {}); + expect(page.items.map((item) => item.id)).toEqual(['feature_flags']); + const admin = await governanceSettings.list(contextOf('admin'), {}); + expect(admin.items.map((item) => item.id)).toEqual( + expect.arrayContaining(['feature_flags', 'password_policy']), + ); + expect(admin.items).toHaveLength(2); + expect(admin.items[0]).toHaveProperty('hash'); + }); + + it('refuses a member a policy named that only owners and admins read', async () => { + await expect( + governanceSettings.list(contextOf('member'), { + ids: ['password_policy'], + }), + ).rejects.toMatchObject({ code: 'FORBIDDEN', status: 403 }); + }); + + it('changes a policy only where the role can in the app [MCP-R10]', async () => { + // Any member reads the feature flags; only an owner or admin changes them. + const change = { + kind: 'governance' as const, + id: 'feature_flags', + op: 'set' as const, + config: { rules: [], enabled: false }, + }; + const expected = { + 'governance/feature_flags': hashOf(stored.get('feature_flags')), + }; + const refused = await applySettings( + contextOf('member'), + registry, + [change], + expected, + ); + expect(refused).toMatchObject({ + code: 'FORBIDDEN', + error: 'Only owners and admins can change organization policies.', + hint: expect.stringContaining('an owner or admin can'), + applied: [], + }); + expect(writeGovernancePolicyFile).not.toHaveBeenCalled(); + // A policy only owners and admins read is refused at the read. + const hidden = await planSettings(contextOf('member'), registry, [ + { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: stored.get('password_policy'), + }, + ]); + expect(hidden.changes[0]?.refusal).toMatchObject({ code: 'FORBIDDEN' }); + + const applied = await applySettings( + contextOf('admin'), + registry, + [change], + expected, + ); + expect(applied).toEqual({ + applied: [ + { + kind: 'governance', + id: 'feature_flags', + key: 'governance/feature_flags', + action: 'update', + hash: hashOf(stored.get('feature_flags')), + }, + ], + skipped: [], + }); + expect(stored.get('feature_flags')).toEqual({ rules: [], enabled: false }); + // The writer's own audit row, under the person who holds the key. + expect(createAuditLog).toHaveBeenCalledWith( + { tx: true }, + expect.objectContaining({ + actorId: 'user-admin', + actorEmail: 'person@example.test', + action: 'governance_policy.updated', + resourceId: 'feature_flags', + }), + ); + }); +}); + +describe('naming a policy', () => { + it.each([ + [undefined, 'SETTINGS_ID_REQUIRED'], + ['retention_policy', 'SETTINGS_TALE_ONLY'], + ['dsar_governance', 'SETTINGS_TALE_ONLY'], + ['conversation_access', 'UNKNOWN_POLICY_TYPE'], + ['no_such_policy', 'UNKNOWN_POLICY_TYPE'], + ])('refuses %j as %s', (id, code) => { + expect(() => + governanceSettings.identify({ + kind: 'governance', + ...(id === undefined ? {} : { id }), + op: 'set', + config: {}, + }), + ).toThrow(expect.objectContaining({ code })); + }); +}); + +describe('planning a policy change', () => { + it('names every problem of a config, a field the policy does not have among them', async () => { + const plan = await planSettings(contextOf('admin'), registry, [ + { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: { minLength: 3, minLenght: 14 }, + }, + ]); + expect(plan.ok).toBe(false); + expect(plan.changes[0]?.refusal).toMatchObject({ + code: 'SETTINGS_INVALID', + data: { + issues: [expect.objectContaining({ path: '/config/minLength' })], + }, + }); + const misspelled = await planSettings(contextOf('admin'), registry, [ + { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: { minLenght: 14 }, + }, + ]); + expect(misspelled.changes[0]?.refusal?.data).toEqual({ + issues: [ + { + path: '/config/minLenght', + code: 'unrecognized_key', + message: 'is not a field of this setting', + }, + ], + }); + }); + + it('weighs sandbox budgets against the deployment, as the save does', async () => { + const quota = { + maxSessionsPerOrg: 9, + maxWorkflowSessionsPerOrg: 8, + maxRenderSessionsPerOrg: 6, + }; + const over = await planSettings(contextOf('admin'), registry, [ + { kind: 'governance', id: 'sandbox_quota', op: 'set', config: quota }, + ]); + expect(over.changes[0]?.refusal).toMatchObject({ + code: 'SANDBOX_QUOTA_EXCEEDS_DEPLOYMENT', + data: { total: 23, maxSessions: 16 }, + }); + getSandboxDeploymentLimits.mockResolvedValue({ + status: 'unavailable', + reason: 'unreachable', + }); + const unknown = await planSettings(contextOf('admin'), registry, [ + { kind: 'governance', id: 'sandbox_quota', op: 'set', config: quota }, + ]); + expect(unknown.changes[0]?.refusal).toMatchObject({ + code: 'SANDBOX_CAPACITY_UNAVAILABLE', + hint: expect.stringContaining('lowering'), + }); + expect(writeGovernancePolicyFile).not.toHaveBeenCalled(); + }); + + it('refuses a standard agent runtime the managed lane cannot run, naming those it can', async () => { + const plan = await planSettings(contextOf('admin'), registry, [ + { + kind: 'governance', + id: 'standard_agent', + op: 'set', + config: { enabled: true, harness: 'cursor' }, + }, + ]); + expect(plan.changes[0]?.refusal).toMatchObject({ + code: 'STANDARD_AGENT_HARNESS_INVALID', + data: { harnesses: expect.arrayContaining(['claude-code']) }, + }); + }); + + it('says what a change does beyond its value, and that a change to what is stored does nothing', async () => { + const current = stored.get('password_policy') as Record; + const plan = await planSettings(contextOf('admin'), registry, [ + { + kind: 'governance', + id: 'password_policy', + op: 'set', + config: { ...current, rotationDays: 90 }, + }, + { + kind: 'governance', + id: 'feature_flags', + op: 'set', + config: { rules: [], enabled: true }, + }, + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'update', + effects: ['may-lock-out-members'], + risk: 'critical', + diff: [{ path: '/rotationDays', before: 0, after: 90 }], + }); + expect(plan.changes[1]).toMatchObject({ + action: 'unchanged', + effects: [], + risk: 'low', + }); + }); +}); + +describe('applying a policy change', () => { + it('lands only on the policy the agent read', async () => { + const read = stored.get('feature_flags') as Record; + const before = hashOf(read); + // Someone turns the flags off in the app after the agent read them. + stored.set('feature_flags', { ...read, enabled: false }); + const answer = await applySettings( + contextOf('admin'), + registry, + [ + { + kind: 'governance', + id: 'feature_flags', + op: 'set', + config: { rules: [], enabled: true }, + }, + ], + { 'governance/feature_flags': before }, + ); + expect(answer).toMatchObject({ + code: 'SETTINGS_STALE', + data: { currentHash: hashOf(stored.get('feature_flags')) }, + }); + expect(writeGovernancePolicyFile).not.toHaveBeenCalled(); + }); + + it('creates a policy never saved, expecting none', async () => { + const answer = await applySettings( + contextOf('owner'), + registry, + [ + { + kind: 'governance', + id: 'session_idle_timeout', + op: 'set', + config: { enabled: true, idleTimeoutMinutes: 60 }, + }, + ], + { 'governance/session_idle_timeout': null }, + ); + expect(answer).toMatchObject({ + applied: [{ action: 'create', key: 'governance/session_idle_timeout' }], + }); + expect(writeGovernancePolicyFile).toHaveBeenCalledWith( + { tx: true }, + 'acme', + 'session_idle_timeout', + { enabled: true, idleTimeoutMinutes: 60 }, + null, + ); + }); +}); + +describe('what a policy change does', () => { + it('names a lockout, a sign-out or a removed approval only where one happens', () => { + expect(governanceEffects('login_policy', null, { enabled: true })).toEqual([ + 'may-lock-out-members', + ]); + expect(governanceEffects('login_policy', null, { enabled: false })).toEqual( + [], + ); + expect( + governanceEffects( + 'password_policy', + { rotationDays: 90 }, + { rotationDays: 180 }, + ), + ).toEqual([]); + expect( + governanceEffects( + 'two_factor_policy', + { enforced: true, gracePeriodDays: 7, exemptSsoUsers: true }, + { enforced: true, gracePeriodDays: 3, exemptSsoUsers: true }, + ), + ).toEqual(['may-lock-out-members']); + expect( + governanceEffects( + 'two_factor_policy', + { enforced: true, gracePeriodDays: 7, exemptSsoUsers: true }, + { enforced: true, gracePeriodDays: 14, exemptSsoUsers: true }, + ), + ).toEqual([]); + expect( + governanceEffects( + 'session_idle_timeout', + { enabled: true, idleTimeoutMinutes: 60 }, + { enabled: true, idleTimeoutMinutes: 30 }, + ), + ).toEqual(['signs-out-members']); + const gated = { + rules: [{ connector: 'github', decision: 'require_approval' }], + }; + expect( + governanceEffects('approval_policy', gated, { + rules: [{ connector: 'github', decision: 'auto_approve' }], + }), + ).toEqual(['removes-human-approval']); + expect(governanceEffects('approval_policy', gated, { rules: [] })).toEqual([ + 'removes-human-approval', + ]); + expect(governanceEffects('approval_policy', null, gated)).toEqual([]); + expect( + governanceEffects( + 'review_policy', + { requireIndependentReviewer: true, requiredCompetences: ['legal'] }, + { requireIndependentReviewer: true, requiredCompetences: [] }, + ), + ).toEqual(['removes-human-approval']); + expect(governanceEffects('budgets', null, { rules: [] })).toEqual([]); + }); +}); diff --git a/services/platform/backend/domains/governance/settings-resource.ts b/services/platform/backend/domains/governance/settings-resource.ts new file mode 100644 index 0000000000..ba51a60c71 --- /dev/null +++ b/services/platform/backend/domains/governance/settings-resource.ts @@ -0,0 +1,305 @@ +import { + FILE_POLICY_TYPES, + isFilePolicyType, + POLICY_SCHEMAS, + type FilePolicyType, +} from '@tale/shared/schemas/governance'; +import { + GOVERNANCE_KEYS_NOT_OVER_MCP, + type SettingsEffect, +} from '@tale/shared/schemas/settings-kinds'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { + identityOf, + pageOf, + parseSettingsConfig, + settingsActor, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsChange, + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { + assertGovernancePolicyReadable, + checkGovernancePolicy, + GovernancePolicyError, + mayChangeGovernancePolicies, + readGovernancePolicySnapshotFor, + saveGovernancePolicy, +} from './policy-writer.ts'; + +/** + * The organization's policies as a settings kind over MCP (`governance`): + * one resource per policy, named by its key. Every read and change goes + * through the policy writer the Settings pages use (`policy-writer.ts`), + * with its gates, its checks and its audit row; this module adds what an + * agent needs to weigh a change — which policies it may name, and what a + * change does beyond the value it sets. + */ + +const ID_FORM = 'the policy key, such as password_policy'; + +/** The policy an id names, when the kind takes it. */ +function policyKey(id: string): FilePolicyType { + if (Object.hasOwn(GOVERNANCE_KEYS_NOT_OVER_MCP, id)) { + const reason: string = Reflect.get(GOVERNANCE_KEYS_NOT_OVER_MCP, id); + throw id === 'conversation_access' + ? new SettingsRefusalError('UNKNOWN_POLICY_TYPE', `${id} ${reason}`, { + hint: 'tale://docs/settings lists the policies this kind takes', + }) + : new SettingsRefusalError('SETTINGS_TALE_ONLY', `${id} ${reason}`, { + hint: 'tell the person where to change it in Tale; nothing over MCP changes it', + }); + } + if (!isFilePolicyType(id)) { + throw new SettingsRefusalError( + 'UNKNOWN_POLICY_TYPE', + `"${id}" is not an organization policy`, + { hint: 'tale://docs/settings lists the policies this kind takes' }, + ); + } + return id; +} + +/** + * A refusal of the policy writer as an agent reads it: its own code and + * sentence, with a hint. The two refusals the app's door answers in a + * form of its own get stable codes, and a capacity the sandbox service + * cannot state now is a refusal to retry, not a fault. + */ +function asRefusal(error: unknown): unknown { + if (!(error instanceof GovernancePolicyError)) return error; + if (error.code === 'use_special_action') { + return new SettingsRefusalError('SETTINGS_TALE_ONLY', error.message, { + hint: 'tell the person where to change it in Tale; nothing over MCP changes it', + }); + } + if (error.code === 'validation') { + return new SettingsRefusalError('SETTINGS_INVALID', error.message, { + hint: 'fix the config and plan again; tale://docs/settings names the fields of each policy', + }); + } + if (error.code === 'SANDBOX_CAPACITY_UNAVAILABLE') { + return new SettingsRefusalError(error.code, error.message, { + status: 409, + hint: 'lowering the sandbox budgets works now; raising them waits until the sandbox service answers again', + }); + } + return new SettingsRefusalError(error.code, error.message, { + status: error.status === 503 ? 409 : error.status, + ...(error.status === 403 + ? { + hint: 'the role of the person whose key this is cannot make this change; an owner or admin can', + } + : {}), + ...(error.data === undefined ? {} : { data: error.data }), + }); +} + +async function withRefusals(run: () => Promise): Promise { + try { + return await run(); + } catch (error) { + throw asRefusal(error); + } +} + +function list(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function record(value: unknown): Record { + return isRecord(value) ? value : {}; +} + +/** Whether a change of the approval rules lets through without a person + * something that needed one: a target that required approval no longer + * does. */ +function approvalLoosened(before: unknown, after: unknown): boolean { + const decisions = (policy: unknown) => + new Map( + list(record(policy).rules).map((rule) => { + const { connector, action, decision } = record(rule); + return [`${String(connector)}|${String(action)}`, decision] as const; + }), + ); + const now = decisions(after); + return [...decisions(before)].some( + ([target, decision]) => + decision === 'require_approval' && now.get(target) !== 'require_approval', + ); +} + +/** Whether a change of the review rules lets someone sign off agent work + * who could not before. */ +function reviewLoosened(before: unknown, after: unknown): boolean { + const was = record(before); + const now = record(after); + if ( + was.requireIndependentReviewer === true && + now.requireIndependentReviewer !== true + ) { + return true; + } + const kept = new Set(list(now.requiredCompetences)); + return list(was.requiredCompetences).some( + (competence) => !kept.has(competence), + ); +} + +function asNumber(value: unknown): number | undefined { + return typeof value === 'number' ? value : undefined; +} + +/** + * What a change of one policy does beyond the value it sets, from the + * policy before (null when none is saved) and after: who may be locked + * out or signed out, and which human approval it removes. + */ +export function governanceEffects( + key: FilePolicyType, + before: unknown, + after: unknown, +): SettingsEffect[] { + const was = isRecord(before) ? before : null; + const now = record(after); + switch (key) { + case 'login_policy': + // An enabled lockout counts failed sign-ins against members. + return now.enabled === false ? [] : ['may-lock-out-members']; + case 'password_policy': { + // Only rotation reaches passwords already set: turned on or + // shortened, it expires some. + const rotation = asNumber(now.rotationDays) ?? 0; + const previous = asNumber(was?.rotationDays) ?? 0; + return rotation > 0 && (previous === 0 || rotation < previous) + ? ['may-lock-out-members'] + : []; + } + case 'two_factor_policy': { + if (now.enforced !== true) return []; + const tightened = + was?.enforced !== true || + (asNumber(now.gracePeriodDays) ?? 0) < + (asNumber(was.gracePeriodDays) ?? 0) || + (was.exemptSsoUsers !== false && now.exemptSsoUsers === false); + return tightened ? ['may-lock-out-members'] : []; + } + case 'session_idle_timeout': { + if (now.enabled !== true) return []; + const shortened = + was?.enabled !== true || + (asNumber(now.idleTimeoutMinutes) ?? 0) < + (asNumber(was.idleTimeoutMinutes) ?? 0); + return shortened ? ['signs-out-members'] : []; + } + case 'approval_policy': + return approvalLoosened(was, now) ? ['removes-human-approval'] : []; + case 'review_policy': + return reviewLoosened(was, now) ? ['removes-human-approval'] : []; + default: + return []; + } +} + +/** One policy as the kind answers it, or null when none is saved. */ +async function readPolicy( + ctx: SettingsContext, + key: FilePolicyType, +): Promise { + const { caller } = ctx; + const snapshot = await withRefusals(() => + readGovernancePolicySnapshotFor( + ctx.sql, + { + organizationId: caller.organizationId, + role: caller.role, + orgSlug: caller.orgSlug, + }, + key, + ), + ); + if (snapshot.policy === null || snapshot.hash === null) return null; + return { id: key, config: snapshot.policy.config, hash: snapshot.hash }; +} + +/** Whether the caller's role reads a policy — a member reads a few, an + * owner or admin every one. */ +function readable(role: string, key: FilePolicyType): boolean { + try { + assertGovernancePolicyReadable(role, key); + return true; + } catch (error) { + if (error instanceof GovernancePolicyError && error.status === 403) { + return false; + } + throw error; + } +} + +/** The policy a change names. */ +function changedKey(change: SettingsChange): FilePolicyType { + return policyKey(identityOf('governance', change.id, undefined, ID_FORM)); +} + +export const governanceSettings: SettingsKindHandler = { + kind: 'governance', + access: async ({ caller }) => ({ + read: true, + write: mayChangeGovernancePolicies(caller.role), + }), + identify: (change) => changedKey(change), + list: async (ctx, query) => { + const keys = + query.ids === undefined + ? FILE_POLICY_TYPES.filter( + (key) => + !Object.hasOwn(GOVERNANCE_KEYS_NOT_OVER_MCP, key) && + readable(ctx.caller.role, key), + ) + : query.ids.map(policyKey); + const items: SettingsResource[] = []; + for (const key of keys) { + const policy = await readPolicy(ctx, key); + if (policy !== null) items.push(policy); + } + return pageOf(items, query.cursor, 100); + }, + read: async (ctx, id) => + id === null ? null : readPolicy(ctx, policyKey(id)), + plan: async (ctx, change, current) => { + const key = changedKey(change); + parseSettingsConfig( + POLICY_SCHEMAS[key], + change.config, + `the ${key} policy`, + ); + const checked = await withRefusals(async () => + checkGovernancePolicy(ctx.sql, await settingsActor(ctx), key, { + config: change.config, + }), + ); + return { + after: checked.config, + unchanged: + current !== null && + configurationHash(current.config) === configurationHash(checked.config), + effects: governanceEffects(key, current?.config ?? null, checked.config), + }; + }, + apply: async (ctx, change, expectedHash) => { + const key = changedKey(change); + await withRefusals(async () => + saveGovernancePolicy(ctx.sql, await settingsActor(ctx), key, { + config: change.config, + expectedHash, + }), + ); + return { hash: (await readPolicy(ctx, key))?.hash ?? null }; + }, +}; diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index f0183049b9..0d265ae5a5 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -5,6 +5,9 @@ * handler here is answered as not available on this deployment. */ +import { governanceSettings } from '../../governance/settings-resource.ts'; import type { SettingsRegistry } from './registry.ts'; -export const SETTINGS_HANDLERS: SettingsRegistry = {}; +export const SETTINGS_HANDLERS: SettingsRegistry = { + governance: governanceSettings, +}; diff --git a/services/platform/backend/domains/mcp/spec.md b/services/platform/backend/domains/mcp/spec.md index 3509c2e9f5..ba3f68b620 100644 --- a/services/platform/backend/domains/mcp/spec.md +++ b/services/platform/backend/domains/mcp/spec.md @@ -182,6 +182,19 @@ An agent reads the organization's settings, plans a change and applies it throug Each kind of setting is read and written by the same code the Settings page uses, so the person's role allows the same changes over MCP as in the app. +### MCP-R10 · An agent changes a setting only where its person's role can change it in the app + +Each kind of setting is read and changed through the code its Settings page uses, with the same +checks of the person's role, so a person's agent can read and change every setting their role +lets them read and change in the app, and nothing more. A change the role does not allow is +refused with the reason the app's check gives, and nothing in the call is applied. Without +`kinds`, `get_settings` says for each kind whether the person's role may read and change it. + +- **Example**: Ada, an admin, has her agent turn the organization's feature flags off → they are + off. Mia, an ordinary member, has her agent send the same change → refused, saying only owners + and admins can change organization policies, and the flags stay on; her agent asks for the + password policy, which only owners and admins read → refused as well. + ### MCP-R11 · A settings call applies only when each setting is still what the agent read Every change names the hash of the setting the agent read, or none for a setting it creates. @@ -394,9 +407,9 @@ deployment of a release. A signed-in person downloads it in the app; an agent re a version its agent saves records the door and the key but no client name; a 2026-07-28 client names itself on every call (MCP-R26). - The tool inventory and each tool's arguments (`lib/mcp/tools.ts`, `lib/mcp/args.ts`). -- No kind of setting is served over MCP yet: each arrives with its handler beside the code that - writes it in the app. Until then the catalog lists it as unavailable, and a change to it is - refused (`SETTINGS_KIND_UNAVAILABLE`). +- A kind of setting is served over MCP once its handler sits beside the code that writes it in + the app; until then the catalog lists it as unavailable, and a change to it is refused + (`SETTINGS_KIND_UNAVAILABLE`). - A client cannot subscribe to a resource or be told that a list changed (`subscriptions/listen` answers 404 on 2026-07-28): the lists are read again when a client reconnects, or on 2026-07-28 once the time the answer named has passed. From 4e0c33ed122294d8703c828f0b0b32a53918c01d Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:06:48 +0200 Subject: [PATCH 21/35] feat(platform): change the embedding model over MCP The knowledge-embedding kind reads and saves the organization's model through the writer the Data residency page uses, behind its owner-or-admin gate, with its compare-and-set, its audit row and the documents and websites that follow a save. As a declaration the CLI applies, a change of the model itself is taken only while the knowledge base is empty, so two models' vectors never meet in a search; the similarity floor and the serving limits change at any time. The check a save runs is lifted out of the writer so a plan runs it too. MCP-R28. --- .../backend/domains/knowledge/admin.ts | 40 ++- .../domains/knowledge/embedding-save.ts | 11 +- .../knowledge/settings-resource.test.ts | 265 ++++++++++++++++++ .../domains/knowledge/settings-resource.ts | 121 ++++++++ .../backend/domains/mcp/settings/handlers.ts | 2 + services/platform/backend/domains/mcp/spec.md | 13 + 6 files changed, 436 insertions(+), 16 deletions(-) create mode 100644 services/platform/backend/domains/knowledge/settings-resource.test.ts create mode 100644 services/platform/backend/domains/knowledge/settings-resource.ts diff --git a/services/platform/backend/domains/knowledge/admin.ts b/services/platform/backend/domains/knowledge/admin.ts index b3f0a2835d..466ebf5622 100644 --- a/services/platform/backend/domains/knowledge/admin.ts +++ b/services/platform/backend/domains/knowledge/admin.ts @@ -447,21 +447,15 @@ function embeddingAuditFields(actor: KnowledgeAuditActor) { } /** - * Save the organization's embedding model, compare-and-set on the hash a - * change names. With an actor, a save that changes the stored model leaves - * one audit row (`knowledge_embedding.saved`) with the model before and - * after, written in the transaction that holds the knowledge config's - * write lock and before the file, so a failed write takes the row back; a - * save of what is stored leaves none. `sql` is the root handle: the write - * opens its own transaction. + * Check an embedding model as a save checks it, writing nothing: the + * config is the file's own shape, its endpoint passes the deployment's + * host policy, and its provider does not declare that it cannot embed. + * Answers the config as the write reads it. */ -export async function writeKnowledgeEmbedding( - sql: Sql, +export function checkKnowledgeEmbedding( orgSlug: string, config: unknown, - expectedHash?: string | null, - actor?: KnowledgeAuditActor, -): Promise { +): KnowledgeEmbeddingWrite { // The similarity floor and the serving limits are settings the Settings // form does not carry (see `resolveKeptEmbeddingSettings`), so the body // may say `null` for them — clear — as well as a value. @@ -476,13 +470,33 @@ export async function writeKnowledgeEmbedding( assertHostAllowed(parsed.data.baseUrl); } assertProviderCanEmbed(orgSlug, parsed.data.providerSlug); + return parsed.data; +} + +/** + * Save the organization's embedding model, compare-and-set on the hash a + * change names. With an actor, a save that changes the stored model leaves + * one audit row (`knowledge_embedding.saved`) with the model before and + * after, written in the transaction that holds the knowledge config's + * write lock and before the file, so a failed write takes the row back; a + * save of what is stored leaves none. `sql` is the root handle: the write + * opens its own transaction. + */ +export async function writeKnowledgeEmbedding( + sql: Sql, + orgSlug: string, + config: unknown, + expectedHash?: string | null, + actor?: KnowledgeAuditActor, +): Promise { + const written = checkKnowledgeEmbedding(orgSlug, config); await sql.begin((tx) => withConfigWriteLock(tx, orgSlug, 'knowledge', async () => { const current = await readKnowledgeEmbeddingView(orgSlug); if (expectedHash !== undefined) assertExpectedHash(current.hash, expectedHash); const filePath = embeddingFilePath(orgSlug); - const next = resolveKeptEmbeddingSettings(parsed.data, current.config); + const next = resolveKeptEmbeddingSettings(written, current.config); const serialized = serializeEmbeddingJson(next); const currentContent = await readFileSafe(filePath); if (actor !== undefined && currentContent !== serialized) { diff --git a/services/platform/backend/domains/knowledge/embedding-save.ts b/services/platform/backend/domains/knowledge/embedding-save.ts index 8755bfce31..dae63b4916 100644 --- a/services/platform/backend/domains/knowledge/embedding-save.ts +++ b/services/platform/backend/domains/knowledge/embedding-save.ts @@ -31,12 +31,17 @@ export interface EmbeddingOrganization { } /** - * Who may manage the organization's knowledge configuration — its - * database connection and its embedding model: a role with the + * Whether a role may manage the organization's knowledge configuration — + * its database connection and its embedding model: a role with the * org-settings capability, which owners and admins hold. */ +export function mayManageKnowledge(role: string): boolean { + return defineAbilityFor(role).can('write', 'orgSettings'); +} + +/** Refuse a role that may not manage the knowledge configuration. */ export function assertKnowledgeAdmin(role: string): void { - if (defineAbilityFor(role).cannot('write', 'orgSettings')) { + if (!mayManageKnowledge(role)) { throw new ConfigurationError( 'ORG_FORBIDDEN', `Role "${role}" cannot manage the knowledge configuration.`, diff --git a/services/platform/backend/domains/knowledge/settings-resource.test.ts b/services/platform/backend/domains/knowledge/settings-resource.test.ts new file mode 100644 index 0000000000..37e1cdf2bc --- /dev/null +++ b/services/platform/backend/domains/knowledge/settings-resource.test.ts @@ -0,0 +1,265 @@ +// @vitest-environment node + +/** + * The embedding model over MCP, through the writer the Data residency page + * uses: the config store is a temporary directory, the database a double + * that runs the writer's transaction, and the corpus counts and the + * documents and websites that follow a save are doubles too. + */ + +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { corpus, createAuditLog } = vi.hoisted(() => ({ + corpus: { documents: 0, websites: 0 }, + createAuditLog: vi.fn(), +})); + +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog })); +vi.mock('../documents/service.ts', () => ({ + approxCountDocumentsForOrg: vi.fn(async () => corpus.documents), +})); +vi.mock('../websites/service.ts', () => ({ + countWebsites: vi.fn(async () => corpus.websites), + websitesAfterEmbeddingChange: vi.fn(async () => ({ queued: 0 })), +})); +vi.mock('./service.ts', () => ({ + requeueEmbeddingBlockedDocuments: vi.fn(async () => ({ requeued: 0 })), + requeueDocumentsWithoutVectors: vi.fn(async () => ({ requeued: 0 })), +})); + +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { knowledgeEmbeddingSettings } from './settings-resource.ts'; + +const registry = { 'knowledge-embedding': knowledgeEmbeddingSettings }; + +const MODEL = { + providerSlug: 'local-embedding', + model: 'example-embedding', + dimensions: 1024, +}; + +function contextOf(role: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + // Every statement answers the caller's address; the write lock reads + // nothing back. + const tag = async () => [{ email: `${role}@example.test` }]; + const sql = Object.assign(tag, { + begin: (work: (tx: unknown) => Promise) => work(tag), + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: sql as unknown as Sql, caller }; +} + +const change = (config: unknown) => ({ + kind: 'knowledge-embedding' as const, + op: 'set' as const, + config, +}); + +/** Store a model as the page would, and answer its hash. */ +async function stored(config: unknown): Promise { + const answer = await applySettings( + contextOf('admin'), + registry, + [change(config)], + { 'knowledge-embedding': null }, + ); + const [applied] = (answer.applied ?? []) as Array<{ hash: string }>; + if (applied === undefined) throw new Error(JSON.stringify(answer)); + createAuditLog.mockClear(); + return applied.hash; +} + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(path.join(tmpdir(), 'tale-embedding-kind-')); + vi.stubEnv('TALE_CONFIG_DIR', dir); + corpus.documents = 0; + corpus.websites = 0; + createAuditLog.mockReset(); + createAuditLog.mockResolvedValue('row-1'); +}); + +afterEach(async () => { + vi.unstubAllEnvs(); + await rm(dir, { recursive: true, force: true }); +}); + +describe('who reads and changes the embedding model [MCP-R10]', () => { + it('lets an owner or admin read and change it, and nobody else', async () => { + for (const role of ['owner', 'admin']) { + expect(await knowledgeEmbeddingSettings.access(contextOf(role))).toEqual({ + read: true, + write: true, + }); + } + for (const role of ['developer', 'member']) { + expect(await knowledgeEmbeddingSettings.access(contextOf(role))).toEqual({ + read: false, + write: false, + }); + const answer = await getSettings(contextOf(role), registry, { + kinds: ['knowledge-embedding'], + }); + expect(answer.refused).toEqual([ + expect.objectContaining({ + kind: 'knowledge-embedding', + code: 'ORG_FORBIDDEN', + }), + ]); + } + }); +}); + +describe('planning a change of the embedding model', () => { + it('takes a first model while the knowledge base is empty, saying so [MCP-R28]', async () => { + const plan = await planSettings(contextOf('admin'), registry, [ + change(MODEL), + ]); + expect(plan.changes[0]).toMatchObject({ + key: 'knowledge-embedding', + action: 'create', + currentHash: null, + effects: ['requires-empty-corpus'], + risk: 'critical', + }); + }); + + it('refuses another model while documents or websites are indexed, naming how many [MCP-R28]', async () => { + const hash = await stored(MODEL); + corpus.documents = 40; + corpus.websites = 2; + const plan = await planSettings(contextOf('admin'), registry, [ + change({ ...MODEL, model: 'example-embedding-2' }), + ]); + expect(plan.changes[0]).toMatchObject({ + currentHash: hash, + refusal: { + code: 'EMBEDDING_CORPUS_NOT_EMPTY', + error: expect.stringContaining('40 documents and 2 websites'), + hint: expect.stringContaining('Settings > Data residency'), + data: { documents: 40, websites: 2 }, + }, + }); + }); + + it('changes the similarity floor and the serving limits at any time [MCP-R28]', async () => { + await stored(MODEL); + corpus.documents = 40; + const plan = await planSettings(contextOf('admin'), registry, [ + change({ ...MODEL, minSimilarity: 0.4, maxConcurrentRequests: 2 }), + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'update', + effects: [], + diff: [ + { path: '/maxConcurrentRequests', after: 2 }, + { path: '/minSimilarity', after: 0.4 }, + ], + }); + }); + + it('keeps a stored setting the change leaves out, as the page does', async () => { + await stored({ ...MODEL, minSimilarity: 0.4 }); + const plan = await planSettings(contextOf('admin'), registry, [ + change(MODEL), + ]); + expect(plan.changes[0]).toMatchObject({ action: 'unchanged' }); + }); + + it('names every problem, a field the model does not have among them', async () => { + const plan = await planSettings(contextOf('admin'), registry, [ + change({ ...MODEL, dimensions: 1000, modle: 'x' }), + ]); + expect(plan.changes[0]?.refusal).toMatchObject({ + code: 'SETTINGS_INVALID', + data: { + issues: [expect.objectContaining({ path: '/config/dimensions' })], + }, + }); + const misspelled = await planSettings(contextOf('admin'), registry, [ + change({ ...MODEL, modle: 'x' }), + ]); + expect(misspelled.changes[0]?.refusal?.data).toEqual({ + issues: [ + { + path: '/config/modle', + code: 'unrecognized_key', + message: 'is not a field of this setting', + }, + ], + }); + }); +}); + +describe('applying a change of the embedding model', () => { + it('saves through the page’s writer, audited under the person who holds the key', async () => { + const answer = await applySettings( + contextOf('admin'), + registry, + [change(MODEL)], + { 'knowledge-embedding': null }, + ); + const read = await knowledgeEmbeddingSettings.read( + contextOf('admin'), + null, + ); + expect(answer).toEqual({ + applied: [ + { + kind: 'knowledge-embedding', + id: null, + key: 'knowledge-embedding', + action: 'create', + hash: read?.hash, + }, + ], + skipped: [], + }); + expect(read?.config).toEqual(MODEL); + expect(createAuditLog).toHaveBeenCalledOnce(); + expect(createAuditLog.mock.lastCall?.[1]).toMatchObject({ + action: 'knowledge_embedding.saved', + actorId: 'user-admin', + actorEmail: 'admin@example.test', + newState: MODEL, + }); + }); + + it('lands only on the model the agent read', async () => { + const hash = await stored(MODEL); + // Someone changes the floor in Tale after the agent read the model. + await applySettings( + contextOf('owner'), + registry, + [change({ ...MODEL, minSimilarity: 0.5 })], + { 'knowledge-embedding': hash }, + ); + const answer = await applySettings( + contextOf('admin'), + registry, + [change({ ...MODEL, minSimilarity: 0.3 })], + { 'knowledge-embedding': hash }, + ); + expect(answer).toMatchObject({ + code: 'SETTINGS_STALE', + applied: [], + }); + }); +}); diff --git a/services/platform/backend/domains/knowledge/settings-resource.ts b/services/platform/backend/domains/knowledge/settings-resource.ts new file mode 100644 index 0000000000..912c1b15e0 --- /dev/null +++ b/services/platform/backend/domains/knowledge/settings-resource.ts @@ -0,0 +1,121 @@ +import { sameEmbeddingModel } from '@tale/shared/config/platform-resources'; +import { knowledgeEmbeddingWriteSchema } from '@tale/shared/schemas/knowledge'; +import type { SettingsEffect } from '@tale/shared/schemas/settings-kinds'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { approxCountDocumentsForOrg } from '../documents/service.ts'; +import { + identifySingle, + parseSettingsConfig, + settingsActor, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { countWebsites } from '../websites/service.ts'; +import { + checkKnowledgeEmbedding, + readKnowledgeEmbeddingView, + resolveKeptEmbeddingSettings, +} from './admin.ts'; +import { + assertKnowledgeAdmin, + mayManageKnowledge, + saveKnowledgeEmbedding, +} from './embedding-save.ts'; + +/** + * The organization's embedding model as a settings kind over MCP + * (`knowledge-embedding`): one resource, read and saved through the writer + * the Data residency page uses (`embedding-save.ts`), with its gate, its + * compare-and-set, its audit row and the documents and websites that + * follow a save. + * + * A change of the model itself — provider, credential, model, width or + * endpoint — is taken only while the knowledge base is empty, as a + * declaration applied by the CLI takes it: vectors of two models must never + * meet in one search, and a model of the same width would find the old + * vectors and compare against them. The similarity floor and the serving + * limits change at any time. + */ + +/** How many documents and websites the organization's knowledge base + * holds — what a change of the model would leave in another model's + * vectors. */ +async function corpusOf(ctx: SettingsContext) { + const [documents, websites] = await Promise.all([ + approxCountDocumentsForOrg(ctx.sql, ctx.caller.organizationId), + countWebsites(ctx.sql, ctx.caller.organizationId), + ]); + return { documents, websites }; +} + +async function readEmbedding( + ctx: SettingsContext, +): Promise { + assertKnowledgeAdmin(ctx.caller.role); + const view = await readKnowledgeEmbeddingView(ctx.caller.orgSlug); + if (view.config === null || view.hash === null) return null; + return { id: null, config: view.config, hash: view.hash }; +} + +export const knowledgeEmbeddingSettings: SettingsKindHandler = { + kind: 'knowledge-embedding', + access: async ({ caller }) => { + const allowed = mayManageKnowledge(caller.role); + return { read: allowed, write: allowed }; + }, + identify: identifySingle('knowledge-embedding'), + list: async (ctx) => { + const current = await readEmbedding(ctx); + return { items: current === null ? [] : [current], nextCursor: null }; + }, + read: async (ctx) => readEmbedding(ctx), + plan: async (ctx, change, current) => { + assertKnowledgeAdmin(ctx.caller.role); + parseSettingsConfig( + knowledgeEmbeddingWriteSchema, + change.config, + 'the embedding model', + ); + const written = checkKnowledgeEmbedding(ctx.caller.orgSlug, change.config); + const view = await readKnowledgeEmbeddingView(ctx.caller.orgSlug); + const after = resolveKeptEmbeddingSettings(written, view.config); + const unchanged = + current !== null && + configurationHash(after) === configurationHash(current.config); + const effects: SettingsEffect[] = []; + if (!unchanged && !sameEmbeddingModel(after, current?.config ?? null)) { + const corpus = await corpusOf(ctx); + if (corpus.documents > 0 || corpus.websites > 0) { + throw new SettingsRefusalError( + 'EMBEDDING_CORPUS_NOT_EMPTY', + `the embedding model changes only while the knowledge base is empty; it holds ${corpus.documents} documents and ${corpus.websites} websites`, + { + status: 409, + hint: 'the similarity floor and the serving limits change at any time; for another model, tell the person to change it in Tale, under Settings > Data residency, where what is indexed is queued again', + data: corpus, + }, + ); + } + effects.push('requires-empty-corpus'); + } + return { after, unchanged, effects }; + }, + apply: async (ctx, change, expectedHash) => { + await saveKnowledgeEmbedding( + ctx.sql, + { + organizationId: ctx.caller.organizationId, + orgSlug: ctx.caller.orgSlug, + }, + change.config, + expectedHash, + await settingsActor(ctx), + ); + return { hash: (await readEmbedding(ctx))?.hash ?? null }; + }, +}; diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index 0d265ae5a5..6b046f5e84 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -6,8 +6,10 @@ */ import { governanceSettings } from '../../governance/settings-resource.ts'; +import { knowledgeEmbeddingSettings } from '../../knowledge/settings-resource.ts'; import type { SettingsRegistry } from './registry.ts'; export const SETTINGS_HANDLERS: SettingsRegistry = { governance: governanceSettings, + 'knowledge-embedding': knowledgeEmbeddingSettings, }; diff --git a/services/platform/backend/domains/mcp/spec.md b/services/platform/backend/domains/mcp/spec.md index ba3f68b620..ce9f536b60 100644 --- a/services/platform/backend/domains/mcp/spec.md +++ b/services/platform/backend/domains/mcp/spec.md @@ -224,6 +224,19 @@ enters a new secret in Tale. agent reads the policy → the prompt reads as masked; the agent changes another field and sends the masked prompt back → the prompt is kept as Ben wrote it. +### MCP-R28 · An agent changes the embedding model only while the knowledge base is empty + +Vectors of two embedding models must never meet in one search, so an agent's change to the model +itself — its provider, credential, model, vector width or endpoint — is taken only while the +organization holds no document and no website, as a declaration applied with the CLI is. With +anything indexed it is refused, naming how many documents and websites there are +(`EMBEDDING_CORPUS_NOT_EMPTY`), and the person changes the model in Tale, where what is indexed +is queued again. The similarity floor and the serving limits change at any time. + +- **Example**: Ada's agent proposes a larger embedding model while 40 documents are indexed → + refused, naming the 40 documents; her agent lowers the similarity floor instead → it is + changed, and nothing is indexed again. + ## Answers and refusals ### MCP-R18 · A refusal comes back as an answer the agent can read, not a protocol error From b3ed9e421754902f0270da0f6d6ca33b60509e9b Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:09:19 +0200 Subject: [PATCH 22/35] feat(platform): change the branding over MCP The branding kind reads and saves the accent colour and the image file names through the writer the Branding page uses, behind its owner-or-admin gate, with its compare-and-set and its audit row. A file the old colour field still carries reads as the page shows it, so a read sent back changes nothing. Images are uploaded in Tale, so a file name a change sets must name one the organization has uploaded. --- .../backend/domains/branding/service.ts | 15 +- .../branding/settings-resource.test.ts | 231 ++++++++++++++++++ .../domains/branding/settings-resource.ts | 140 +++++++++++ .../backend/domains/mcp/settings/handlers.ts | 2 + 4 files changed, 383 insertions(+), 5 deletions(-) create mode 100644 services/platform/backend/domains/branding/settings-resource.test.ts create mode 100644 services/platform/backend/domains/branding/settings-resource.ts diff --git a/services/platform/backend/domains/branding/service.ts b/services/platform/backend/domains/branding/service.ts index 8d86533f96..1aacd3f542 100644 --- a/services/platform/backend/domains/branding/service.ts +++ b/services/platform/backend/domains/branding/service.ts @@ -103,13 +103,18 @@ export class BrandingError extends Error { } /** - * Who may change the organization's branding — read it for editing, save - * it, upload or delete its images: a role with the org-settings - * capability, which owners and admins hold. Anyone else is refused, with - * the capability named, before anything is read or written. + * Whether a role may change the organization's branding — read it for + * editing, save it, upload or delete its images: a role with the + * org-settings capability, which owners and admins hold. */ +export function mayChangeBranding(role: string): boolean { + return defineAbilityFor(role).can('write', 'orgSettings'); +} + +/** Refuse a role that may not change the branding, naming the capability + * it lacks, before anything is read or written. */ export function assertBrandingWriter(role: string): void { - if (defineAbilityFor(role).cannot('write', 'orgSettings')) { + if (!mayChangeBranding(role)) { throw new BrandingError( 'ORG_FORBIDDEN', `Role "${role}" lacks the org-settings capability required to modify branding.`, diff --git a/services/platform/backend/domains/branding/settings-resource.test.ts b/services/platform/backend/domains/branding/settings-resource.test.ts new file mode 100644 index 0000000000..e204fb7259 --- /dev/null +++ b/services/platform/backend/domains/branding/settings-resource.test.ts @@ -0,0 +1,231 @@ +// @vitest-environment node + +/** + * The branding over MCP, through the writer the Branding page uses: the + * config store is a temporary directory, the database a double that runs + * the writer's transaction, and the audit chain a double that records. + */ + +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { createAuditLog } = vi.hoisted(() => ({ createAuditLog: vi.fn() })); +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog })); + +import { + resolveBrandingFilePath, + resolveImagesDir, +} from '../../core/branding/file_utils.ts'; +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { brandingSettings } from './settings-resource.ts'; + +const registry = { branding: brandingSettings }; + +function contextOf(role: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + const tag = async () => [{ email: `${role}@example.test` }]; + const sql = Object.assign(tag, { + begin: (work: (tx: unknown) => Promise) => work(tag), + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: sql as unknown as Sql, caller }; +} + +const change = (config: unknown) => ({ + kind: 'branding' as const, + op: 'set' as const, + config, +}); + +/** A branding file as the page, or an older release, left it. */ +async function storedFile(config: unknown): Promise { + const file = resolveBrandingFilePath('acme'); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, `${JSON.stringify(config, null, 2)}\n`); +} + +async function uploadedImage(filename: string): Promise { + const dir = resolveImagesDir('acme'); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, filename), ''); +} + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(path.join(tmpdir(), 'tale-branding-kind-')); + vi.stubEnv('TALE_CONFIG_DIR', dir); + createAuditLog.mockReset(); + createAuditLog.mockResolvedValue('row-1'); +}); + +afterEach(async () => { + vi.unstubAllEnvs(); + await rm(dir, { recursive: true, force: true }); +}); + +describe('who reads and changes the branding [MCP-R10]', () => { + it('lets an owner or admin read and change it, and refuses everyone else as the page does', async () => { + await storedFile({ accentColor: '#112233' }); + for (const role of ['owner', 'admin']) { + expect(await brandingSettings.access(contextOf(role))).toEqual({ + read: true, + write: true, + }); + } + for (const role of ['developer', 'member']) { + expect(await brandingSettings.access(contextOf(role))).toEqual({ + read: false, + write: false, + }); + const answer = await getSettings(contextOf(role), registry, { + kinds: ['branding'], + }); + expect(answer.refused).toEqual([ + { + kind: 'branding', + code: 'ORG_FORBIDDEN', + error: `Role "${role}" lacks the org-settings capability required to modify branding.`, + }, + ]); + expect(answer.resources).toEqual([]); + } + }); +}); + +describe('reading the branding', () => { + it('reads a file the old colour field still carries as the page shows it, so sending it back changes nothing', async () => { + await storedFile({ brandColor: '#112233', logoFilename: 'logo.svg' }); + const answer = await getSettings(contextOf('admin'), registry, { + kinds: ['branding'], + }); + expect(answer.resources).toEqual([ + expect.objectContaining({ + key: 'branding', + config: { accentColor: '#112233', logoFilename: 'logo.svg' }, + }), + ]); + await uploadedImage('logo.svg'); + const plan = await planSettings(contextOf('admin'), registry, [ + change({ accentColor: '#112233', logoFilename: 'logo.svg' }), + ]); + expect(plan.changes[0]).toMatchObject({ action: 'unchanged' }); + }); +}); + +describe('planning a branding change', () => { + it('takes a new accent colour, at low risk', async () => { + await storedFile({ accentColor: '#112233' }); + const plan = await planSettings(contextOf('admin'), registry, [ + change({ accentColor: '#445566' }), + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'update', + diff: [{ path: '/accentColor', before: '#112233', after: '#445566' }], + effects: [], + risk: 'low', + }); + }); + + it.each(['logo.png', '../other-org/logo.svg', 'images/logo.svg'])( + 'refuses %j, which names no uploaded image', + async (logoFilename) => { + const plan = await planSettings(contextOf('admin'), registry, [ + change({ accentColor: '#445566', logoFilename }), + ]); + expect(plan.changes[0]?.refusal).toMatchObject({ + code: 'BRANDING_IMAGE_UNKNOWN', + error: + '/config/logoFilename names no image uploaded to this organization', + hint: expect.stringContaining('Settings > Branding'), + }); + }, + ); + + it('keeps an uploaded image, and refuses the old colour field or one the branding lacks', async () => { + await uploadedImage('favicon-light.png'); + const kept = await planSettings(contextOf('admin'), registry, [ + change({ faviconLightFilename: 'favicon-light.png' }), + ]); + expect(kept.changes[0]).toMatchObject({ action: 'create' }); + const legacy = await planSettings(contextOf('admin'), registry, [ + change({ brandColor: '#445566', textLogo: 'Acme' }), + ]); + expect(legacy.changes[0]?.refusal).toMatchObject({ + code: 'SETTINGS_INVALID', + data: { + issues: [ + expect.objectContaining({ path: '/config/brandColor' }), + expect.objectContaining({ path: '/config/textLogo' }), + ], + }, + }); + }); +}); + +describe('applying a branding change', () => { + it('saves through the page’s writer, audited under the person who holds the key', async () => { + await storedFile({ accentColor: '#112233' }); + const [current] = ( + await getSettings(contextOf('admin'), registry, { kinds: ['branding'] }) + ).resources as Array<{ hash: string }>; + const answer = await applySettings( + contextOf('admin'), + registry, + [change({ accentColor: '#445566' })], + { branding: current?.hash ?? null }, + ); + const read = await brandingSettings.read(contextOf('admin'), null); + expect(answer).toEqual({ + applied: [ + { + kind: 'branding', + id: null, + key: 'branding', + action: 'update', + hash: read?.hash, + }, + ], + skipped: [], + }); + expect(read?.config).toEqual({ accentColor: '#445566' }); + expect(createAuditLog).toHaveBeenCalledOnce(); + expect(createAuditLog.mock.lastCall?.[1]).toMatchObject({ + action: 'branding.updated', + actorId: 'user-admin', + actorEmail: 'admin@example.test', + newState: { accentColor: '#445566' }, + }); + }); + + it('lands only on the branding the agent read', async () => { + await storedFile({ accentColor: '#112233' }); + const [read] = ( + await getSettings(contextOf('admin'), registry, { kinds: ['branding'] }) + ).resources as Array<{ hash: string }>; + // Someone saves another colour in Tale after the agent read it. + await storedFile({ accentColor: '#778899' }); + const answer = await applySettings( + contextOf('admin'), + registry, + [change({ accentColor: '#445566' })], + { branding: read?.hash ?? null }, + ); + expect(answer).toMatchObject({ code: 'SETTINGS_STALE', applied: [] }); + expect(createAuditLog).not.toHaveBeenCalled(); + }); +}); diff --git a/services/platform/backend/domains/branding/settings-resource.ts b/services/platform/backend/domains/branding/settings-resource.ts new file mode 100644 index 0000000000..cfbb5f7146 --- /dev/null +++ b/services/platform/backend/domains/branding/settings-resource.ts @@ -0,0 +1,140 @@ +import { stat } from 'node:fs/promises'; + +import { brandingFormSchema } from '@tale/shared/schemas/branding'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { resolveImagePath } from '../../core/branding/file_utils.ts'; +import { + identifySingle, + parseSettingsConfig, + settingsActor, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { + assertBrandingWriter, + mayChangeBranding, + readBrandingConfig, + saveBranding, +} from './service.ts'; + +/** + * The organization's branding as a settings kind over MCP (`branding`): + * one resource — the accent colour and the file names of the logo and the + * favicons — read and saved through the writer the Branding page uses, + * behind its owner-or-admin gate, with its compare-and-set and its audit + * row. The images themselves are uploaded in Tale: a file name a change + * sets must name an image the organization has uploaded. + */ + +const IMAGE_FIELDS = [ + 'logoFilename', + 'faviconLightFilename', + 'faviconDarkFilename', +] as const; + +/** + * The branding as the Branding page edits it: a file the old colour field + * still carries reads with that colour as the accent colour, as every + * reader shows it, so a read sent back unchanged is the page's own save. + */ +function editedView(config: unknown): Record { + if (!isRecord(config)) return {}; + const { brandColor, accentColor, ...rest } = config; + const colour = + typeof accentColor === 'string' && accentColor !== '' + ? accentColor + : brandColor; + return { + ...rest, + ...(typeof colour === 'string' && colour !== '' + ? { accentColor: colour } + : {}), + }; +} + +async function readBrandingResource( + ctx: SettingsContext, +): Promise { + assertBrandingWriter(ctx.caller.role); + const snapshot = await readBrandingConfig(ctx.caller.orgSlug); + if (snapshot.config === null || snapshot.hash === null) return null; + return { id: null, config: editedView(snapshot.config), hash: snapshot.hash }; +} + +/** Whether a file name names an image the organization has uploaded. */ +async function uploaded(orgSlug: string, filename: string): Promise { + let file: string; + try { + file = resolveImagePath(orgSlug, filename); + } catch (error) { + console.warn( + '[branding] a settings change named an image file name that is not one:', + error instanceof Error ? error.message : error, + ); + return false; + } + try { + return (await stat(file)).isFile(); + } catch (error) { + if (Reflect.get(Object(error), 'code') === 'ENOENT') return false; + throw error; + } +} + +export const brandingSettings: SettingsKindHandler = { + kind: 'branding', + access: async ({ caller }) => { + const allowed = mayChangeBranding(caller.role); + return { read: allowed, write: allowed }; + }, + identify: identifySingle('branding'), + list: async (ctx) => { + const current = await readBrandingResource(ctx); + return { items: current === null ? [] : [current], nextCursor: null }; + }, + read: async (ctx) => readBrandingResource(ctx), + plan: async (ctx, change, current) => { + assertBrandingWriter(ctx.caller.role); + const after = parseSettingsConfig( + brandingFormSchema, + change.config, + 'the branding', + ); + for (const field of IMAGE_FIELDS) { + const filename = after[field]; + if (filename === undefined || filename === '') continue; + if (!(await uploaded(ctx.caller.orgSlug, filename))) { + throw new SettingsRefusalError( + 'BRANDING_IMAGE_UNKNOWN', + `/config/${field} names no image uploaded to this organization`, + { + hint: 'images are uploaded in Tale, under Settings > Branding; a file name here keeps an uploaded one, or is left out to show none', + data: { field }, + }, + ); + } + } + return { + after, + unchanged: + current !== null && + configurationHash(after) === configurationHash(current.config), + }; + }, + apply: async (ctx, change, expectedHash) => { + const { hash } = await saveBranding( + ctx.sql, + ctx.caller.orgSlug, + change.config, + expectedHash, + await settingsActor(ctx), + ); + return { hash }; + }, +}; diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index 6b046f5e84..6de7fe140e 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -5,6 +5,7 @@ * handler here is answered as not available on this deployment. */ +import { brandingSettings } from '../../branding/settings-resource.ts'; import { governanceSettings } from '../../governance/settings-resource.ts'; import { knowledgeEmbeddingSettings } from '../../knowledge/settings-resource.ts'; import type { SettingsRegistry } from './registry.ts'; @@ -12,4 +13,5 @@ import type { SettingsRegistry } from './registry.ts'; export const SETTINGS_HANDLERS: SettingsRegistry = { governance: governanceSettings, 'knowledge-embedding': knowledgeEmbeddingSettings, + branding: brandingSettings, }; From 8c8b68115a24eb8a317db5ef3ecb52921b166ce5 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:11:27 +0200 Subject: [PATCH 23/35] feat(platform): change the deployment settings over MCP The deployment kind reads and saves this deployment's own settings through the writer the operator's settings use, behind the same gate: an owner or admin of any organization reads them, an address on the editor allowlist changes them. Its version conflict is answered as every other stale setting is, with the hash stored now, and a plan says when a new sandbox runtime takes effect only after a restart. --- .../deployment/settings-resource.test.ts | 201 ++++++++++++++++++ .../domains/deployment/settings-resource.ts | 161 ++++++++++++++ .../backend/domains/mcp/settings/handlers.ts | 2 + 3 files changed, 364 insertions(+) create mode 100644 services/platform/backend/domains/deployment/settings-resource.test.ts create mode 100644 services/platform/backend/domains/deployment/settings-resource.ts diff --git a/services/platform/backend/domains/deployment/settings-resource.test.ts b/services/platform/backend/domains/deployment/settings-resource.test.ts new file mode 100644 index 0000000000..72379ba925 --- /dev/null +++ b/services/platform/backend/domains/deployment/settings-resource.test.ts @@ -0,0 +1,201 @@ +// @vitest-environment node + +/** + * The deployment's own settings over MCP, through the writer the + * operator's settings use: the config store is a temporary directory, the + * database a double that knows the caller's memberships and address, and + * the audit chain a double that records. + */ + +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { createAuditLog } = vi.hoisted(() => ({ createAuditLog: vi.fn() })); +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog })); + +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { deploymentSettings } from './settings-resource.ts'; + +const registry = { deployment: deploymentSettings }; + +/** + * A caller who is `role` in their organization and signs in as `email`. + * The database answers the gate's membership read and the address read; + * every other statement reads nothing back. + */ +function contextOf(role: string, email: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: 'user-1', + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + const tag = async (strings: TemplateStringsArray) => { + const text = strings.join('?'); + if (text.includes('FROM "member"')) { + return [{ organizationId: 'org-1', role }]; + } + if (text.includes('FROM "user"')) return [{ email }]; + return []; + }; + const sql = Object.assign(tag, { + begin: (work: (tx: unknown) => Promise) => work(tag), + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: sql as unknown as Sql, caller }; +} + +const OPERATOR = 'ops@example.test'; +const operator = () => contextOf('owner', OPERATOR); + +const change = (config: unknown) => ({ + kind: 'deployment' as const, + op: 'set' as const, + config, +}); + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(path.join(tmpdir(), 'tale-deployment-kind-')); + vi.stubEnv('TALE_CONFIG_DIR', dir); + vi.stubEnv('TALE_DEPLOYMENT_CONFIG_ADMINS', OPERATOR); + createAuditLog.mockReset(); + createAuditLog.mockResolvedValue('row-1'); +}); + +afterEach(async () => { + vi.unstubAllEnvs(); + await rm(dir, { recursive: true, force: true }); +}); + +describe('who reads and changes the deployment settings [MCP-R10]', () => { + it('lets an admin read them, an editor on the allowlist change them, and nobody else either', async () => { + expect(await deploymentSettings.access(operator())).toEqual({ + read: true, + write: true, + }); + expect( + await deploymentSettings.access(contextOf('admin', 'ada@example.test')), + ).toEqual({ read: true, write: false }); + expect( + await deploymentSettings.access(contextOf('member', OPERATOR)), + ).toEqual({ read: false, write: false }); + + const refused = await planSettings( + contextOf('admin', 'ada@example.test'), + registry, + [change({ version: 1 })], + ); + expect(refused.changes[0]?.refusal).toEqual({ + code: 'FORBIDDEN_DEPLOYMENT_EDITOR', + error: 'Your account is not in the deployment editor allowlist.', + hint: expect.stringContaining('editor allowlist'), + }); + const member = await getSettings(contextOf('member', OPERATOR), registry, { + kinds: ['deployment'], + }); + expect(member.refused).toEqual([ + expect.objectContaining({ code: 'FORBIDDEN_INSTANCE_ADMIN' }), + ]); + }); +}); + +describe('planning a change of the deployment settings', () => { + it('says that a new sandbox runtime takes effect after a restart', async () => { + const plan = await planSettings(operator(), registry, [ + change({ version: 1, sandboxRuntime: { tier: 'gvisor' } }), + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'create', + effects: ['restart-required'], + risk: 'critical', + }); + }); + + it('names every problem, a section the settings do not have among them', async () => { + const plan = await planSettings(operator(), registry, [ + change({ + version: 2, + sandboxRuntime: { tier: 'docker' }, + dataStores: {}, + }), + ]); + expect(plan.changes[0]?.refusal).toMatchObject({ + code: 'SETTINGS_INVALID', + data: { + issues: expect.arrayContaining([ + expect.objectContaining({ path: '/config/version' }), + expect.objectContaining({ path: '/config/sandboxRuntime/tier' }), + ]), + }, + }); + }); +}); + +describe('applying a change of the deployment settings', () => { + it('saves through the operator’s writer and answers the hash stored', async () => { + const answer = await applySettings( + operator(), + registry, + [change({ version: 1, sandboxRuntime: { tier: 'gvisor' } })], + { deployment: null }, + ); + const read = await deploymentSettings.read(operator(), null); + expect(answer).toEqual({ + applied: [ + { + kind: 'deployment', + id: null, + key: 'deployment', + action: 'create', + hash: read?.hash, + }, + ], + skipped: [], + }); + expect(read?.config).toEqual({ + version: 1, + sandboxRuntime: { tier: 'gvisor' }, + }); + expect(createAuditLog.mock.lastCall?.[1]).toMatchObject({ + action: 'deployment_config_saved', + actorEmail: OPERATOR, + }); + }); + + it('answers a change made meanwhile as stale, with the hash stored now', async () => { + const created = await applySettings( + operator(), + registry, + [change({ version: 1 })], + { deployment: null }, + ); + const [first] = (created.applied ?? []) as Array<{ hash: string }>; + await writeFile( + path.join(dir, 'deployment.yml'), + 'version: 1\nsandboxRuntime:\n tier: kata\n', + ); + const answer = await applySettings( + operator(), + registry, + [change({ version: 1, sandboxRuntime: { tier: 'gvisor' } })], + { deployment: first?.hash ?? null }, + ); + expect(answer).toMatchObject({ + code: 'SETTINGS_STALE', + data: { + currentHash: (await deploymentSettings.read(operator(), null))?.hash, + }, + }); + }); +}); diff --git a/services/platform/backend/domains/deployment/settings-resource.ts b/services/platform/backend/domains/deployment/settings-resource.ts new file mode 100644 index 0000000000..126cea9699 --- /dev/null +++ b/services/platform/backend/domains/deployment/settings-resource.ts @@ -0,0 +1,161 @@ +import { deploymentConfigSchema } from '@tale/shared/schemas/deployment'; +import type { SettingsEffect } from '@tale/shared/schemas/settings-kinds'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { isDeploymentEditor } from '../../core/deployment/editors.ts'; +import { ConfigurationError } from '../../core/lib/config_store/precondition'; +import { + callerEmail, + identifySingle, + parseSettingsConfig, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { + DeploymentError, + type InstanceAdminAuth, + readDeploymentConfigView, + requireInstanceAdmin, + saveDeploymentConfig, +} from './service.ts'; + +/** + * This deployment's own settings as a settings kind over MCP + * (`deployment`): one resource for every organization on the deployment, + * read and saved through the writer the operator's settings use, behind the + * same gate — reading takes an owner or admin of any organization, changing + * additionally an address on the deployment's editor allowlist. + */ + +/** The person behind the call as the deployment's gate reads them. */ +async function instanceAdmin( + ctx: SettingsContext, + write: boolean, +): Promise { + const email = (await callerEmail(ctx)) ?? ''; + return requireInstanceAdmin( + ctx.sql, + { id: ctx.caller.userId, email }, + { write }, + ); +} + +/** + * A refusal of the deployment's writer as an agent reads it: a version + * conflict is the conflict every other writer raises, so the call answers + * it with the hash stored now; a file the server cannot read is the + * operator's to repair, not a fault of the call. + */ +function asRefusal(error: unknown): unknown { + if (!(error instanceof DeploymentError)) return error; + if (error.code === 'DEPLOYMENT_VERSION_CONFLICT') { + return new ConfigurationError('CONFIG_VERSION_CONFLICT', error.message); + } + if (error.code === 'DEPLOYMENT_CONFIG_UNREADABLE') { + return new SettingsRefusalError( + error.code, + 'the deployment settings file cannot be read', + { + status: 409, + hint: 'whoever runs this Tale repairs the file on the server; nothing changes it over MCP until then', + }, + ); + } + if (error.status === 500) return error; + const hint = GATE_HINTS[error.code]; + return new SettingsRefusalError(error.code, error.message, { + status: error.status, + ...(hint === undefined ? {} : { hint }), + ...(Object.keys(error.data).length === 0 ? {} : { data: error.data }), + }); +} + +/** What the person behind a refused call can do about the gate. */ +const GATE_HINTS: Readonly> = { + FORBIDDEN_INSTANCE_ADMIN: + 'the deployment settings are read by an owner or admin of an organization on this deployment', + FORBIDDEN_DEPLOYMENT_EDITOR: + "they are changed only by the addresses on the deployment's editor allowlist, which whoever runs this Tale keeps", +}; + +async function withRefusals(run: () => Promise): Promise { + try { + return await run(); + } catch (error) { + throw asRefusal(error); + } +} + +async function readDeployment( + ctx: SettingsContext, +): Promise { + return withRefusals(async () => { + const view = await readDeploymentConfigView( + await instanceAdmin(ctx, false), + ); + if (view.hash === null) return null; + return { id: null, config: view.config, hash: view.hash }; + }); +} + +function sandboxRuntimeOf(config: unknown): unknown { + return isRecord(config) ? (config.sandboxRuntime ?? null) : null; +} + +export const deploymentSettings: SettingsKindHandler = { + kind: 'deployment', + access: async (ctx) => { + try { + await instanceAdmin(ctx, false); + } catch (error) { + if (error instanceof DeploymentError && error.status === 403) { + return { read: false, write: false }; + } + throw error; + } + return { read: true, write: isDeploymentEditor(await callerEmail(ctx)) }; + }, + identify: identifySingle('deployment'), + list: async (ctx) => { + const current = await readDeployment(ctx); + return { items: current === null ? [] : [current], nextCursor: null }; + }, + read: async (ctx) => readDeployment(ctx), + plan: async (ctx, change, current) => { + await withRefusals(() => instanceAdmin(ctx, true)); + const after = parseSettingsConfig( + deploymentConfigSchema, + change.config, + 'the deployment settings', + ); + const effects: SettingsEffect[] = []; + // The sandbox spawner reads its runtime when the deployment starts. + if ( + configurationHash(sandboxRuntimeOf(after)) !== + configurationHash(sandboxRuntimeOf(current?.config ?? null)) + ) { + effects.push('restart-required'); + } + return { + after, + unchanged: + current !== null && + configurationHash(after) === configurationHash(current.config), + effects, + }; + }, + apply: async (ctx, change, expectedHash) => + withRefusals(async () => { + const { hash } = await saveDeploymentConfig( + ctx.sql, + await instanceAdmin(ctx, true), + { config: change.config, expectedHash }, + ); + return { hash }; + }), +}; diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index 6de7fe140e..75c268f9f6 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -6,6 +6,7 @@ */ import { brandingSettings } from '../../branding/settings-resource.ts'; +import { deploymentSettings } from '../../deployment/settings-resource.ts'; import { governanceSettings } from '../../governance/settings-resource.ts'; import { knowledgeEmbeddingSettings } from '../../knowledge/settings-resource.ts'; import type { SettingsRegistry } from './registry.ts'; @@ -14,4 +15,5 @@ export const SETTINGS_HANDLERS: SettingsRegistry = { governance: governanceSettings, 'knowledge-embedding': knowledgeEmbeddingSettings, branding: brandingSettings, + deployment: deploymentSettings, }; From 2c2bbd8524c66d4c81074878f35c3d3763ef8b8d Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:13:04 +0200 Subject: [PATCH 24/35] refactor(platform): lift the provider definition's checks out of its save checkProviderDefinition answers a definition as the save checks it (its shape under its name, a name no shipped provider has, endpoints without credentials that pass the host policy) and providerCredentialCount how many credentials still name a provider, so a plan can ask both without writing. The save and the deletion answer exactly as before. --- .../backend/domains/providers/config.ts | 81 ++++++++++++++----- 1 file changed, 60 insertions(+), 21 deletions(-) diff --git a/services/platform/backend/domains/providers/config.ts b/services/platform/backend/domains/providers/config.ts index 91ea3397f2..bb53ad6e00 100644 --- a/services/platform/backend/domains/providers/config.ts +++ b/services/platform/backend/domains/providers/config.ts @@ -94,19 +94,12 @@ export interface SaveProviderDefinitionOptions { alongside?: (tx: TransactionSql) => Promise; } -export async function saveProviderDefinition( - sql: Sql, - scope: { - organizationId: string; - orgSlug: string; - userId: string; - email?: string; - }, +/** A definition as a save checks it, and the file it is kept in. */ +function checkedDefinition( + orgSlug: string, name: string, - config: ProviderDefinition, - expectedHash: string | null, - options: SaveProviderDefinitionOptions = {}, -) { + config: unknown, +): { definition: ProviderDefinition; file: string } { const parsed = providerDefinitionSchema.safeParse(config); if (!parsed.success || parsed.data.name !== name) { throw new ConfigurationError( @@ -115,7 +108,7 @@ export async function saveProviderDefinition( 400, ); } - const file = definitionPath(scope.orgSlug, name); + const file = definitionPath(orgSlug, name); for (const endpoint of [ parsed.data.baseUrl, parsed.data.harnessEndpoint?.baseUrl, @@ -134,7 +127,55 @@ export async function saveProviderDefinition( ); } } - const content = stringifyYaml(parsed.data); + return { definition: parsed.data, file }; +} + +/** + * Check a custom provider's definition as a save checks it, writing + * nothing: the definition's own shape under the name it is saved as, a + * name that is a provider's and no shipped provider's, and endpoints that + * carry no credentials and pass the deployment's host policy. Answers the + * definition as the save stores it. + */ +export function checkProviderDefinition( + orgSlug: string, + name: string, + config: unknown, +): ProviderDefinition { + return checkedDefinition(orgSlug, name, config).definition; +} + +/** How many of the organization's credentials name the provider — a + * provider is removed only once none does. */ +export async function providerCredentialCount( + db: Sql | TransactionSql, + organizationId: string, + name: string, +): Promise { + const rows = await db<{ count: number }[]>` + SELECT count(*)::int AS count + FROM app.provider_credentials + WHERE org_id = ${organizationId} + AND provider_slug = ${name} + `; + return rows[0]?.count ?? 0; +} + +export async function saveProviderDefinition( + sql: Sql, + scope: { + organizationId: string; + orgSlug: string; + userId: string; + email?: string; + }, + name: string, + config: ProviderDefinition, + expectedHash: string | null, + options: SaveProviderDefinitionOptions = {}, +) { + const { definition, file } = checkedDefinition(scope.orgSlug, name, config); + const content = stringifyYaml(definition); const save = (tx: TransactionSql) => withConfigWriteLock(tx, scope.orgSlug, 'providers', async () => { const current = await readProviderDefinition(scope.orgSlug, name); @@ -248,13 +289,11 @@ export async function deleteProviderDefinition( ); } assertExpectedHash(current.hash, expectedHash); - const rows = await tx<{ count: number }[]>` - SELECT count(*)::int AS count - FROM app.provider_credentials - WHERE org_id = ${scope.organizationId} - AND provider_slug = ${name} - `; - const inUse = rows[0]?.count ?? 0; + const inUse = await providerCredentialCount( + tx, + scope.organizationId, + name, + ); if (inUse > 0) { throw new ConfigurationError( 'PROVIDER_IN_USE', From dcc1a277808c8755099a56969631d3d4ea21a30c Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:15:24 +0200 Subject: [PATCH 25/35] feat(platform): change an organization's own AI providers over MCP The provider kind reads, saves and removes the providers an organization defined through the writers the AI providers page uses, behind its owner, admin or developer gate, with their checks, history and audit rows. A plan says when a change sends the organization's requests to another endpoint, refuses removing a provider credentials still name, and the refresh-catalogs act reads one provider's catalog afresh without repeating what the provider answered. The catalog refresh is split per provider so the act and the page's refresh share it. --- .../backend/domains/mcp/settings/handlers.ts | 2 + .../backend/domains/providers/management.ts | 64 ++-- .../providers/settings-resource.test.ts | 279 ++++++++++++++++++ .../domains/providers/settings-resource.ts | 209 +++++++++++++ 4 files changed, 531 insertions(+), 23 deletions(-) create mode 100644 services/platform/backend/domains/providers/settings-resource.test.ts create mode 100644 services/platform/backend/domains/providers/settings-resource.ts diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index 75c268f9f6..0d0fa898bb 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -9,9 +9,11 @@ import { brandingSettings } from '../../branding/settings-resource.ts'; import { deploymentSettings } from '../../deployment/settings-resource.ts'; import { governanceSettings } from '../../governance/settings-resource.ts'; import { knowledgeEmbeddingSettings } from '../../knowledge/settings-resource.ts'; +import { providerSettings } from '../../providers/settings-resource.ts'; import type { SettingsRegistry } from './registry.ts'; export const SETTINGS_HANDLERS: SettingsRegistry = { + provider: providerSettings, governance: governanceSettings, 'knowledge-embedding': knowledgeEmbeddingSettings, branding: brandingSettings, diff --git a/services/platform/backend/domains/providers/management.ts b/services/platform/backend/domains/providers/management.ts index 687f0815a9..70dcc48602 100644 --- a/services/platform/backend/domains/providers/management.ts +++ b/services/platform/backend/domains/providers/management.ts @@ -1,3 +1,4 @@ +import type { ProviderDefinition } from '@tale/shared/schemas/providers'; import type { Sql } from 'postgres'; import { isAdminOrDeveloperRole } from '../../auth/membership.ts'; @@ -39,30 +40,47 @@ export async function refreshProviderCatalogs( ): Promise { const results: CatalogRefreshResult[] = []; for (const provider of resolveProvidersForOrg(org.orgSlug)) { - if ( - provider.catalog.source === 'static' || - provider.catalog.source === 'none' - ) { - continue; - } - try { - const bearerToken = await resolveCatalogBearer( - sql, - org.organizationId, - provider, - ); - const entries = await getProviderCatalog(provider, { - forceRefresh: true, - ...(bearerToken !== undefined ? { bearerToken } : {}), - }); - results.push({ name: provider.name, modelCount: entries.length }); - } catch (error) { - results.push({ - name: provider.name, - modelCount: 0, - error: error instanceof Error ? error.message : String(error), - }); + if (hasLiveCatalog(provider)) { + results.push(await refreshProviderCatalog(sql, org, provider)); } } return results; } + +/** Whether a provider's models come from a live source a refresh reads + * again; a static list or none has nothing to refresh. */ +export function hasLiveCatalog(provider: ProviderDefinition): boolean { + return ( + provider.catalog.source !== 'static' && provider.catalog.source !== 'none' + ); +} + +/** + * Fetch one provider's model catalog afresh, with the organization's + * listing key for it when it holds one: how many models it lists now, or + * why it could not be read. + */ +export async function refreshProviderCatalog( + sql: Sql, + org: { readonly organizationId: string }, + provider: ProviderDefinition, +): Promise { + try { + const bearerToken = await resolveCatalogBearer( + sql, + org.organizationId, + provider, + ); + const entries = await getProviderCatalog(provider, { + forceRefresh: true, + ...(bearerToken !== undefined ? { bearerToken } : {}), + }); + return { name: provider.name, modelCount: entries.length }; + } catch (error) { + return { + name: provider.name, + modelCount: 0, + error: error instanceof Error ? error.message : String(error), + }; + } +} diff --git a/services/platform/backend/domains/providers/settings-resource.test.ts b/services/platform/backend/domains/providers/settings-resource.test.ts new file mode 100644 index 0000000000..4e42d7a553 --- /dev/null +++ b/services/platform/backend/domains/providers/settings-resource.test.ts @@ -0,0 +1,279 @@ +// @vitest-environment node + +/** + * The organization's own AI providers over MCP, through the writers the AI + * providers page uses: the config store is a temporary directory, the + * database a double, and the provider's catalog and the audit chain are + * doubles that record. + */ + +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import type { Sql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { bearer, catalog, createAuditLog, credentials } = vi.hoisted(() => ({ + bearer: vi.fn(), + catalog: vi.fn(), + createAuditLog: vi.fn(), + // How many of the organization's credentials name the provider. + credentials: { count: 0 }, +})); + +vi.mock('../audit_logs/service', () => ({ createAuditLog })); +vi.mock('../provider_credentials/service.ts', async (original) => ({ + ...(await original()), + resolveCatalogBearer: bearer, +})); +vi.mock('../../core/lib/providers/catalog_fetch.ts', async (original) => ({ + ...(await original< + typeof import('../../core/lib/providers/catalog_fetch.ts') + >()), + getProviderCatalog: catalog, +})); + +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { providerSettings } from './settings-resource.ts'; + +const registry = { provider: providerSettings }; + +const definition = { + name: 'local-chat', + displayName: 'Local chat', + apiFormat: 'openai', + baseUrl: 'https://models.example.test/v1', + catalog: { source: 'models-endpoint' }, + embedding: 'unknown', + auth: [{ method: 'env' }], +}; + +function contextOf(role: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + const tag = async (strings: TemplateStringsArray) => { + const text = strings.join('?'); + if (text.includes('FROM "user"')) + return [{ email: `${role}@example.test` }]; + if (text.includes('app.provider_credentials')) { + return [{ count: credentials.count }]; + } + return []; + }; + const sql = Object.assign(tag, { + begin: (work: (tx: unknown) => Promise) => work(tag), + }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: sql as unknown as Sql, caller }; +} + +const set = (config: unknown, id?: string) => ({ + kind: 'provider' as const, + ...(id === undefined ? {} : { id }), + op: 'set' as const, + config, +}); + +/** Define the provider as an admin, and answer its hash. */ +async function defined(config: unknown = definition): Promise { + const answer = await applySettings( + contextOf('admin'), + registry, + [set(config)], + { + 'provider/local-chat': null, + }, + ); + const [applied] = (answer.applied ?? []) as Array<{ hash: string }>; + if (applied === undefined) throw new Error(JSON.stringify(answer)); + createAuditLog.mockClear(); + return applied.hash; +} + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(path.join(tmpdir(), 'tale-provider-kind-')); + vi.stubEnv('TALE_CONFIG_DIR', dir); + credentials.count = 0; + bearer.mockReset(); + catalog.mockReset(); + createAuditLog.mockReset(); + createAuditLog.mockResolvedValue('row-1'); +}); + +afterEach(async () => { + vi.unstubAllEnvs(); + await rm(dir, { recursive: true, force: true }); +}); + +describe('who reads and changes the providers [MCP-R10]', () => { + it('lets an owner, admin or developer read and change them, and refuses a member', async () => { + for (const role of ['owner', 'admin', 'developer']) { + expect(await providerSettings.access(contextOf(role))).toEqual({ + read: true, + write: true, + }); + } + expect(await providerSettings.access(contextOf('member'))).toEqual({ + read: false, + write: false, + }); + const answer = await getSettings(contextOf('member'), registry, { + kinds: ['provider'], + }); + expect(answer.refused).toEqual([ + expect.objectContaining({ + code: 'FORBIDDEN', + error: 'Only owners, admins and developers can change AI providers.', + }), + ]); + }); +}); + +describe('defining a provider', () => { + it('saves it through the page’s writer and lists it with its hash, audited under the key holder', async () => { + const hash = await defined(); + const answer = await getSettings(contextOf('developer'), registry, { + kinds: ['provider'], + }); + expect(answer.resources).toEqual([ + { + kind: 'provider', + id: 'local-chat', + key: 'provider/local-chat', + hash, + config: expect.objectContaining({ name: 'local-chat' }), + }, + ]); + await applySettings( + contextOf('developer'), + registry, + [set({ ...definition, displayName: 'Local models' })], + { 'provider/local-chat': hash }, + ); + expect(createAuditLog.mock.lastCall?.[1]).toMatchObject({ + action: 'provider_definition.saved', + actorId: 'user-developer', + actorEmail: 'developer@example.test', + resourceId: 'local-chat', + }); + }); + + it.each([ + [ + 'an id another than the name', + set(definition, 'other'), + 'SETTINGS_ID_INVALID', + ], + [ + 'a provider Tale ships', + set({ ...definition, name: 'openai' }), + 'PROVIDER_NAME_RESERVED', + ], + [ + 'an endpoint carrying a password', + set({ ...definition, baseUrl: 'https://u:p@models.example.test/v1' }), + 'PROVIDER_ENDPOINT_INVALID', + ], + [ + 'a field a provider does not have', + set({ ...definition, baseURL: 'https://models.example.test/v2' }), + 'SETTINGS_INVALID', + ], + ])('refuses %s before anything is written', async (_what, change, code) => { + const plan = await planSettings(contextOf('admin'), registry, [change]); + expect(plan.changes[0]?.refusal?.code).toBe(code); + }); + + it('says when a change sends the organization’s requests to another endpoint', async () => { + await defined(); + const plan = await planSettings(contextOf('admin'), registry, [ + set({ ...definition, baseUrl: 'https://other.example.test/v1' }), + // A new display name sends nothing elsewhere. + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'update', + effects: ['changes-serving-account'], + risk: 'high', + }); + const renamed = await planSettings(contextOf('admin'), registry, [ + set({ ...definition, displayName: 'Local models' }), + ]); + expect(renamed.changes[0]).toMatchObject({ action: 'update', effects: [] }); + }); +}); + +describe('removing a provider', () => { + it('is refused while credentials still name it, and removes it once none does', async () => { + const hash = await defined(); + credentials.count = 2; + const refused = await planSettings(contextOf('admin'), registry, [ + { kind: 'provider', id: 'local-chat', op: 'delete' }, + ]); + expect(refused.changes[0]?.refusal).toMatchObject({ + code: 'PROVIDER_IN_USE', + error: '2 credentials still use this provider. Delete them first.', + data: { credentials: 2 }, + }); + credentials.count = 0; + const answer = await applySettings( + contextOf('admin'), + registry, + [{ kind: 'provider', id: 'local-chat', op: 'delete' }], + { 'provider/local-chat': hash }, + ); + expect(answer).toMatchObject({ + applied: [{ action: 'delete', hash: null }], + }); + expect(await providerSettings.read(contextOf('admin'), 'local-chat')).toBe( + null, + ); + }); +}); + +describe('refreshing a provider’s catalog', () => { + it('reads it afresh with the organization’s key, and never repeats what the provider answered', async () => { + const hash = await defined(); + bearer.mockResolvedValue('sk-listing'); + catalog.mockResolvedValue([{ id: 'model-a' }]); + const act = { + kind: 'provider' as const, + id: 'local-chat', + op: 'act' as const, + act: 'refresh-catalogs', + }; + const plan = await planSettings(contextOf('admin'), registry, [act]); + expect(plan.changes[0]).toMatchObject({ + action: 'act', + effects: ['reaches-vendor'], + }); + const answer = await applySettings(contextOf('admin'), registry, [act], { + 'provider/local-chat': hash, + }); + expect(answer).toMatchObject({ applied: [{ action: 'act', hash }] }); + expect(catalog).toHaveBeenCalledWith( + expect.objectContaining({ name: 'local-chat' }), + { forceRefresh: true, bearerToken: 'sk-listing' }, + ); + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + catalog.mockRejectedValue(new Error('private upstream request data')); + const failed = await applySettings(contextOf('admin'), registry, [act], { + 'provider/local-chat': hash, + }); + expect(failed).toMatchObject({ code: 'CATALOG_REFRESH_FAILED' }); + expect(JSON.stringify(failed)).not.toContain('private upstream'); + warn.mockRestore(); + }); +}); diff --git a/services/platform/backend/domains/providers/settings-resource.ts b/services/platform/backend/domains/providers/settings-resource.ts new file mode 100644 index 0000000000..4637a1fe06 --- /dev/null +++ b/services/platform/backend/domains/providers/settings-resource.ts @@ -0,0 +1,209 @@ +import { providerDefinitionSchema } from '@tale/shared/schemas/providers'; +import type { SettingsEffect } from '@tale/shared/schemas/settings-kinds'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { loadOrgCustomProviders } from '../../core/lib/providers/org_providers.ts'; +import { + identityOf, + pageOf, + parseSettingsConfig, + settingsActor, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsChange, + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { + checkProviderDefinition, + deleteProviderDefinition, + providerCredentialCount, + readProviderDefinition, + saveProviderDefinition, +} from './config.ts'; +import { + hasLiveCatalog, + mayManageProviders, + refreshProviderCatalog, +} from './management.ts'; + +/** + * The organization's own AI providers as a settings kind over MCP + * (`provider`): one resource per provider the organization defined, named + * by the provider's name, read, saved and removed through the writers the + * AI providers page uses — with their checks, their compare-and-set, their + * history and their audit rows. The providers Tale ships are not settings; + * their credentials are (`provider-credential`). + */ + +const ID_FORM = 'the provider name, such as local-chat'; + +function assertProviderManager(role: string): void { + if (!mayManageProviders(role)) { + throw new SettingsRefusalError( + 'FORBIDDEN', + 'Only owners, admins and developers can change AI providers.', + { + status: 403, + hint: 'the role of the person whose key this is cannot make this change; an owner, admin or developer can', + }, + ); + } +} + +async function readProvider( + ctx: SettingsContext, + name: string, +): Promise { + const snapshot = await readProviderDefinition(ctx.caller.orgSlug, name); + if (snapshot.config === null || snapshot.hash === null) return null; + return { id: name, config: snapshot.config, hash: snapshot.hash }; +} + +/** The provider a change names. */ +function nameOf(change: SettingsChange): string { + const carried = + change.op === 'set' && + isRecord(change.config) && + typeof change.config.name === 'string' + ? change.config.name + : undefined; + return identityOf('provider', change.id, carried, ID_FORM); +} + +/** Where a definition sends the organization's requests, and with them + * its keys. */ +function endpointsOf(config: unknown): unknown { + if (!isRecord(config)) return null; + const harness = isRecord(config.harnessEndpoint) + ? config.harnessEndpoint.baseUrl + : undefined; + return [config.baseUrl ?? null, config.apiFormat ?? null, harness ?? null]; +} + +export const providerSettings: SettingsKindHandler = { + kind: 'provider', + access: async ({ caller }) => { + const allowed = mayManageProviders(caller.role); + return { read: allowed, write: allowed }; + }, + identify: (change) => nameOf(change), + list: async (ctx, query) => { + assertProviderManager(ctx.caller.role); + const names = + query.ids ?? + loadOrgCustomProviders(ctx.caller.orgSlug) + .map((provider) => provider.name) + .sort((a, b) => a.localeCompare(b)); + const items: SettingsResource[] = []; + for (const name of names) { + const provider = await readProvider(ctx, name); + if (provider !== null) items.push(provider); + } + return pageOf(items, query.cursor, 100); + }, + read: async (ctx, id) => { + assertProviderManager(ctx.caller.role); + return id === null ? null : readProvider(ctx, id); + }, + plan: async (ctx, change, current) => { + assertProviderManager(ctx.caller.role); + const name = nameOf(change); + if (change.op === 'delete') { + if (current === null) return {}; + const inUse = await providerCredentialCount( + ctx.sql, + ctx.caller.organizationId, + name, + ); + if (inUse > 0) { + throw new SettingsRefusalError( + 'PROVIDER_IN_USE', + inUse === 1 + ? '1 credential still uses this provider. Delete it first.' + : `${inUse} credentials still use this provider. Delete them first.`, + { + status: 409, + hint: 'remove its credentials first: kind provider-credential, ids beginning with the provider name', + data: { credentials: inUse }, + }, + ); + } + return {}; + } + if (change.op === 'act') { + // Reading a catalog sends the organization's key to the provider. + return { effects: ['reaches-vendor'] }; + } + parseSettingsConfig( + providerDefinitionSchema, + change.config, + `the provider ${name}`, + ); + const after = checkProviderDefinition( + ctx.caller.orgSlug, + name, + change.config, + ); + const effects: SettingsEffect[] = []; + if ( + current !== null && + configurationHash(endpointsOf(after)) !== + configurationHash(endpointsOf(current.config)) + ) { + effects.push('changes-serving-account'); + } + return { + after, + unchanged: + current !== null && + configurationHash(after) === configurationHash(current.config), + effects, + }; + }, + apply: async (ctx, change, expectedHash) => { + const name = nameOf(change); + const actor = await settingsActor(ctx); + const scope = { ...actor, orgSlug: ctx.caller.orgSlug }; + if (change.op === 'delete') { + await deleteProviderDefinition(ctx.sql, scope, name, expectedHash); + return { hash: null }; + } + if (change.op === 'act') { + const provider = loadOrgCustomProviders(ctx.caller.orgSlug).find( + (entry) => entry.name === name, + ); + if (provider !== undefined && hasLiveCatalog(provider)) { + const result = await refreshProviderCatalog(ctx.sql, actor, provider); + if (result.error !== undefined) { + // The provider's own words may carry what its endpoint answered; + // they stay in the server's log. + console.warn( + `[providers] refreshing the catalog of "${name}" over MCP failed:`, + result.error, + ); + throw new SettingsRefusalError( + 'CATALOG_REFRESH_FAILED', + `the model catalog of ${name} could not be read`, + { + status: 409, + hint: "check the provider's endpoint and its credential, then refresh again", + }, + ); + } + } + return { hash: (await readProvider(ctx, name))?.hash ?? null }; + } + const saved = await saveProviderDefinition( + ctx.sql, + scope, + name, + checkProviderDefinition(ctx.caller.orgSlug, name, change.config), + expectedHash, + ); + return { hash: saved.hash }; + }, +}; From 801520562fb5561ce931684af0c28692de345ccb Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:20:07 +0200 Subject: [PATCH 26/35] feat(platform): change provider credentials over MCP The provider-credential kind lists every credential of the organization by provider and name, never with its secret, and creates, edits and removes them through the writers the AI providers page uses, behind its owner, admin or developer gate; the documents and websites follow a credential the embedding model resolves, as after a save on the page. As a declaration the CLI applies, only a credential that reads its key from an environment variable is created or changed; one with a key or a subscription is entered in Tale and may only be removed here. A removal checks the hash the agent read inside its serializable transaction. --- .../backend/domains/mcp/settings/handlers.ts | 2 + .../domains/provider_credentials/service.ts | 2 +- .../settings-resource.test.ts | 437 ++++++++++++++++++ .../provider_credentials/settings-resource.ts | 284 ++++++++++++ 4 files changed, 724 insertions(+), 1 deletion(-) create mode 100644 services/platform/backend/domains/provider_credentials/settings-resource.test.ts create mode 100644 services/platform/backend/domains/provider_credentials/settings-resource.ts diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index 0d0fa898bb..1636dfe7a0 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -9,11 +9,13 @@ import { brandingSettings } from '../../branding/settings-resource.ts'; import { deploymentSettings } from '../../deployment/settings-resource.ts'; import { governanceSettings } from '../../governance/settings-resource.ts'; import { knowledgeEmbeddingSettings } from '../../knowledge/settings-resource.ts'; +import { providerCredentialSettings } from '../../provider_credentials/settings-resource.ts'; import { providerSettings } from '../../providers/settings-resource.ts'; import type { SettingsRegistry } from './registry.ts'; export const SETTINGS_HANDLERS: SettingsRegistry = { provider: providerSettings, + 'provider-credential': providerCredentialSettings, governance: governanceSettings, 'knowledge-embedding': knowledgeEmbeddingSettings, branding: brandingSettings, diff --git a/services/platform/backend/domains/provider_credentials/service.ts b/services/platform/backend/domains/provider_credentials/service.ts index 394600067d..487659fc83 100644 --- a/services/platform/backend/domains/provider_credentials/service.ts +++ b/services/platform/backend/domains/provider_credentials/service.ts @@ -342,7 +342,7 @@ function credentialHash(row: Omit): string { } export async function listCredentials( - sql: Sql, + sql: Sql | TransactionSql, scope: CredentialScope, providerSlug?: string, ): Promise { diff --git a/services/platform/backend/domains/provider_credentials/settings-resource.test.ts b/services/platform/backend/domains/provider_credentials/settings-resource.test.ts new file mode 100644 index 0000000000..2fadd08c87 --- /dev/null +++ b/services/platform/backend/domains/provider_credentials/settings-resource.test.ts @@ -0,0 +1,437 @@ +// @vitest-environment node + +/** + * Provider credentials over MCP. The credential writers are the AI + * providers page's own, held by their own suites against a real schema; + * here they are an in-memory table with the same gate, hash and refusals, + * so what the kind adds — which credentials it takes, its ids, its plan + * and its compare-and-set on a removal — is what is tested. + */ + +import { configurationHash } from '@tale/shared/utils/configuration-hash'; +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { CredentialListItem, CredentialScope } from './service.ts'; + +const { follow, table, usedByEmbedding } = vi.hoisted(() => ({ + follow: vi.fn(), + table: new Map>(), + usedByEmbedding: new Set(), +})); + +vi.mock('@tale/shared/db/serializable', () => ({ + transactSerializable: ( + _sql: unknown, + work: (tx: unknown) => Promise, + ) => work({}), +})); +vi.mock('./embedding-follow.ts', () => ({ + followEmbeddingCredential: follow, +})); +vi.mock('./service.ts', async (original) => { + const actual = await original(); + const { ConfigurationError } = + await import('../../core/lib/config_store/precondition'); + const hashed = (row: Omit) => ({ + ...row, + hash: configurationHash(row), + }); + let next = 0; + return { + ...actual, + listCredentials: async ( + _db: unknown, + scope: CredentialScope, + providerSlug?: string, + ) => { + actual.assertCredentialAdmin(scope); + return [...table.values()] + .filter( + (row) => + providerSlug === undefined || row.providerSlug === providerSlug, + ) + .map(hashed); + }, + credentialDependents: async ( + _db: unknown, + _scope: unknown, + id: string, + ) => ({ + usedBy: usedByEmbedding.has(id) ? ['embedding'] : [], + }), + createCredential: vi.fn( + async ( + _tx: unknown, + scope: CredentialScope, + args: Record, + ) => { + actual.assertCredentialAdmin(scope); + const id = `cred-${++next}`; + table.set(id, { + id, + providerSlug: String(args.providerSlug), + authMethod: String(args.authMethod), + name: String(args.name), + envName: typeof args.envName === 'string' ? args.envName : null, + endpointUrl: + typeof args.endpointUrl === 'string' ? args.endpointUrl : null, + maskedPreview: null, + modelAllowlist: Array.isArray(args.modelAllowlist) + ? (args.modelAllowlist as string[]) + : null, + isDefault: args.isDefault === true, + status: args.status === 'disabled' ? 'disabled' : 'active', + createdAt: next, + updatedAt: next, + }); + return id; + }, + ), + updateCredential: vi.fn( + async ( + _tx: unknown, + _scope: CredentialScope, + id: string, + patch: Record, + expectedHash?: string, + ) => { + const row = table.get(id); + if (row === undefined) throw new Error('no such credential'); + if (expectedHash !== undefined && hashed(row).hash !== expectedHash) { + throw new ConfigurationError( + 'CONFIG_VERSION_CONFLICT', + 'Configuration changed since it was reviewed.', + ); + } + const defined = Object.fromEntries( + Object.entries(patch).filter(([, value]) => value !== undefined), + ); + table.set(id, { ...row, ...defined, updatedAt: row.updatedAt + 1 }); + }, + ), + deleteCredential: vi.fn( + async (_tx: unknown, _scope: unknown, id: string) => { + table.delete(id); + return { providerSlug: 'openai' }; + }, + ), + }; +}); + +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { + createCredential, + deleteCredential, + updateCredential, +} from './service.ts'; +import { providerCredentialSettings } from './settings-resource.ts'; + +const registry = { 'provider-credential': providerCredentialSettings }; + +function contextOf(role: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + const tag = async () => [{ email: `${role}@example.test` }]; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: tag as unknown as Sql, caller }; +} + +const ENV_KEY = { + providerSlug: 'openai', + authMethod: 'env', + name: 'Production key', + envName: 'TALE_PROVIDER_KEY_OPENAI_PROD', + endpointUrl: null, + modelAllowlist: null, + status: 'active', + isDefault: true, +}; +const ENV_ID = 'openai/Production%20key'; + +function stored( + id: string, + fields: Partial>, +): void { + table.set(id, { + id, + providerSlug: 'openai', + authMethod: 'env', + name: 'Production key', + envName: 'TALE_PROVIDER_KEY_OPENAI_PROD', + endpointUrl: null, + maskedPreview: null, + modelAllowlist: null, + isDefault: true, + status: 'active', + createdAt: 1, + updatedAt: 1, + ...fields, + }); +} + +async function hashOf(id: string): Promise { + const read = await providerCredentialSettings.read(contextOf('admin'), id); + if (read === null) throw new Error(`no ${id}`); + return read.hash; +} + +beforeEach(() => { + table.clear(); + usedByEmbedding.clear(); + vi.clearAllMocks(); +}); + +describe('who reads and changes credentials [MCP-R10]', () => { + it('lets an owner, admin or developer read and change them, and refuses a member as the page does', async () => { + for (const role of ['owner', 'admin', 'developer']) { + expect(await providerCredentialSettings.access(contextOf(role))).toEqual({ + read: true, + write: true, + }); + } + const answer = await getSettings(contextOf('member'), registry, { + kinds: ['provider-credential'], + }); + expect(answer.refused).toEqual([ + expect.objectContaining({ + code: 'FORBIDDEN_DEVELOPER_SETTINGS', + error: 'Admin or developer role required', + }), + ]); + }); +}); + +describe('reading credentials', () => { + it('lists every credential by provider and name, none with its secret', async () => { + stored('cred-env', {}); + stored('cred-key', { + authMethod: 'api-key', + name: 'Team key', + envName: null, + isDefault: false, + maskedPreview: 'sk-…Z2', + }); + const answer = await getSettings(contextOf('admin'), registry, { + kinds: ['provider-credential'], + }); + expect(answer.resources).toEqual([ + expect.objectContaining({ + key: `provider-credential/${ENV_ID}`, + id: ENV_ID, + config: ENV_KEY, + }), + expect.objectContaining({ + id: 'openai/Team%20key', + config: expect.objectContaining({ authMethod: 'api-key' }), + }), + ]); + expect(JSON.stringify(answer)).not.toContain('sk-…Z2'); + }); +}); + +describe('planning a credential change', () => { + it('creates a credential that reads its key from the environment, as a new default that serves at once', async () => { + const plan = await planSettings(contextOf('admin'), registry, [ + { kind: 'provider-credential', op: 'set', config: ENV_KEY }, + ]); + expect(plan.changes[0]).toMatchObject({ + id: ENV_ID, + key: `provider-credential/${ENV_ID}`, + action: 'create', + effects: ['changes-serving-account'], + }); + }); + + it('refuses a credential with a key or a subscription, which is entered in Tale', async () => { + stored('cred-key', { authMethod: 'api-key', envName: null }); + const existing = await planSettings(contextOf('admin'), registry, [ + { kind: 'provider-credential', op: 'set', config: ENV_KEY }, + ]); + expect(existing.changes[0]?.refusal).toMatchObject({ + code: 'SETTINGS_TALE_ONLY', + hint: expect.stringContaining('Settings > AI providers'), + }); + const created = await planSettings(contextOf('admin'), registry, [ + { + kind: 'provider-credential', + op: 'set', + config: { ...ENV_KEY, name: 'Other', authMethod: 'subscription-key' }, + }, + ]); + expect(created.changes[0]?.refusal?.code).toBe('SETTINGS_TALE_ONLY'); + }); + + it('refuses a key typed into the change, naming where, never the key', async () => { + const plan = await planSettings(contextOf('admin'), registry, [ + { + kind: 'provider-credential', + op: 'set', + config: { ...ENV_KEY, secret: 'sk-000000000000000000000000' }, + }, + ]); + expect(plan.changes[0]?.refusal).toMatchObject({ + code: 'SECRET_ARGUMENT_REFUSED', + data: { places: [{ pointer: '/config/secret' }] }, + }); + expect(JSON.stringify(plan)).not.toContain('sk-0000'); + }); + + it.each([ + ['an id naming another credential', 'openai/Other', 'SETTINGS_ID_INVALID'], + ['an id with no provider', 'Production%20key', 'SETTINGS_ID_INVALID'], + ])('refuses %s', async (_what, id, code) => { + const plan = await planSettings(contextOf('admin'), registry, [ + { kind: 'provider-credential', id, op: 'set', config: ENV_KEY }, + ]); + expect(plan.changes[0]?.refusal?.code).toBe(code); + }); + + it('says when an edit changes what serves the provider, and nothing when it narrows the models', async () => { + stored('cred-env', {}); + const plan = await planSettings(contextOf('admin'), registry, [ + { + kind: 'provider-credential', + op: 'set', + config: { ...ENV_KEY, status: 'disabled', isDefault: false }, + }, + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'update', + effects: ['changes-serving-account'], + }); + const narrowed = await planSettings(contextOf('admin'), registry, [ + { + kind: 'provider-credential', + op: 'set', + config: { ...ENV_KEY, modelAllowlist: ['gpt-6-luna'] }, + }, + ]); + expect(narrowed.changes[0]).toMatchObject({ + action: 'update', + effects: [], + }); + }); +}); + +describe('applying a credential change', () => { + it('creates and edits through the page’s writers, and the documents follow', async () => { + const created = await applySettings( + contextOf('admin'), + registry, + [{ kind: 'provider-credential', op: 'set', config: ENV_KEY }], + { [`provider-credential/${ENV_ID}`]: null }, + ); + expect(created).toMatchObject({ + applied: [{ action: 'create', hash: await hashOf(ENV_ID) }], + }); + expect(createCredential).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + userId: 'user-admin', + email: 'admin@example.test', + role: 'admin', + }), + { + providerSlug: 'openai', + authMethod: 'env', + name: 'Production key', + envName: 'TALE_PROVIDER_KEY_OPENAI_PROD', + status: 'active', + isDefault: true, + }, + null, + ); + expect(follow).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ organizationId: 'org-1' }), + 'cred-1', + ); + + const hash = await hashOf(ENV_ID); + await applySettings( + contextOf('admin'), + registry, + [ + { + kind: 'provider-credential', + op: 'set', + config: { ...ENV_KEY, envName: 'TALE_PROVIDER_KEY_OPENAI_NEXT' }, + }, + ], + { [`provider-credential/${ENV_ID}`]: hash }, + ); + expect(updateCredential).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + 'cred-1', + expect.objectContaining({ envName: 'TALE_PROVIDER_KEY_OPENAI_NEXT' }), + hash, + ); + }); + + it('refuses removing the credential the embedding model uses, and names what the removal of a default breaks', async () => { + stored('cred-env', {}); + usedByEmbedding.add('cred-env'); + const refused = await planSettings(contextOf('admin'), registry, [ + { kind: 'provider-credential', id: ENV_ID, op: 'delete' }, + ]); + expect(refused.changes[0]?.refusal).toMatchObject({ + code: 'CREDENTIAL_IN_USE', + data: { usedBy: ['embedding'] }, + }); + usedByEmbedding.clear(); + const plan = await planSettings(contextOf('admin'), registry, [ + { kind: 'provider-credential', id: ENV_ID, op: 'delete' }, + ]); + expect(plan.changes[0]).toMatchObject({ + action: 'delete', + effects: ['breaks-dependents'], + }); + }); + + it('removes a credential only as the agent read it, a key entered in Tale included', async () => { + stored('cred-key', { + authMethod: 'api-key', + name: 'Team key', + envName: null, + isDefault: false, + }); + const id = 'openai/Team%20key'; + const read = await hashOf(id); + // Someone edits the credential in Tale after the agent read it. + stored('cred-key', { + authMethod: 'api-key', + name: 'Team key', + envName: null, + isDefault: false, + status: 'disabled', + }); + const stale = await applySettings( + contextOf('admin'), + registry, + [{ kind: 'provider-credential', id, op: 'delete' }], + { [`provider-credential/${id}`]: read }, + ); + expect(stale).toMatchObject({ code: 'SETTINGS_STALE', applied: [] }); + const removed = await applySettings( + contextOf('admin'), + registry, + [{ kind: 'provider-credential', id, op: 'delete' }], + { [`provider-credential/${id}`]: await hashOf(id) }, + ); + expect(removed).toMatchObject({ + applied: [{ action: 'delete', hash: null }], + }); + expect(deleteCredential).toHaveBeenCalledOnce(); + }); +}); diff --git a/services/platform/backend/domains/provider_credentials/settings-resource.ts b/services/platform/backend/domains/provider_credentials/settings-resource.ts new file mode 100644 index 0000000000..7d104d0933 --- /dev/null +++ b/services/platform/backend/domains/provider_credentials/settings-resource.ts @@ -0,0 +1,284 @@ +import { transactSerializable } from '@tale/shared/db/serializable'; +import { providerEnvironmentCredentialSchema } from '@tale/shared/schemas/providers'; +import type { SettingsEffect } from '@tale/shared/schemas/settings-kinds'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { isAdminOrDeveloperRole } from '../../auth/membership.ts'; +import { assertExpectedHash } from '../../core/lib/config_store/precondition'; +import { + identityOf, + pageOf, + parseSettingsConfig, + settingsActor, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsChange, + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { followEmbeddingCredential } from './embedding-follow.ts'; +import { + assertCredentialAdmin, + assertCredentialEndpointUrl, + createCredential, + credentialDependents, + type CredentialListItem, + deleteCredential, + listCredentials, + updateCredential, +} from './service.ts'; + +/** + * The organization's provider credentials as a settings kind over MCP + * (`provider-credential`), through the writers the AI providers page + * uses, behind its owner, admin or developer gate, with their checks and + * audit rows. One resource per credential, named `/`. + * + * Every credential reads, none with its secret; only one that reads its key + * from an environment variable of the deployment is created or changed + * here, as a declaration applied by the CLI does. An API key or a + * subscription is entered in Tale, so its secret never travels through + * MCP; such a credential may still be removed. + */ + +const ID_FORM = + 'the provider and the credential name joined by a slash, the name URI-encoded, such as openai/Production%20key'; + +/** Where a person enters a credential that carries a secret. */ +const TALE_ONLY_HINT = + 'tell the person to add or change it in Tale, under Settings > AI providers; over MCP only a credential that reads its key from an environment variable is created or changed'; + +function idOf(providerSlug: string, name: string): string { + return `${providerSlug}/${encodeURIComponent(name)}`; +} + +/** The provider and the name an id names. */ +function partsOf(id: string): { providerSlug: string; name: string } { + const slash = id.indexOf('/'); + let name: string | undefined; + if (slash > 0) { + try { + name = decodeURIComponent(id.slice(slash + 1)); + } catch (error) { + console.warn( + '[provider-credentials] a settings id names no credential:', + error instanceof Error ? error.message : error, + ); + } + } + if (name === undefined || name === '') { + throw new SettingsRefusalError( + 'SETTINGS_ID_INVALID', + `"${id}" names no credential`, + { hint: `the id is ${ID_FORM}` }, + ); + } + return { providerSlug: id.slice(0, slash), name }; +} + +/** A credential as a declaration names it: what it is, never its secret. */ +function declarationOf(row: CredentialListItem): Record { + return { + providerSlug: row.providerSlug, + authMethod: row.authMethod, + name: row.name, + envName: row.envName, + endpointUrl: row.endpointUrl, + modelAllowlist: row.modelAllowlist, + status: row.status, + isDefault: row.isDefault, + }; +} + +function resourceOf(row: CredentialListItem): SettingsResource { + return { + id: idOf(row.providerSlug, row.name), + config: declarationOf(row), + hash: row.hash, + }; +} + +/** The stored credential an id names, or null. */ +async function findCredential( + ctx: SettingsContext, + id: string, +): Promise { + const { providerSlug, name } = partsOf(id); + const rows = await listCredentials( + ctx.sql, + await settingsActor(ctx), + providerSlug, + ); + return rows.find((row) => row.name === name) ?? null; +} + +/** The credential a change names. */ +function credentialIdOf(change: SettingsChange): string { + const config = + change.op === 'set' && isRecord(change.config) ? change.config : null; + const carried = + typeof config?.providerSlug === 'string' && typeof config.name === 'string' + ? idOf(config.providerSlug, config.name) + : undefined; + return identityOf('provider-credential', change.id, carried, ID_FORM); +} + +/** What the resolver serves a provider's requests with. */ +function servingOf(config: unknown): unknown { + if (!isRecord(config)) return null; + return [ + config.status ?? null, + config.isDefault ?? null, + config.envName ?? null, + config.endpointUrl ?? null, + ]; +} + +export const providerCredentialSettings: SettingsKindHandler = { + kind: 'provider-credential', + access: async ({ caller }) => { + const allowed = isAdminOrDeveloperRole(caller.role); + return { read: allowed, write: allowed }; + }, + identify: (change) => credentialIdOf(change), + list: async (ctx, query) => { + const scope = await settingsActor(ctx); + const rows = await listCredentials(ctx.sql, scope); + const wanted = query.ids === undefined ? null : new Set(query.ids); + const items = rows + .map(resourceOf) + .filter((item) => wanted === null || wanted.has(item.id ?? '')); + return pageOf(items, query.cursor, 100); + }, + read: async (ctx, id) => { + if (id === null) return null; + const row = await findCredential(ctx, id); + return row === null ? null : resourceOf(row); + }, + plan: async (ctx, change, current) => { + const scope = await settingsActor(ctx); + assertCredentialAdmin(scope); + const id = credentialIdOf(change); + if (change.op === 'delete') { + const row = current === null ? null : await findCredential(ctx, id); + if (row === null) return {}; + const { usedBy } = await credentialDependents(ctx.sql, scope, row.id); + if (usedBy.length > 0) { + throw new SettingsRefusalError( + 'CREDENTIAL_IN_USE', + 'The knowledge embedding model uses this credential. Choose another credential for it under Settings → Data residency → Embedding model first.', + { + status: 409, + hint: 'point the knowledge-embedding setting at another credential first', + data: { usedBy }, + }, + ); + } + // Nothing promotes another credential when the default goes. + return row.isDefault && row.status === 'active' + ? { effects: ['breaks-dependents'] } + : {}; + } + const sent = isRecord(change.config) ? change.config.authMethod : undefined; + if ( + (sent !== undefined && sent !== 'env') || + (current !== null && + isRecord(current.config) && + current.config.authMethod !== 'env') + ) { + throw new SettingsRefusalError( + 'SETTINGS_TALE_ONLY', + `${id} holds a key or a subscription entered in Tale`, + { hint: TALE_ONLY_HINT }, + ); + } + const after = parseSettingsConfig( + providerEnvironmentCredentialSchema, + change.config, + `the credential ${id}`, + ); + if (after.endpointUrl !== null) { + assertCredentialEndpointUrl(after.endpointUrl); + } + const effects: SettingsEffect[] = []; + // A new active default, or a credential that serves differently now. + const changesServing = + current === null + ? after.isDefault && after.status === 'active' + : configurationHash(servingOf(after)) !== + configurationHash(servingOf(current.config)); + if (changesServing) effects.push('changes-serving-account'); + return { + after, + unchanged: + current !== null && + configurationHash(after) === configurationHash(current.config), + effects, + }; + }, + apply: async (ctx, change, expectedHash) => { + const scope = await settingsActor(ctx); + const id = credentialIdOf(change); + const { providerSlug, name } = partsOf(id); + if (change.op === 'delete') { + await transactSerializable(ctx.sql, async (tx) => { + const row = (await listCredentials(tx, scope, providerSlug)).find( + (entry) => entry.name === name, + ); + assertExpectedHash(row?.hash ?? null, expectedHash); + if (row !== undefined) await deleteCredential(tx, scope, row.id); + }); + return { hash: null }; + } + const config = providerEnvironmentCredentialSchema.parse(change.config); + const existing = await findCredential(ctx, id); + let credentialId: string; + if (existing === null) { + credentialId = await transactSerializable(ctx.sql, (tx) => + createCredential( + tx, + scope, + { + providerSlug: config.providerSlug, + authMethod: 'env', + name: config.name, + envName: config.envName, + ...(config.endpointUrl === null + ? {} + : { endpointUrl: config.endpointUrl }), + ...(config.modelAllowlist === null + ? {} + : { modelAllowlist: config.modelAllowlist }), + status: config.status, + isDefault: config.isDefault, + }, + null, + ), + ); + } else { + credentialId = existing.id; + await transactSerializable(ctx.sql, (tx) => + updateCredential( + tx, + scope, + existing.id, + { + envName: config.envName, + endpointUrl: config.endpointUrl, + modelAllowlist: config.modelAllowlist, + status: config.status, + isDefault: config.isDefault, + }, + expectedHash ?? undefined, + ), + ); + } + // The documents and websites follow a credential the embedding model + // resolves, as they do after a save on the page. + await followEmbeddingCredential(ctx.sql, scope, credentialId); + return { hash: (await findCredential(ctx, id))?.hash ?? null }; + }, +}; From 75f84d75e0450790b2e05cd211d454788047dac4 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:26:22 +0200 Subject: [PATCH 27/35] feat(platform): change project, agent and task instructions over MCP The project-instructions, agent-instructions, agent-tools and task-instructions kinds read and change through the managed writers a declaration applied by the CLI goes through, behind each project's and task's own rules, which a plan checks before anything is written: an editor role on a project that is not archived, an agent Tale does not manage, a task the person may work on. Project and agent settings list by page over the projects the person reads; a task is read by its id. Every kind the descriptors name is now served, and the composition's type holds it so. --- .../domains/mcp/settings/handlers.test.ts | 15 + .../backend/domains/mcp/settings/handlers.ts | 22 +- .../projects/settings-resource.test.ts | 466 ++++++++++++++++++ .../domains/projects/settings-resource.ts | 364 ++++++++++++++ .../domains/tasks/settings-resource.test.ts | 183 +++++++ .../domains/tasks/settings-resource.ts | 141 ++++++ 6 files changed, 1187 insertions(+), 4 deletions(-) create mode 100644 services/platform/backend/domains/mcp/settings/handlers.test.ts create mode 100644 services/platform/backend/domains/projects/settings-resource.test.ts create mode 100644 services/platform/backend/domains/projects/settings-resource.ts create mode 100644 services/platform/backend/domains/tasks/settings-resource.test.ts create mode 100644 services/platform/backend/domains/tasks/settings-resource.ts diff --git a/services/platform/backend/domains/mcp/settings/handlers.test.ts b/services/platform/backend/domains/mcp/settings/handlers.test.ts new file mode 100644 index 0000000000..74f43fa3af --- /dev/null +++ b/services/platform/backend/domains/mcp/settings/handlers.test.ts @@ -0,0 +1,15 @@ +import { SETTINGS_KINDS } from '@tale/shared/schemas/settings-kinds'; +import { describe, expect, it } from 'vitest'; + +import { SETTINGS_HANDLERS } from './handlers.ts'; + +describe('the settings kinds this deployment serves', () => { + it('serves every kind the descriptors name, each by the handler of that kind', () => { + expect(Object.keys(SETTINGS_HANDLERS).toSorted()).toEqual( + SETTINGS_KINDS.map((descriptor) => descriptor.kind).toSorted(), + ); + for (const [kind, handler] of Object.entries(SETTINGS_HANDLERS)) { + expect(handler.kind).toBe(kind); + } + }); +}); diff --git a/services/platform/backend/domains/mcp/settings/handlers.ts b/services/platform/backend/domains/mcp/settings/handlers.ts index 1636dfe7a0..5fe54236d6 100644 --- a/services/platform/backend/domains/mcp/settings/handlers.ts +++ b/services/platform/backend/domains/mcp/settings/handlers.ts @@ -1,23 +1,37 @@ /** * The settings kinds this deployment serves over MCP: each kind's handler, * registered beside the native writer it calls (`backend/domains// - * settings-resource.ts`). A kind the shared descriptors name without a - * handler here is answered as not available on this deployment. + * settings-resource.ts`). Every kind the shared descriptors name has one — + * the type holds it, so a new kind cannot be described without its handler. */ +import type { SettingsKind } from '@tale/shared/schemas/settings-kinds'; + import { brandingSettings } from '../../branding/settings-resource.ts'; import { deploymentSettings } from '../../deployment/settings-resource.ts'; import { governanceSettings } from '../../governance/settings-resource.ts'; import { knowledgeEmbeddingSettings } from '../../knowledge/settings-resource.ts'; +import { + agentInstructionsSettings, + agentToolsSettings, + projectInstructionsSettings, +} from '../../projects/settings-resource.ts'; import { providerCredentialSettings } from '../../provider_credentials/settings-resource.ts'; import { providerSettings } from '../../providers/settings-resource.ts'; -import type { SettingsRegistry } from './registry.ts'; +import { taskInstructionsSettings } from '../../tasks/settings-resource.ts'; +import type { SettingsKindHandler } from './registry.ts'; -export const SETTINGS_HANDLERS: SettingsRegistry = { +export const SETTINGS_HANDLERS: Readonly< + Record +> = { provider: providerSettings, 'provider-credential': providerCredentialSettings, governance: governanceSettings, 'knowledge-embedding': knowledgeEmbeddingSettings, branding: brandingSettings, + 'project-instructions': projectInstructionsSettings, + 'agent-instructions': agentInstructionsSettings, + 'agent-tools': agentToolsSettings, + 'task-instructions': taskInstructionsSettings, deployment: deploymentSettings, }; diff --git a/services/platform/backend/domains/projects/settings-resource.test.ts b/services/platform/backend/domains/projects/settings-resource.test.ts new file mode 100644 index 0000000000..6315580509 --- /dev/null +++ b/services/platform/backend/domains/projects/settings-resource.test.ts @@ -0,0 +1,466 @@ +// @vitest-environment node + +/** + * A project's instructions and its agents' instructions and tools over + * MCP. The writers are the managed lane's own, held against a real schema + * by `managed-instructions.integration.ts` and `managed-tools.integration.ts`; + * here they are an in-memory store with the same hash and refusals, so + * what the kinds add — ids, listing, plan gates and compare-and-set — is + * what is tested. + */ + +import { configurationHash } from '@tale/shared/utils/configuration-hash'; +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { agents, projects } = vi.hoisted(() => ({ + projects: new Map< + string, + { instructions: string; archived: boolean; editable: boolean } + >(), + agents: new Map< + string, + { instructions: string; tools: string[]; managed: boolean } + >(), +})); + +vi.mock('@tale/shared/db/serializable', () => ({ + transactSerializable: ( + _sql: unknown, + work: (tx: unknown) => Promise, + ) => work({}), +})); +vi.mock('./service.ts', async (original) => { + const actual = await original(); + const { ConfigurationError } = + await import('../../core/lib/config_store/precondition'); + const snapshot = (config: T) => ({ + config, + hash: configurationHash(config), + }); + const projectOf = (id: string) => { + const found = projects.get(id); + if (found === undefined) { + throw new actual.ProjectError( + 'PROJECT_NOT_FOUND', + 'Project not found', + 404, + ); + } + return { id, ...found }; + }; + const agentOf = (projectId: string, agentId: string) => { + projectOf(projectId); + const found = agents.get(`${projectId}/${agentId}`); + if (found === undefined) { + throw new actual.ProjectError( + 'PROJECT_AGENT_NOT_FOUND', + 'Agent not found', + 404, + ); + } + return found; + }; + const cas = (current: unknown, expected: string) => { + if (configurationHash(current) !== expected) { + throw new ConfigurationError( + 'CONFIG_VERSION_CONFLICT', + 'Configuration changed since it was reviewed.', + ); + } + }; + return { + ...actual, + getProjectAuthContext: async ( + _sql: unknown, + member: { organizationId: string; userId: string; role: string }, + ) => ({ ...member, teamIds: [] }), + listProjects: async () => + [...projects.entries()] + .filter(([, entry]) => !entry.archived) + .map(([id]) => ({ id })), + listProjectAgents: async ( + _sql: unknown, + _auth: unknown, + projectId: string, + ) => + [...agents.keys()] + .filter((key) => key.startsWith(`${projectId}/`)) + .map((key) => ({ id: key.slice(projectId.length + 1) })), + loadProjectOrThrow: async (_sql: unknown, id: string) => projectOf(id), + assertWritable: (entry: { editable: boolean }) => { + if (!entry.editable) { + throw new actual.ProjectError( + 'RBAC_FORBIDDEN', + 'Editor role required', + 403, + ); + } + }, + assertProjectActive: (entry: { archived: boolean }) => { + if (entry.archived) { + throw new actual.ProjectError( + 'PROJECT_ARCHIVED', + 'The project is archived; restore it first.', + 409, + ); + } + }, + getProjectAgent: async ( + _sql: unknown, + _auth: unknown, + projectId: string, + agentId: string, + ) => agentOf(projectId, agentId), + readProjectInstructionsConfiguration: async ( + _sql: unknown, + _auth: unknown, + projectId: string, + ) => + snapshot({ projectId, instructions: projectOf(projectId).instructions }), + readAgentInstructionsConfiguration: async ( + _sql: unknown, + _auth: unknown, + projectId: string, + agentId: string, + ) => + snapshot({ + projectId, + agentId, + instructions: agentOf(projectId, agentId).instructions, + }), + readAgentToolsConfiguration: async ( + _sql: unknown, + _auth: unknown, + projectId: string, + agentId: string, + ) => + snapshot({ + projectId, + agentId, + tools: agentOf(projectId, agentId).tools, + }), + updateProjectInstructions: vi.fn( + async ( + _tx: unknown, + _auth: unknown, + projectId: string, + instructions: string, + expected: string, + ) => { + const entry = projectOf(projectId); + cas({ projectId, instructions: entry.instructions }, expected); + projects.set(projectId, { ...entry, instructions }); + }, + ), + updateAgentInstructionsConfiguration: vi.fn( + async ( + _tx: unknown, + _auth: unknown, + config: { projectId: string; agentId: string; instructions: string }, + expected: string, + ) => { + const entry = agentOf(config.projectId, config.agentId); + cas( + { + projectId: config.projectId, + agentId: config.agentId, + instructions: entry.instructions, + }, + expected, + ); + agents.set(`${config.projectId}/${config.agentId}`, { + ...entry, + instructions: config.instructions, + }); + }, + ), + updateAgentToolsConfiguration: vi.fn( + async ( + _tx: unknown, + _auth: unknown, + config: { projectId: string; agentId: string; tools: string[] }, + expected: string, + ) => { + const entry = agentOf(config.projectId, config.agentId); + cas( + { + projectId: config.projectId, + agentId: config.agentId, + tools: entry.tools, + }, + expected, + ); + agents.set(`${config.projectId}/${config.agentId}`, { + ...entry, + tools: config.tools, + }); + }, + ), + }; +}); + +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { updateAgentToolsConfiguration } from './service.ts'; +import { + agentInstructionsSettings, + agentToolsSettings, + projectInstructionsSettings, +} from './settings-resource.ts'; + +const registry = { + 'project-instructions': projectInstructionsSettings, + 'agent-instructions': agentInstructionsSettings, + 'agent-tools': agentToolsSettings, +}; + +function contextOf(role: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + const tag = async () => [{ email: `${role}@example.test` }]; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: tag as unknown as Sql, caller }; +} + +function project( + id: string, + fields: Partial<{ + instructions: string; + archived: boolean; + editable: boolean; + }> = {}, +) { + projects.set(id, { + instructions: '', + archived: false, + editable: true, + ...fields, + }); +} + +function agent( + key: string, + fields: Partial<{ + instructions: string; + tools: string[]; + managed: boolean; + }> = {}, +) { + agents.set(key, { instructions: '', tools: [], managed: false, ...fields }); +} + +beforeEach(() => { + projects.clear(); + agents.clear(); + vi.clearAllMocks(); +}); + +describe('who reads and changes project settings [MCP-R10]', () => { + it('lets every member read and an editor change, as the access matrix says', async () => { + expect( + await projectInstructionsSettings.access(contextOf('member')), + ).toEqual({ read: true, write: false }); + for (const role of ['editor', 'developer', 'admin']) { + expect(await agentToolsSettings.access(contextOf(role))).toEqual({ + read: true, + write: true, + }); + } + }); + + it("refuses a change the project's own rules refuse, before anything is written", async () => { + project('p-read', { editable: false }); + project('p-old', { archived: true }); + agent('p-ok/a-managed', { managed: true }); + project('p-ok'); + const plan = await planSettings(contextOf('editor'), registry, [ + { + kind: 'project-instructions', + op: 'set', + config: { projectId: 'p-read', instructions: 'Be brief.' }, + }, + { + kind: 'project-instructions', + op: 'set', + config: { projectId: 'p-old', instructions: 'Be brief.' }, + }, + { + kind: 'agent-instructions', + op: 'set', + config: { + projectId: 'p-ok', + agentId: 'a-managed', + instructions: 'Be brief.', + }, + }, + ]); + expect(plan.changes.map((change) => change.refusal?.code)).toEqual([ + 'RBAC_FORBIDDEN', + 'PROJECT_ARCHIVED', + 'PROJECT_AGENT_MANAGED', + ]); + }); +}); + +describe('reading project settings', () => { + it('pages the instructions of the projects the caller reads, archived ones aside', async () => { + for (let index = 0; index < 60; index += 1) + project(`p-${String(index).padStart(2, '0')}`); + project('p-archived', { archived: true }); + const first = await getSettings(contextOf('member'), registry, { + kinds: ['project-instructions'], + }); + expect(first.resources).toHaveLength(50); + expect(first.nextCursor).toBe('p50'); + const second = await getSettings(contextOf('member'), registry, { + kinds: ['project-instructions'], + cursor: 'p50', + }); + expect(second.resources).toHaveLength(10); + expect(second.nextCursor).toBe(null); + expect(JSON.stringify([first, second])).not.toContain('p-archived'); + }); + + it("lists every agent's tools by project and agent", async () => { + project('p-1'); + agent('p-1/a-1', { tools: ['task_find'] }); + agent('p-1/a-2'); + const answer = await getSettings(contextOf('member'), registry, { + kinds: ['agent-tools'], + }); + expect(answer.resources).toEqual([ + expect.objectContaining({ + key: 'agent-tools/p-1/a-1', + config: { projectId: 'p-1', agentId: 'a-1', tools: ['task_find'] }, + }), + expect.objectContaining({ key: 'agent-tools/p-1/a-2' }), + ]); + }); +}); + +describe('changing project settings', () => { + it('names the resource by the ids its config carries, and refuses a config another than its id', async () => { + project('p-1'); + const plan = await planSettings(contextOf('editor'), registry, [ + { + kind: 'project-instructions', + id: 'p-2', + op: 'set', + config: { projectId: 'p-1', instructions: 'Be brief.' }, + }, + { + kind: 'agent-instructions', + id: 'p-1', + op: 'set', + config: { projectId: 'p-1', agentId: 'a-1', instructions: 'x' }, + }, + { + kind: 'project-instructions', + op: 'set', + config: { projectId: 'p-1', instructions: 'Be brief.', tone: 'dry' }, + }, + ]); + expect(plan.changes.map((change) => change.refusal?.code)).toEqual([ + 'SETTINGS_ID_INVALID', + 'SETTINGS_ID_INVALID', + 'SETTINGS_INVALID', + ]); + }); + + it('applies through the managed writer, compare-and-set on the hash read', async () => { + project('p-1', { instructions: 'Old.' }); + const [read] = ( + await getSettings(contextOf('editor'), registry, { + kinds: ['project-instructions'], + ids: ['p-1'], + }) + ).resources as Array<{ hash: string }>; + const change = { + kind: 'project-instructions' as const, + op: 'set' as const, + config: { projectId: 'p-1', instructions: 'Be brief.' }, + }; + const plan = await planSettings(contextOf('editor'), registry, [change]); + expect(plan.changes[0]).toMatchObject({ + key: 'project-instructions/p-1', + action: 'update', + diff: [{ path: '/instructions', before: 'Old.', after: 'Be brief.' }], + risk: 'high', + }); + const answer = await applySettings( + contextOf('editor'), + registry, + [change], + { + 'project-instructions/p-1': read?.hash ?? null, + }, + ); + expect(answer).toMatchObject({ + applied: [ + { + action: 'update', + hash: configurationHash({ + projectId: 'p-1', + instructions: 'Be brief.', + }), + }, + ], + }); + const stale = await applySettings( + contextOf('editor'), + registry, + [{ ...change, config: { projectId: 'p-1', instructions: 'Later.' } }], + { 'project-instructions/p-1': read?.hash ?? null }, + ); + expect(stale).toMatchObject({ code: 'SETTINGS_STALE', applied: [] }); + }); + + it("grants an agent only tools the catalog has, in the catalog's order", async () => { + project('p-1'); + agent('p-1/a-1'); + const hash = configurationHash({ + projectId: 'p-1', + agentId: 'a-1', + tools: [], + }); + const refused = await planSettings(contextOf('editor'), registry, [ + { + kind: 'agent-tools', + op: 'set', + config: { projectId: 'p-1', agentId: 'a-1', tools: ['shell_exec'] }, + }, + ]); + expect(refused.changes[0]?.refusal?.code).toBe('SETTINGS_INVALID'); + await applySettings( + contextOf('editor'), + registry, + [ + { + kind: 'agent-tools', + op: 'set', + config: { + projectId: 'p-1', + agentId: 'a-1', + tools: ['task_get', 'task_find'], + }, + }, + ], + { 'agent-tools/p-1/a-1': hash }, + ); + expect(updateAgentToolsConfiguration).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ userId: 'user-editor' }), + { projectId: 'p-1', agentId: 'a-1', tools: ['task_find', 'task_get'] }, + hash, + ); + }); +}); diff --git a/services/platform/backend/domains/projects/settings-resource.ts b/services/platform/backend/domains/projects/settings-resource.ts new file mode 100644 index 0000000000..ada93e6d7c --- /dev/null +++ b/services/platform/backend/domains/projects/settings-resource.ts @@ -0,0 +1,364 @@ +import { transactSerializable } from '@tale/shared/db/serializable'; +import { + managedAgentInstructionsSchema, + managedAgentToolsSchema, + managedProjectInstructionsSchema, +} from '@tale/shared/schemas/managed-configuration'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; +import type { Sql, TransactionSql } from 'postgres'; + +import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { + callerEmail, + identityOf, + pageOf, + parseSettingsConfig, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsChange, + SettingsContext, + SettingsKindHandler, + SettingsPage, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { + assertProjectActive, + assertWritable, + getProjectAgent, + getProjectAuthContext, + listProjectAgents, + listProjects, + loadProjectOrThrow, + type ProjectAuthContext, + readAgentInstructionsConfiguration, + readAgentToolsConfiguration, + readProjectInstructionsConfiguration, + updateAgentInstructionsConfiguration, + updateAgentToolsConfiguration, + updateProjectInstructions, +} from './service.ts'; + +/** + * A project's standing instructions and its agents' instructions and tools + * as settings kinds over MCP (`project-instructions`, `agent-instructions`, + * `agent-tools`): read and changed through the writers a declaration + * applied by the CLI goes through, behind the project's own access rules — + * reading takes access to the project, changing takes its editor role on a + * project that is not archived, and an agent Tale manages changes in Tale + * alone. Each config carries the ids of what it belongs to, as a + * declaration names them. + */ + +/** Who the caller is to the projects' access rules. */ +export async function projectAuthOf( + ctx: SettingsContext, +): Promise { + return getProjectAuthContext( + ctx.sql, + { + organizationId: ctx.caller.organizationId, + userId: ctx.caller.userId, + role: ctx.caller.role, + }, + await callerEmail(ctx), + ); +} + +/** A managed read as a resource: its config always exists while what it + * belongs to does, so it always has a revision. */ +export function managedResource( + id: string, + snapshot: { config: unknown; hash: string | null }, +): SettingsResource { + if (snapshot.hash === null) { + throw new Error(`The managed setting ${id} read without a revision`); + } + return { id, config: snapshot.config, hash: snapshot.hash }; +} + +/** The ids an id joins with slashes; `count` of them, none empty. */ +export function idParts( + kind: SettingsChange['kind'], + id: string, + count: number, + form: string, +): string[] { + const parts = id.split('/'); + if (parts.length !== count || parts.some((part) => part === '')) { + throw new SettingsRefusalError( + 'SETTINGS_ID_INVALID', + `"${id}" names no ${kind}`, + { hint: `the id is ${form}` }, + ); + } + return parts; +} + +/** The id a managed config carries: its owners' ids, joined. */ +function carriedId(change: SettingsChange, fields: readonly string[]) { + if (change.op !== 'set' || !isRecord(change.config)) return undefined; + const config = change.config; + const values = fields.map((field) => config[field]); + return values.every((value) => typeof value === 'string' && value !== '') + ? values.join('/') + : undefined; +} + +/** What a role may do with projects, as the access matrix says in + * general; each project's own rules decide. */ +function projectAccess(role: string) { + const ability = defineAbilityFor(role); + return { + read: ability.can('read', 'projects'), + write: ability.can('write', 'projects'), + }; +} + +/** Refuse a change the project's own rules refuse: no editor role on it, + * or an archived project. */ +async function assertProjectEditable( + sql: Sql, + auth: ProjectAuthContext, + projectId: string, +): Promise { + const project = await loadProjectOrThrow(sql, projectId); + assertWritable(project, auth); + assertProjectActive(project); +} + +/** Refuse a change to an agent Tale manages: it changes in Tale alone. */ +async function assertAgentEditable( + sql: Sql, + auth: ProjectAuthContext, + projectId: string, + agentId: string, +): Promise { + await assertProjectEditable(sql, auth, projectId); + const agent = await getProjectAgent(sql, auth, projectId, agentId); + if (agent?.managed === true) { + throw new SettingsRefusalError( + 'PROJECT_AGENT_MANAGED', + 'Managed agent configuration is read-only', + { + status: 409, + hint: 'an agent Tale manages changes in Tale alone', + }, + ); + } +} + +interface ManagedKind { + readonly kind: 'project-instructions' | 'agent-instructions' | 'agent-tools'; + /** The config fields that name the resource, in id order. */ + readonly idFields: readonly string[]; + readonly idForm: string; + readonly what: string; + readonly schema: Parameters[0]; + read( + sql: Sql | TransactionSql, + auth: ProjectAuthContext, + parts: readonly string[], + ): Promise<{ config: unknown; hash: string | null }>; + gate( + sql: Sql, + auth: ProjectAuthContext, + parts: readonly string[], + ): Promise; + /** The native writer, given the config a plan took. */ + write( + tx: TransactionSql, + auth: ProjectAuthContext, + config: unknown, + expectedHash: string, + ): Promise; + /** Every resource of one page of the caller's projects. */ + listPage( + ctx: SettingsContext, + auth: ProjectAuthContext, + cursor: string | undefined, + ): Promise; +} + +function managedKind(spec: ManagedKind): SettingsKindHandler { + const idOf = (change: SettingsChange) => + identityOf( + spec.kind, + change.id, + carriedId(change, spec.idFields), + spec.idForm, + ); + const partsOf = (id: string) => + idParts(spec.kind, id, spec.idFields.length, spec.idForm); + const readOne = async ( + ctx: SettingsContext, + auth: ProjectAuthContext, + id: string, + ): Promise => + managedResource(id, await spec.read(ctx.sql, auth, partsOf(id))); + return { + kind: spec.kind, + access: async ({ caller }) => projectAccess(caller.role), + identify: (change) => idOf(change), + list: async (ctx, query) => { + const auth = await projectAuthOf(ctx); + if (query.ids === undefined) { + return spec.listPage(ctx, auth, query.cursor); + } + const items: SettingsResource[] = []; + for (const id of query.ids) items.push(await readOne(ctx, auth, id)); + return { items, nextCursor: null }; + }, + read: async (ctx, id) => + id === null ? null : readOne(ctx, await projectAuthOf(ctx), id), + plan: async (ctx, change, current) => { + const id = idOf(change); + const after = parseSettingsConfig(spec.schema, change.config, spec.what); + await spec.gate(ctx.sql, await projectAuthOf(ctx), partsOf(id)); + return { + after, + unchanged: + current !== null && + configurationHash(after) === configurationHash(current.config), + }; + }, + apply: async (ctx, change, expectedHash) => { + const id = idOf(change); + const auth = await projectAuthOf(ctx); + // The resource exists while what it belongs to does, so the change + // names the hash it read; the plan answered it as stale otherwise. + if (expectedHash === null) { + throw new SettingsRefusalError( + 'SETTINGS_STALE', + `${spec.kind}/${id} exists, so a change names the hash it read`, + { hint: 'read it with get_settings and apply with its hash' }, + ); + } + await transactSerializable(ctx.sql, (tx) => + spec.write(tx, auth, change.config, expectedHash), + ); + return { hash: (await readOne(ctx, auth, id)).hash }; + }, + }; +} + +/** One page of the caller's projects that are not archived, `size` at a + * time. */ +async function projectPage( + ctx: SettingsContext, + auth: ProjectAuthContext, + cursor: string | undefined, + size: number, +) { + const projects = await listProjects(ctx.sql, auth, { summary: true }); + return pageOf( + projects.map((project) => project.id), + cursor, + size, + ); +} + +/** Every agent resource of one page of the caller's projects. */ +function agentListPage(read: ManagedKind['read']): ManagedKind['listPage'] { + return async (ctx, auth, cursor) => { + const page = await projectPage(ctx, auth, cursor, 10); + const items: SettingsResource[] = []; + for (const projectId of page.items) { + for (const agent of await listProjectAgents(ctx.sql, auth, projectId)) { + items.push( + managedResource( + `${projectId}/${agent.id}`, + await read(ctx.sql, auth, [projectId, agent.id]), + ), + ); + } + } + return { items, nextCursor: page.nextCursor }; + }; +} + +const readAgentInstructions: ManagedKind['read'] = ( + sql, + auth, + [projectId, agentId], +) => + readAgentInstructionsConfiguration(sql, auth, projectId ?? '', agentId ?? ''); + +const readAgentTools: ManagedKind['read'] = (sql, auth, [projectId, agentId]) => + readAgentToolsConfiguration(sql, auth, projectId ?? '', agentId ?? ''); + +const gateAgent: ManagedKind['gate'] = (sql, auth, [projectId, agentId]) => + assertAgentEditable(sql, auth, projectId ?? '', agentId ?? ''); + +export const projectInstructionsSettings = managedKind({ + kind: 'project-instructions', + idFields: ['projectId'], + idForm: 'the project id', + what: "the project's instructions", + schema: managedProjectInstructionsSchema, + read: (sql, auth, [projectId]) => + readProjectInstructionsConfiguration(sql, auth, projectId ?? ''), + gate: (sql, auth, [projectId]) => + assertProjectEditable(sql, auth, projectId ?? ''), + write: (tx, auth, config, expectedHash) => { + const { projectId, instructions } = + managedProjectInstructionsSchema.parse(config); + return updateProjectInstructions( + tx, + auth, + projectId, + instructions, + expectedHash, + ); + }, + listPage: async (ctx, auth, cursor) => { + const page = await projectPage(ctx, auth, cursor, 50); + const items: SettingsResource[] = []; + for (const projectId of page.items) { + items.push( + managedResource( + projectId, + await readProjectInstructionsConfiguration(ctx.sql, auth, projectId), + ), + ); + } + return { items, nextCursor: page.nextCursor }; + }, +}); + +export const agentInstructionsSettings = managedKind({ + kind: 'agent-instructions', + idFields: ['projectId', 'agentId'], + idForm: '/', + what: "the agent's instructions", + schema: managedAgentInstructionsSchema, + read: readAgentInstructions, + gate: gateAgent, + write: (tx, auth, config, expectedHash) => + updateAgentInstructionsConfiguration( + tx, + auth, + managedAgentInstructionsSchema.parse(config), + expectedHash, + ), + listPage: agentListPage(readAgentInstructions), +}); + +export const agentToolsSettings = managedKind({ + kind: 'agent-tools', + idFields: ['projectId', 'agentId'], + idForm: '/', + what: "the agent's tools", + schema: managedAgentToolsSchema, + read: readAgentTools, + gate: gateAgent, + write: (tx, auth, config, expectedHash) => + updateAgentToolsConfiguration( + tx, + auth, + managedAgentToolsSchema.parse(config), + expectedHash, + ), + listPage: agentListPage(readAgentTools), +}); diff --git a/services/platform/backend/domains/tasks/settings-resource.test.ts b/services/platform/backend/domains/tasks/settings-resource.test.ts new file mode 100644 index 0000000000..ff3c7ce890 --- /dev/null +++ b/services/platform/backend/domains/tasks/settings-resource.test.ts @@ -0,0 +1,183 @@ +// @vitest-environment node + +/** + * A task's description over MCP. The writer is the managed lane's own, + * held against a real schema by `projects/managed-instructions.integration.ts`; + * here it is an in-memory task with the same hash and refusals. + */ + +import { configurationHash } from '@tale/shared/utils/configuration-hash'; +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { task } = vi.hoisted(() => ({ + task: { description: 'Draft the report.', archived: false, workable: true }, +})); + +vi.mock('@tale/shared/db/serializable', () => ({ + transactSerializable: ( + _sql: unknown, + work: (tx: unknown) => Promise, + ) => work({}), +})); +vi.mock('../projects/service.ts', async (original) => ({ + ...(await original()), + getProjectAuthContext: async ( + _sql: unknown, + member: { organizationId: string; userId: string; role: string }, + ) => ({ ...member, teamIds: [] }), + loadProjectOrThrow: async (_sql: unknown, id: string) => ({ id }), +})); +vi.mock('./service.ts', async (original) => { + const actual = await original(); + const { ConfigurationError } = + await import('../../core/lib/config_store/precondition'); + const config = () => ({ + projectId: 'p-1', + taskId: 't-1', + description: task.description, + }); + return { + ...actual, + loadTaskOrThrow: async () => ({ id: 't-1', projectId: 'p-1' }), + assertTaskWorkable: async () => { + if (!task.workable) { + throw new actual.TaskError( + 'TASK_FORBIDDEN', + 'Not allowed to work on this task', + 403, + ); + } + }, + assertTaskNotArchived: () => { + if (task.archived) { + throw new actual.TaskError( + 'TASK_ARCHIVED', + 'The task is archived.', + 409, + ); + } + }, + readTaskInstructionsConfiguration: async () => ({ + config: config(), + hash: configurationHash(config()), + }), + updateTaskInstructionsConfiguration: vi.fn( + async ( + _tx: unknown, + _auth: unknown, + next: { description: string }, + expected: string, + ) => { + if (configurationHash(config()) !== expected) { + throw new ConfigurationError( + 'CONFIG_VERSION_CONFLICT', + 'Configuration changed since it was reviewed.', + ); + } + task.description = next.description; + }, + ), + }; +}); + +import type { McpCaller } from '../mcp/caller.ts'; +import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; +import { planSettings } from '../mcp/settings/plan.ts'; +import type { SettingsContext } from '../mcp/settings/registry.ts'; +import { taskInstructionsSettings } from './settings-resource.ts'; + +const registry = { 'task-instructions': taskInstructionsSettings }; + +function contextOf(role: string): SettingsContext { + const caller: McpCaller = { + organizationId: 'org-1', + orgSlug: 'acme', + userId: `user-${role}`, + role, + credential: { kind: 'api-key', apiKeyId: 'key-laptop' }, + }; + const tag = async () => [{ email: `${role}@example.test` }]; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double + return { sql: tag as unknown as Sql, caller }; +} + +const change = (description: string) => ({ + kind: 'task-instructions' as const, + op: 'set' as const, + config: { projectId: 'p-1', taskId: 't-1', description }, +}); + +beforeEach(() => { + Object.assign(task, { + description: 'Draft the report.', + archived: false, + workable: true, + }); +}); + +describe("a task's description over MCP", () => { + it('reads the tasks a call names, and asks for ids rather than reading every task', async () => { + const all = await getSettings(contextOf('member'), registry, { + kinds: ['task-instructions'], + }); + expect(all.refused).toEqual([ + expect.objectContaining({ + code: 'SETTINGS_IDS_REQUIRED', + hint: expect.stringContaining('/'), + }), + ]); + const named = await getSettings(contextOf('member'), registry, { + kinds: ['task-instructions'], + ids: ['p-1/t-1'], + }); + expect(named.resources).toEqual([ + expect.objectContaining({ + key: 'task-instructions/p-1/t-1', + config: { + projectId: 'p-1', + taskId: 't-1', + description: 'Draft the report.', + }, + }), + ]); + }); + + it("refuses what the task's own rules refuse, before anything is written [MCP-R10]", async () => { + task.archived = true; + const archived = await planSettings(contextOf('member'), registry, [ + change('Draft it by Friday.'), + ]); + expect(archived.changes[0]?.refusal?.code).toBe('TASK_ARCHIVED'); + task.archived = false; + task.workable = false; + const forbidden = await planSettings(contextOf('member'), registry, [ + change('Draft it by Friday.'), + ]); + expect(forbidden.changes[0]?.refusal?.code).toBe('TASK_FORBIDDEN'); + }); + + it('changes the description through the managed writer, only as it was read', async () => { + const read = configurationHash({ + projectId: 'p-1', + taskId: 't-1', + description: 'Draft the report.', + }); + const applied = await applySettings( + contextOf('member'), + registry, + [change('Draft it by Friday.')], + { 'task-instructions/p-1/t-1': read }, + ); + expect(applied).toMatchObject({ applied: [{ action: 'update' }] }); + expect(task.description).toBe('Draft it by Friday.'); + const stale = await applySettings( + contextOf('member'), + registry, + [change('Draft it by Monday.')], + { 'task-instructions/p-1/t-1': read }, + ); + expect(stale).toMatchObject({ code: 'SETTINGS_STALE' }); + }); +}); diff --git a/services/platform/backend/domains/tasks/settings-resource.ts b/services/platform/backend/domains/tasks/settings-resource.ts new file mode 100644 index 0000000000..916dcdc1f0 --- /dev/null +++ b/services/platform/backend/domains/tasks/settings-resource.ts @@ -0,0 +1,141 @@ +import { transactSerializable } from '@tale/shared/db/serializable'; +import { managedTaskInstructionsSchema } from '@tale/shared/schemas/managed-configuration'; +import { configurationHash } from '@tale/shared/utils/configuration-hash'; + +import { defineAbilityFor } from '../../../lib/permissions/ability.ts'; +import { isRecord } from '../../../lib/utils/type-utils.ts'; +import { + identityOf, + parseSettingsConfig, + SettingsRefusalError, +} from '../mcp/settings/kit.ts'; +import type { + SettingsChange, + SettingsContext, + SettingsKindHandler, + SettingsResource, +} from '../mcp/settings/registry.ts'; +import { loadProjectOrThrow } from '../projects/service.ts'; +import { + idParts, + managedResource, + projectAuthOf, +} from '../projects/settings-resource.ts'; +import { + assertTaskNotArchived, + assertTaskWorkable, + loadTaskOrThrow, + readTaskInstructionsConfiguration, + updateTaskInstructionsConfiguration, +} from './service.ts'; + +/** + * A task's description as a settings kind over MCP (`task-instructions`): + * read and changed through the writer a declaration applied by the CLI + * goes through, behind the task's own rules — changing takes someone who + * may work on the task, which is not archived, and a person it mentions + * must be someone who can be mentioned on it. A project holds many tasks, + * so a read names the tasks it wants. + */ + +const ID_FORM = '/'; + +function taskIdOf(change: SettingsChange): string { + const config = + change.op === 'set' && isRecord(change.config) ? change.config : null; + const carried = + typeof config?.projectId === 'string' && typeof config.taskId === 'string' + ? `${config.projectId}/${config.taskId}` + : undefined; + return identityOf('task-instructions', change.id, carried, ID_FORM); +} + +async function readTask( + ctx: SettingsContext, + id: string, +): Promise { + const [projectId = '', taskId = ''] = idParts( + 'task-instructions', + id, + 2, + ID_FORM, + ); + return managedResource( + id, + await readTaskInstructionsConfiguration( + ctx.sql, + await projectAuthOf(ctx), + projectId, + taskId, + ), + ); +} + +export const taskInstructionsSettings: SettingsKindHandler = { + kind: 'task-instructions', + access: async ({ caller }) => { + // Whoever reads a project may work on its tasks; each task's own + // rules decide. + const allowed = defineAbilityFor(caller.role).can('read', 'projects'); + return { read: allowed, write: allowed }; + }, + identify: (change) => taskIdOf(change), + list: async (ctx, query) => { + if (query.ids === undefined) { + throw new SettingsRefusalError( + 'SETTINGS_IDS_REQUIRED', + 'task-instructions reads the tasks a call names, not every task', + { + hint: `name each task in ids as ${ID_FORM}, from its link in Tale`, + }, + ); + } + const items: SettingsResource[] = []; + for (const id of query.ids) items.push(await readTask(ctx, id)); + return { items, nextCursor: null }; + }, + read: async (ctx, id) => (id === null ? null : readTask(ctx, id)), + plan: async (ctx, change, current) => { + const id = taskIdOf(change); + const after = parseSettingsConfig( + managedTaskInstructionsSchema, + change.config, + "the task's description", + ); + const [projectId = '', taskId = ''] = idParts( + 'task-instructions', + id, + 2, + ID_FORM, + ); + const auth = await projectAuthOf(ctx); + const task = await loadTaskOrThrow(ctx.sql, taskId, auth.organizationId); + const project = await loadProjectOrThrow(ctx.sql, projectId); + await assertTaskWorkable(ctx.sql, project, task, auth); + assertTaskNotArchived(task); + return { + after, + unchanged: + current !== null && + configurationHash(after) === configurationHash(current.config), + }; + }, + apply: async (ctx, change, expectedHash) => { + const id = taskIdOf(change); + // The task exists while it does, so the change names the hash it read; + // the plan answered it as stale otherwise. + if (expectedHash === null) { + throw new SettingsRefusalError( + 'SETTINGS_STALE', + `task-instructions/${id} exists, so a change names the hash it read`, + { hint: 'read it with get_settings and apply with its hash' }, + ); + } + const auth = await projectAuthOf(ctx); + const config = managedTaskInstructionsSchema.parse(change.config); + await transactSerializable(ctx.sql, (tx) => + updateTaskInstructionsConfiguration(tx, auth, config, expectedHash), + ); + return { hash: (await readTask(ctx, id)).hash }; + }, +}; From 2515f3caea2d2182f79ab6eca968782c53ab2983 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:31:16 +0200 Subject: [PATCH 28/35] test(platform): hold settings over MCP end to end checkMcpSettingsConfig drives the MCP door against a real database in an organization of its own: every kind is served, the catalog says what each role may do, and an owner's agent changes a policy, the branding, a provider, its environment credential, the embedding model and a project's instructions, each leaving its page's audit row stamped as coming through apply_settings, while a member's agent and a stale read are refused. A credential pasted into a stored policy never leaves a read through a real kind and survives its masked round trip. MCP-R14 names a setting changed among the writes it audits; the spec's Not yet now lists the pages no kind covers. --- .../governance/settings-resource.test.ts | 42 ++ .../domains/mcp/settings.integration.ts | 387 ++++++++++++++++++ services/platform/backend/domains/mcp/spec.md | 16 +- .../platform/backend/integration-check.ts | 8 + 4 files changed, 447 insertions(+), 6 deletions(-) create mode 100644 services/platform/backend/domains/mcp/settings.integration.ts diff --git a/services/platform/backend/domains/governance/settings-resource.test.ts b/services/platform/backend/domains/governance/settings-resource.test.ts index 01285921cc..dd387dced2 100644 --- a/services/platform/backend/domains/governance/settings-resource.test.ts +++ b/services/platform/backend/domains/governance/settings-resource.test.ts @@ -56,6 +56,7 @@ vi.mock('../sandbox/unused-rule.ts', () => ({ import { ConfigurationError } from '../../core/lib/config_store/precondition'; import type { McpCaller } from '../mcp/caller.ts'; import { applySettings } from '../mcp/settings/apply.ts'; +import { getSettings } from '../mcp/settings/get.ts'; import { planSettings } from '../mcp/settings/plan.ts'; import type { SettingsContext } from '../mcp/settings/registry.ts'; import { governanceEffects, governanceSettings } from './settings-resource.ts'; @@ -414,6 +415,47 @@ describe('applying a policy change', () => { }); }); +describe('a credential someone pasted into a policy in Tale [MCP-R12]', () => { + const PASTED = 'sk-000000000000000000000000'; + + it('never leaves in a read, and stays as written when its mask comes back', async () => { + stored.set('system_prompt', { + enabled: true, + mandatoryInstructions: `Use the key ${PASTED} for the CRM.`, + }); + const answer = await getSettings(contextOf('admin'), registry, { + kinds: ['governance'], + ids: ['system_prompt'], + }); + expect(JSON.stringify(answer)).not.toContain(PASTED); + const [read] = answer.resources as Array<{ + config: Record; + hash: string; + }>; + expect(read?.config.mandatoryInstructions).toMatchObject({ masked: true }); + + const sent = { ...read?.config, enabled: false }; + const plan = await planSettings(contextOf('admin'), registry, [ + { kind: 'governance', id: 'system_prompt', op: 'set', config: sent }, + ]); + expect(JSON.stringify(plan)).not.toContain(PASTED); + expect(plan.changes[0]).toMatchObject({ + action: 'update', + diff: [{ path: '/enabled', before: true, after: false }], + }); + await applySettings( + contextOf('admin'), + registry, + [{ kind: 'governance', id: 'system_prompt', op: 'set', config: sent }], + { 'governance/system_prompt': read?.hash ?? null }, + ); + expect(stored.get('system_prompt')).toEqual({ + enabled: false, + mandatoryInstructions: `Use the key ${PASTED} for the CRM.`, + }); + }); +}); + describe('what a policy change does', () => { it('names a lockout, a sign-out or a removed approval only where one happens', () => { expect(governanceEffects('login_policy', null, { enabled: true })).toEqual([ diff --git a/services/platform/backend/domains/mcp/settings.integration.ts b/services/platform/backend/domains/mcp/settings.integration.ts new file mode 100644 index 0000000000..230c18046b --- /dev/null +++ b/services/platform/backend/domains/mcp/settings.integration.ts @@ -0,0 +1,387 @@ +/** + * Settings over MCP against a real database and a real server: every kind + * is served, an owner's agent changes the organization's policies, + * branding, providers, credentials, embedding model and project + * instructions through the MCP door, each change leaves the audit row its + * Settings page leaves, stamped as coming through MCP, and a member's + * agent is refused what a member is refused in the app. The lane works in + * an organization of its own, so nothing it changes reaches another lane. + */ + +import { randomUUID } from 'node:crypto'; + +import type { Sql } from 'postgres'; +import { z } from 'zod'; + +import { + type RecordCheck, + signUpUser, +} from '../../integration-lane-helpers.ts'; + +const answerSchema = z.object({ + result: z.object({ + content: z.array(z.object({ text: z.string() })).min(1), + isError: z.boolean(), + }), +}); + +interface ToolAnswer { + readonly isError: boolean; + readonly value: Record; + readonly raw: string; +} + +export async function checkMcpSettingsConfig( + sql: Sql, + base: string, + record: RecordCheck, +): Promise { + const headers = { 'content-type': 'application/json', origin: base }; + const owner = await signUpUser(base, 'mcp-settings'); + const created = z.object({ id: z.string(), slug: z.string() }).safeParse( + await ( + await fetch(`${base}/api/auth/organization/create`, { + method: 'POST', + headers: { ...headers, cookie: owner.cookie }, + body: JSON.stringify({ + name: 'MCP settings', + slug: `mcp-settings-${randomUUID().slice(0, 8)}`, + }), + }) + ).json(), + ); + if (!created.success) { + record( + 'MCP settings: the lane has an organization of its own', + false, + created.error.message, + ); + return; + } + const org = created.data; + const mint = async (cookie: string, name: string): Promise => { + const minted = z.looseObject({ key: z.string() }).safeParse( + await ( + await fetch(`${base}/api/auth/api-key/create`, { + method: 'POST', + headers: { ...headers, cookie }, + body: JSON.stringify({ name }), + }) + ).json(), + ); + return minted.success ? minted.data.key : ''; + }; + const ownerKey = await mint(owner.cookie, 'itest-mcp-settings'); + // A member's key, made the way one arises: minted while a developer, + // used once the person is a member. + const member = await signUpUser(base, 'mcp-settings-member'); + await sql` + INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") + VALUES (gen_random_uuid(), ${org.id}, ${member.userId}, 'developer', + ${new Date()}) + `; + const memberKey = await mint(member.cookie, 'itest-mcp-settings-member'); + await sql` + UPDATE "member" SET "role" = 'member' + WHERE "organizationId" = ${org.id} AND "userId" = ${member.userId} + `; + + let rpcId = 7000; + const tool = async ( + name: string, + args: Record, + key = ownerKey, + ): Promise => { + rpcId += 1; + const res = await fetch(`${base}/api/v1/mcp`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${key}`, + 'x-organization-slug': org.slug, + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: rpcId, + method: 'tools/call', + params: { name, arguments: args }, + }), + }); + const raw = await res.text(); + const parsed = answerSchema.safeParse(JSON.parse(raw)); + if (!parsed.success) return { isError: true, value: {}, raw }; + const value = z + .record(z.string(), z.unknown()) + .safeParse(JSON.parse(parsed.data.result.content[0]?.text ?? '{}')); + return { + isError: parsed.data.result.isError, + value: value.success ? value.data : {}, + raw, + }; + }; + /** A resource as get_settings reads it: its hash and config, or null + * when there is none. */ + const readOf = async ( + kind: string, + id?: string, + ): Promise<{ hash: string; config: unknown } | null> => { + const read = await tool('get_settings', { + kinds: [kind], + ...(id === undefined ? {} : { ids: [id] }), + }); + const resources = z + .array(z.object({ hash: z.string(), config: z.unknown() }).loose()) + .safeParse(read.value.resources); + return resources.success ? (resources.data[0] ?? null) : null; + }; + const hashOf = async (kind: string, id?: string): Promise => + (await readOf(kind, id))?.hash ?? null; + /** Apply one change, naming the hash it expects. */ + const apply = async ( + change: Record, + key: string, + expected: string | null, + as = ownerKey, + ) => + tool( + 'apply_settings', + { changes: [change], expected: { [key]: expected } }, + as, + ); + /** Whether the latest audit row of an action on a resource came through + * the settings tool. */ + const auditedViaMcp = async ( + action: string, + where: { resourceId?: string; resourceName?: string }, + ): Promise => { + const rows = await sql<{ via: string | null; tool: string | null }[]>` + SELECT metadata->>'via' AS via, metadata->>'tool' AS tool + FROM app.audit_logs + WHERE org_id = ${org.id} AND action = ${action} + AND (${where.resourceId ?? null}::text IS NULL + OR resource_id = ${where.resourceId ?? null}) + AND (${where.resourceName ?? null}::text IS NULL + OR resource_name = ${where.resourceName ?? null}) + ORDER BY ts DESC + LIMIT 1 + `; + return rows[0]?.via === 'mcp' && rows[0]?.tool === 'apply_settings'; + }; + + // The catalog: every kind served, and what each role may do. + const ownerCatalog = await tool('get_settings', {}); + const memberCatalog = await tool('get_settings', {}, memberKey); + const kinds = z.array( + z + .object({ + kind: z.string(), + available: z.boolean(), + read: z.boolean(), + write: z.boolean(), + }) + .loose(), + ); + const ownerKinds = kinds.safeParse(ownerCatalog.value.kinds); + const memberKinds = kinds.safeParse(memberCatalog.value.kinds); + const access = (parsed: typeof ownerKinds, kind: string): string => + parsed.success + ? JSON.stringify( + parsed.data + .filter((entry) => entry.kind === kind) + .map((entry) => [entry.read, entry.write]), + ) + : 'unread'; + record( + 'MCP get_settings serves every kind, and says what the role may do with each (MCP-R10)', + ownerKinds.success && + ownerKinds.data.length === 10 && + ownerKinds.data.every((entry) => entry.available) && + access(ownerKinds, 'governance') === '[[true,true]]' && + access(memberKinds, 'governance') === '[[true,false]]' && + access(memberKinds, 'branding') === '[[false,false]]', + `owner=${ownerKinds.success ? ownerKinds.data.length : 'unread'} kinds, member governance=${access(memberKinds, 'governance')}, member branding=${access(memberKinds, 'branding')}`, + ); + + // A policy: the owner's agent changes it, a member's is refused, and a + // change from an old read is stale. + // Whatever a new organization starts with, the change flips it. + const flagsRead = await readOf('governance', 'feature_flags'); + const flagsBefore = flagsRead?.hash ?? null; + const enabledBefore = z + .object({ enabled: z.boolean() }) + .loose() + .safeParse(flagsRead?.config).data?.enabled; + const flags = { + kind: 'governance', + id: 'feature_flags', + op: 'set', + config: { rules: [], enabled: enabledBefore !== true }, + }; + const flagsApplied = await apply( + flags, + 'governance/feature_flags', + flagsBefore, + ); + const flagsAfter = await hashOf('governance', 'feature_flags'); + const memberFlags = await apply( + { ...flags, config: { rules: [], enabled: enabledBefore === true } }, + 'governance/feature_flags', + flagsAfter, + memberKey, + ); + const staleFlags = await apply( + { ...flags, config: { rules: [], enabled: enabledBefore === true } }, + 'governance/feature_flags', + flagsBefore, + ); + record( + "MCP apply_settings changes a policy through its writer, refuses a member's agent and a stale read (MCP-R10, MCP-R11, MCP-R14)", + !flagsApplied.isError && + (await auditedViaMcp( + flagsBefore === null + ? 'governance_policy.created' + : 'governance_policy.updated', + { resourceId: 'feature_flags' }, + )) && + memberFlags.isError && + memberFlags.value.code === 'FORBIDDEN' && + (await hashOf('governance', 'feature_flags')) === flagsAfter && + staleFlags.isError && + staleFlags.value.code === 'SETTINGS_STALE' && + z.object({ currentHash: z.string() }).safeParse(staleFlags.value.data) + .data?.currentHash === flagsAfter, + `applied=${flagsApplied.raw.slice(0, 160)}, member=${String(memberFlags.value.code)}, stale=${String(staleFlags.value.code)}`, + ); + + // The branding. + const accentColor = `#${randomUUID().replaceAll('-', '').slice(0, 6)}`; + const branding = await apply( + { kind: 'branding', op: 'set', config: { accentColor } }, + 'branding', + await hashOf('branding'), + ); + record( + 'MCP apply_settings changes the branding through its writer, audited as coming through MCP (MCP-R14)', + !branding.isError && + (await auditedViaMcp('branding.updated', { resourceId: org.id })), + branding.raw.slice(0, 200), + ); + + // A provider of the organization's own, a credential for it read from + // the environment, and an embedding model on it — the knowledge base is + // empty, so the model may be set. + const providerName = 'itest-mcp-settings'; + const provider = await apply( + { + kind: 'provider', + op: 'set', + config: { + name: providerName, + displayName: 'Itest MCP settings', + apiFormat: 'openai', + baseUrl: 'https://models.example.test/v1', + catalog: { source: 'models-endpoint' }, + embedding: 'unknown', + auth: [{ method: 'env' }], + }, + }, + `provider/${providerName}`, + null, + ); + const credentialId = `${providerName}/Itest%20key`; + const credential = await apply( + { + kind: 'provider-credential', + op: 'set', + config: { + providerSlug: providerName, + authMethod: 'env', + name: 'Itest key', + envName: 'TALE_PROVIDER_KEY_ITEST_MCP_SETTINGS', + endpointUrl: null, + modelAllowlist: null, + status: 'active', + isDefault: true, + }, + }, + `provider-credential/${credentialId}`, + null, + ); + const embedding = await apply( + { + kind: 'knowledge-embedding', + op: 'set', + config: { + providerSlug: providerName, + model: 'itest-embedding', + dimensions: 256, + }, + }, + 'knowledge-embedding', + await hashOf('knowledge-embedding'), + ); + const credentialInUse = await tool('plan_settings', { + changes: [{ kind: 'provider-credential', id: credentialId, op: 'delete' }], + }); + const plannedRefusal = z + .array( + z.object({ refusal: z.object({ code: z.string() }).loose() }).loose(), + ) + .safeParse(credentialInUse.value.changes); + record( + 'MCP apply_settings defines a provider, its environment credential and the embedding model through their writers, each audited as coming through MCP (MCP-R14, MCP-R28)', + !provider.isError && + (await auditedViaMcp('provider_definition.saved', { + resourceId: providerName, + })) && + !credential.isError && + (await auditedViaMcp('provider_credential.created', { + resourceName: 'Itest key', + })) && + !embedding.isError && + (await auditedViaMcp('knowledge_embedding.saved', { + resourceId: 'embedding', + })) && + plannedRefusal.success && + plannedRefusal.data[0]?.refusal.code === 'CREDENTIAL_IN_USE', + `provider=${provider.raw.slice(0, 120)}, credential=${credential.raw.slice(0, 120)}, embedding=${embedding.raw.slice(0, 120)}, delete=${credentialInUse.raw.slice(0, 120)}`, + ); + + // A project's instructions. + const now = Date.now(); + const projects = await sql<{ id: string }[]>` + INSERT INTO app.projects (org_id, name, created_by, created_at_ms, + updated_at_ms) + VALUES (${org.id}, 'MCP settings project', ${owner.userId}, ${now}, ${now}) + RETURNING id + `; + const projectId = projects[0]?.id ?? ''; + const instructions = await apply( + { + kind: 'project-instructions', + op: 'set', + config: { projectId, instructions: 'Answer in one paragraph.' }, + }, + `project-instructions/${projectId}`, + await hashOf('project-instructions', projectId), + ); + const memberInstructions = await apply( + { + kind: 'project-instructions', + op: 'set', + config: { projectId, instructions: 'Answer at length.' }, + }, + `project-instructions/${projectId}`, + await hashOf('project-instructions', projectId), + memberKey, + ); + record( + "MCP apply_settings changes a project's instructions through the managed writer, and refuses a member who may not edit the project (MCP-R10, MCP-R14)", + !instructions.isError && + (await auditedViaMcp('project.instructions.changed', { + resourceId: projectId, + })) && + memberInstructions.isError, + `owner=${instructions.raw.slice(0, 160)}, member=${String(memberInstructions.value.code)}`, + ); +} diff --git a/services/platform/backend/domains/mcp/spec.md b/services/platform/backend/domains/mcp/spec.md index ce9f536b60..7fd38a3fb7 100644 --- a/services/platform/backend/domains/mcp/spec.md +++ b/services/platform/backend/domains/mcp/spec.md @@ -338,9 +338,11 @@ counts twice, once in each. Counters are kept 90 days, and an erasure of the per ### MCP-R14 · Every write over MCP leaves an audit row naming the coding agent A write a tool call makes — a version saved, a deploy, a delete, a trigger set or removed, an -installation added or removed, a run stopped, a question answered — leaves its audit row (`AUTO-R28`), -and every row written during the call says it came through MCP, with the tool, the API key and the -client's name when the client named itself on that call (every call on 2026-07-28; see Not yet). +installation added or removed, a run stopped, a question answered, a setting changed — leaves its +audit row (`AUTO-R28`; for a setting, the row the same change leaves when it is made on its +Settings page), and every row written during the call says it came through MCP, with the tool, the +API key and the client's name when the client named itself on that call (every call on 2026-07-28; +see Not yet). - **Example**: Ada's agent deploys v7 with her key "laptop" → the audit log shows "Automation deployed" by Ada, through MCP (`deploy_automation`, her laptop key). @@ -420,9 +422,11 @@ deployment of a release. A signed-in person downloads it in the app; an agent re a version its agent saves records the door and the key but no client name; a 2026-07-28 client names itself on every call (MCP-R26). - The tool inventory and each tool's arguments (`lib/mcp/tools.ts`, `lib/mcp/args.ts`). -- A kind of setting is served over MCP once its handler sits beside the code that writes it in - the app; until then the catalog lists it as unavailable, and a change to it is refused - (`SETTINGS_KIND_UNAVAILABLE`). +- Settings pages no kind covers yet — members, teams, connectors, skills, competences, legal + holds, data subject requests, the audit log, metrics and a person's own settings among them — + are listed with what an agent cannot do there (`settings/coverage.ts`); those changes are made + in Tale. A secret is always entered in Tale: no change request carries an agent's change there + for the person to finish yet. - A client cannot subscribe to a resource or be told that a list changed (`subscriptions/listen` answers 404 on 2026-07-28): the lists are read again when a client reconnects, or on 2026-07-28 once the time the answer named has passed. diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts index 8bde0f9375..94fe869da4 100644 --- a/services/platform/backend/integration-check.ts +++ b/services/platform/backend/integration-check.ts @@ -64076,6 +64076,14 @@ async function main(): Promise { 'checkMcpEras', () => checkMcpEras(sql, baseUrl, authCtx, `itest-${orgSuffix}`), ], + [ + 'checkMcpSettingsConfig', + async () => { + const { checkMcpSettingsConfig } = + await import('./domains/mcp/settings.integration.ts'); + await checkMcpSettingsConfig(sql, baseUrl, record); + }, + ], [ 'checkRetiredBuilderRoute', () => checkRetiredBuilderRoute(baseUrl, authCtx), From 4f5c6e0353649abedee836e51503fca7c25f03d3 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 00:39:38 +0200 Subject: [PATCH 29/35] feat(platform): teach settings over MCP in the references and the skill get_docs takes the topic settings (also tale://docs/settings): how a change is read, planned and applied, every kind with its config's fields from the schema its writer checks, every governance policy, what each effect of a plan means and every refusal, held to the codes the handlers raise. The server instructions point at it, and the Tale skill gains a Settings section, its refusal rows and the rule to ask before apply_settings. The settings contract moves to 3.30.0, the next minor free across the open branches, with the fingerprints and snapshots. --- .../platform/backend/domains/mcp/docs.test.ts | 2 +- services/platform/backend/domains/mcp/docs.ts | 3 + services/platform/lib/mcp/args.ts | 2 +- .../lib/mcp/contract-fingerprint.json | 4 +- .../platform/lib/mcp/docs/settings.test.ts | 100 +++++++ services/platform/lib/mcp/docs/settings.ts | 279 ++++++++++++++++++ services/platform/lib/mcp/docs/topics.ts | 1 + services/platform/lib/mcp/instructions.ts | 4 +- services/platform/lib/mcp/resources.test.ts | 2 +- services/platform/lib/mcp/resources.ts | 5 + services/platform/lib/mcp/skill.snapshot.md | 18 +- services/platform/lib/mcp/skill.test.ts | 3 + services/platform/lib/mcp/skill.ts | 55 +++- .../lib/mcp/tools.schema.snapshot.json | 4 +- .../lib/shared/constants/api-contract.ts | 15 +- services/platform/public/openapi.json | 4 +- .../scripts/openapi/contract-fingerprint.json | 2 +- .../tests/manual/reference/automation.md | 2 +- 18 files changed, 485 insertions(+), 20 deletions(-) create mode 100644 services/platform/lib/mcp/docs/settings.test.ts create mode 100644 services/platform/lib/mcp/docs/settings.ts diff --git a/services/platform/backend/domains/mcp/docs.test.ts b/services/platform/backend/domains/mcp/docs.test.ts index 4423034028..907d4b17ba 100644 --- a/services/platform/backend/domains/mcp/docs.test.ts +++ b/services/platform/backend/domains/mcp/docs.test.ts @@ -16,7 +16,7 @@ describe('the references get_docs serves beside the authoring one', () => { expect(mcpDocs(topic)?.length ?? 0, topic).toBeGreaterThan(0); } } - expect(mcpDocs('settings')).toBeUndefined(); + expect(mcpDocs('billing')).toBeUndefined(); }); it('states the trigger delivery rules the backend enforces', () => { diff --git a/services/platform/backend/domains/mcp/docs.ts b/services/platform/backend/domains/mcp/docs.ts index 1be2cdaeee..359084bb2b 100644 --- a/services/platform/backend/domains/mcp/docs.ts +++ b/services/platform/backend/domains/mcp/docs.ts @@ -5,6 +5,7 @@ * in `lib/mcp/docs/` cannot import. */ +import { settingsReference } from '../../../lib/mcp/docs/settings.ts'; import { triggersReference } from '../../../lib/mcp/docs/triggers.ts'; import { validationReference } from '../../../lib/mcp/docs/validation.ts'; import { buildTaleSkill } from '../../../lib/mcp/skill.ts'; @@ -37,6 +38,8 @@ export function mcpDocs(topic: string): string | undefined { return triggersReference(TRIGGER_FACTS); case 'validation': return validationReference(); + case 'settings': + return settingsReference(); case 'skill': return buildTaleSkill(); default: diff --git a/services/platform/lib/mcp/args.ts b/services/platform/lib/mcp/args.ts index 1d3f4d00a6..59f2e56e7d 100644 --- a/services/platform/lib/mcp/args.ts +++ b/services/platform/lib/mcp/args.ts @@ -187,7 +187,7 @@ export const ENGINE_TOOL_ARGS = { .enum(MCP_DOC_TOPICS) .optional() .describe( - 'Which reference: "authoring" (the default — the automation grammar and every method), "triggers" (what starts an automation, each kind\'s fields and the events), "validation" (how to read a validation result, and every issue code) or "skill" (the Tale skill, SKILL.md). Each is also the resource tale://docs/.', + 'Which reference: "authoring" (the default — the automation grammar and every method), "triggers" (what starts an automation, each kind\'s fields and the events), "validation" (how to read a validation result, and every issue code), "settings" (every kind of setting with its fields, the effects of a plan and every refusal) or "skill" (the Tale skill, SKILL.md). Each is also the resource tale://docs/.', ), }), get_catalog: z.strictObject({ diff --git a/services/platform/lib/mcp/contract-fingerprint.json b/services/platform/lib/mcp/contract-fingerprint.json index d931030adf..61d44510c7 100644 --- a/services/platform/lib/mcp/contract-fingerprint.json +++ b/services/platform/lib/mcp/contract-fingerprint.json @@ -1,4 +1,4 @@ { - "version": "3.28.0", - "fingerprint": "5f86c9e9e8038d4272206f3808bea5471a9f8be1f4d6ebfcc825be6e639b02e0" + "version": "3.30.0", + "fingerprint": "97040ba77bae43bd454640e8e3ed8cf838bc26702204433d37d1502c8fd36ae7" } diff --git a/services/platform/lib/mcp/docs/settings.test.ts b/services/platform/lib/mcp/docs/settings.test.ts new file mode 100644 index 0000000000..1ab81b54a9 --- /dev/null +++ b/services/platform/lib/mcp/docs/settings.test.ts @@ -0,0 +1,100 @@ +// @vitest-environment node + +import { readdirSync, readFileSync } from 'node:fs'; + +import { FILE_POLICY_TYPES } from '@tale/shared/schemas/governance'; +import { + GOVERNANCE_KEYS_NOT_OVER_MCP, + SETTINGS_EFFECTS, + SETTINGS_KINDS, +} from '@tale/shared/schemas/settings-kinds'; +import { describe, expect, test } from 'vitest'; + +import { MCP_TOOLS } from '../tools'; +import { settingsReference } from './settings'; + +const text = settingsReference(); + +/** Every source a settings refusal is raised in: the settings tools and + * each kind's handler beside its writer. */ +function settingsSources(): string { + const domains = new URL('../../../backend/domains/', import.meta.url); + const handlers = readdirSync(domains, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => new URL(`${entry.name}/settings-resource.ts`, domains)) + .flatMap((file) => { + try { + return [readFileSync(file, 'utf8')]; + } catch (error) { + if (Reflect.get(Object(error), 'code') === 'ENOENT') return []; + throw error; + } + }); + const tools = readdirSync(new URL('mcp/settings/', domains)) + .filter((name) => name.endsWith('.ts') && !name.endsWith('.test.ts')) + .map((name) => + readFileSync(new URL(`mcp/settings/${name}`, domains), 'utf8'), + ); + return [...handlers, ...tools].join('\n'); +} + +describe('the settings reference', () => { + test('describes every kind, in apply order, with its config', () => { + const headings = [...text.matchAll(/^### (\S+)$/gm)].map( + (match) => match[1], + ); + expect(headings).toEqual(SETTINGS_KINDS.map((entry) => entry.kind)); + expect(text.match(/^```json$/gm)?.length ?? 0).toBeGreaterThanOrEqual( + SETTINGS_KINDS.length, + ); + }); + + test('names every policy the governance kind takes, and why the others are not', () => { + for (const key of FILE_POLICY_TYPES) { + if (Object.hasOwn(GOVERNANCE_KEYS_NOT_OVER_MCP, key)) { + expect(text, key).toContain(`- \`${key}\` `); + } else { + expect(text, key).toContain(`- \`${key}\`\n`); + } + } + }); + + test('says what every effect of a plan means, with its risk', () => { + for (const [effect, risk] of Object.entries(SETTINGS_EFFECTS)) { + expect(text).toContain(`| ${effect} | ${risk} |`); + } + }); + + test('lists every refusal a settings handler raises, and only codes one does', () => { + const sources = settingsSources(); + const raised = new Set( + [ + ...sources.matchAll( + /(?:SettingsRefusalError|ConfigurationError)\(\s*'([A-Z][A-Z0-9_]+)'/g, + ), + ].map((match) => match[1] ?? ''), + ); + const listed = [...text.matchAll(/^\| ([A-Z][A-Z0-9_]+) \|/gm)].map( + (match) => match[1] ?? '', + ); + // CONFIG_VERSION_CONFLICT is how a writer says stale; the tools answer + // it as SETTINGS_STALE. + raised.delete('CONFIG_VERSION_CONFLICT'); + for (const code of raised) expect(listed, code).toContain(code); + for (const code of listed) { + expect( + sources.includes(`'${code}'`) || + ['FORBIDDEN', 'RATE_LIMITED', 'INTERNAL_ERROR'].includes(code), + code, + ).toBe(true); + } + }); + + test('fits what get_docs answers', () => { + const cap = MCP_TOOLS.find( + (tool) => tool.name === 'get_docs', + )?.maxResultChars; + expect(cap).toBeDefined(); + expect(text.length).toBeLessThan(cap ?? 0); + }); +}); diff --git a/services/platform/lib/mcp/docs/settings.ts b/services/platform/lib/mcp/docs/settings.ts new file mode 100644 index 0000000000..e5a6631def --- /dev/null +++ b/services/platform/lib/mcp/docs/settings.ts @@ -0,0 +1,279 @@ +import { brandingFormSchema } from '@tale/shared/schemas/branding'; +import { deploymentConfigSchema } from '@tale/shared/schemas/deployment'; +import { + FILE_POLICY_TYPES, + POLICY_SCHEMAS, +} from '@tale/shared/schemas/governance'; +import { knowledgeEmbeddingWriteSchema } from '@tale/shared/schemas/knowledge'; +import { + managedAgentInstructionsSchema, + managedAgentToolsSchema, + managedProjectInstructionsSchema, + managedTaskInstructionsSchema, +} from '@tale/shared/schemas/managed-configuration'; +import { + providerDefinitionSchema, + providerEnvironmentCredentialSchema, +} from '@tale/shared/schemas/providers'; +import { + GOVERNANCE_KEYS_NOT_OVER_MCP, + SETTINGS_EFFECTS, + SETTINGS_KINDS, + SETTINGS_KINDS_NOT_OVER_MCP, + type SettingsEffect, + type SettingsKind, +} from '@tale/shared/schemas/settings-kinds'; +import { z } from 'zod'; + +/** + * The settings reference (`get_docs {topic: "settings"}`, + * `tale://docs/settings`): how an agent reads, plans and changes the + * organization's settings, every kind with its config's fields, what each + * effect of a plan means, and every refusal the settings tools answer. + * Built from the descriptors the registry routes by and the schemas each + * kind's writer checks a config against, so a new kind, policy or field is + * listed the day it can be changed. + */ + +/** What each effect a plan names does, in the words an agent repeats to + * the person. */ +const EFFECT_MEANINGS: Readonly> = { + 'signs-out-members': 'members are signed out, or sooner than before', + 'may-lock-out-members': + 'members may be unable to sign in until they act — a stricter password, a second factor, failed sign-ins counted', + 'removes-human-approval': + "something that waited for a person's approval or review no longer does", + 'changes-serving-account': + "the organization's requests go to another endpoint, or are served with another credential", + 'breaks-dependents': 'something that uses the resource stops working', + 'requires-empty-corpus': + 'taken only while the knowledge base holds no document and no website', + 're-embeds-documents': 'what is indexed is turned into vectors again', + 'restart-required': 'takes effect once the deployment restarts', + 'sends-email': 'an email goes out', + 'revokes-access': 'someone loses access', + irreversible: 'cannot be undone', + 'erases-personal-data': 'personal data is erased', + 'staged-cooldown': 'takes effect only after a waiting period', + 'reaches-vendor': "the organization's key is sent to the provider", + 'ends-running-work': 'work that is running is stopped', +}; + +/** Every refusal the settings tools answer of their own; a kind's writer + * answers its own codes too, each with its sentence and a hint. */ +const REFUSALS: ReadonlyArray = [ + [ + 'INVALID_ARGUMENTS', + 'The call is malformed, or `expected` misses a changed resource or names one no change changes: fix every problem in data.issues.', + ], + [ + 'SETTINGS_INVALID', + "A config is not the kind's: data.issues names every problem by its pointer, a field the setting does not have among them.", + ], + [ + 'SETTINGS_ID_REQUIRED', + 'A change names no resource: give its id, or the config that carries it.', + ], + [ + 'SETTINGS_ID_INVALID', + "The id is not the kind's form, or names another resource than the config does.", + ], + [ + 'SETTINGS_IDS_REQUIRED', + 'The kind reads only the resources a call names: pass ids.', + ], + [ + 'SETTINGS_NOT_FOUND', + 'An act names a resource that does not exist: get_settings lists what does.', + ], + [ + 'SETTINGS_DUPLICATE', + 'One call changes a resource twice: send one change per resource, its whole config as it should end.', + ], + [ + 'SETTINGS_STALE', + 'A resource changed since it was read: read it again, plan against what is stored, and apply with data.currentHash.', + ], + [ + 'SETTINGS_KIND_UNAVAILABLE', + 'This deployment does not serve the kind over MCP: the person changes it in Tale.', + ], + [ + 'SETTINGS_TALE_ONLY', + 'The change is made in Tale alone — a secret entered there, or a workflow of its own: tell the person where.', + ], + [ + 'SECRET_ARGUMENT_REFUSED', + 'A change carries a secret, or a masked value where nothing is stored: data.places names where, never the value. A person enters a secret in Tale.', + ], + ['INVALID_CURSOR', 'Pass the nextCursor a listing answered, or none.'], + [ + 'UNKNOWN_POLICY_TYPE', + 'The id names no policy the governance kind takes: the governance section above lists them.', + ], + [ + 'PROVIDER_IN_USE', + 'Credentials still name the provider: remove them first (kind provider-credential).', + ], + [ + 'CREDENTIAL_IN_USE', + 'The embedding model uses the credential: point the knowledge-embedding setting at another first.', + ], + [ + 'PROJECT_AGENT_MANAGED', + 'Tale manages the agent: it changes in Tale alone.', + ], + [ + 'FORBIDDEN', + "The person's role cannot make the change in the app either: say so; do not retry.", + ], + [ + 'EMBEDDING_CORPUS_NOT_EMPTY', + 'The embedding model changes only while the knowledge base is empty; data names how many documents and websites it holds.', + ], + [ + 'BRANDING_IMAGE_UNKNOWN', + 'A branding file name names no image uploaded to the organization: images are uploaded in Tale.', + ], + [ + 'CATALOG_REFRESH_FAILED', + "A provider's catalog could not be read: check its endpoint and credential, then refresh again.", + ], + [ + 'RATE_LIMITED', + "apply_settings drew on the key holder's settings budget once too often: wait data.retryAfterMs.", + ], + [ + 'INTERNAL_ERROR', + 'A writer failed unexpectedly: read what landed with get_settings, and give data.requestId to whoever runs Tale.', + ], +]; + +/** The schema each kind's config is read through; `governance` reads each + * policy through its own. */ +const CONFIG_SCHEMAS: Readonly< + Record, z.ZodType> +> = { + provider: providerDefinitionSchema, + 'provider-credential': providerEnvironmentCredentialSchema, + 'knowledge-embedding': knowledgeEmbeddingWriteSchema, + branding: brandingFormSchema, + 'project-instructions': managedProjectInstructionsSchema, + 'agent-instructions': managedAgentInstructionsSchema, + 'agent-tools': managedAgentToolsSchema, + 'task-instructions': managedTaskInstructionsSchema, + deployment: deploymentConfigSchema, +}; + +/** A config's fields as JSON Schema, compact. A check JSON Schema cannot + * state reads as no constraint: the writer still makes it. */ +function fieldsOf(schema: z.ZodType): string { + const { $schema: _dialect, ...json } = z.toJSONSchema(schema, { + target: 'draft-2020-12', + io: 'input', + unrepresentable: 'any', + }); + return ['```json', JSON.stringify(json), '```'].join('\n'); +} + +const WORKFLOW = [ + '## How a change is made', + '', + '1. get_settings without kinds: the catalog — each kind, its operations and acts, its base risk, the Settings pages it covers, whether this deployment serves it, and whether your role may read and change it.', + '2. get_settings with kinds (and ids): each resource with its `key`, its `config` and its `hash`. A listing that has more answers `nextCursor`.', + '3. plan_settings with the changes: for each, the `action` (create, update, delete, act or unchanged), the `diff`, its `effects` and its `risk`, or why it is refused. Nothing is written. Show the plan to the person, the effects and the risk first.', + '4. apply_settings with the same changes and `expected`: every changed resource by its key, with the hash you read (null for one you create). Every change is planned again against what is stored now; one refusal or one resource that moved applies nothing.', + '', + "A change is `{kind, id, op, config}`: `set` replaces the whole resource with `config` — send every field it should keep, as you read it; `delete` removes it; `act` runs one of the kind's acts. A resource's key is `/`, or the kind alone for a kind with one resource.", + '', + "Changes run in a fixed order across kinds, so what a resource names exists first; the first failure stops the rest, and the answer says what was applied, what failed and what was skipped. Nothing that landed is undone. Every change is in the audit log as the person's, made through MCP.", + '', + '## Secrets', + '', + 'No secret goes into or comes out of a settings call. A stored secret, and any credential found in a stored setting, reads as `{masked: true, preview}`; send that value back unchanged to keep what is stored there. A secret in a change is refused, naming where it was found. A person enters a new secret in Tale.', +]; + +function effectsSection(): string[] { + return [ + '## Effects and risk', + '', + "A plan's risk is the highest of its kind's base risk and its effects'.", + '', + '| Effect | Risk | What happens |', + '| --- | --- | --- |', + ...Object.entries(SETTINGS_EFFECTS).map( + ([effect, risk]) => + `| ${effect} | ${risk} | ${Reflect.get(EFFECT_MEANINGS, effect)} |`, + ), + ]; +} + +function kindSection(descriptor: (typeof SETTINGS_KINDS)[number]): string[] { + const header = [ + `### ${descriptor.kind}`, + '', + descriptor.description, + '', + `Scope: ${descriptor.scope}. Operations: ${descriptor.ops.join(', ')}${descriptor.acts.length > 0 ? `; acts: ${descriptor.acts.join(', ')}` : ''}. Base risk: ${descriptor.baseRisk}.${descriptor.areas.length > 0 ? ` In Tale: Settings > ${descriptor.areas.join(', ')}.` : ''}`, + '', + ]; + if (descriptor.kind !== 'governance') { + return [ + ...header, + 'Config:', + '', + fieldsOf(CONFIG_SCHEMAS[descriptor.kind]), + '', + ]; + } + const policies = FILE_POLICY_TYPES.filter( + (key) => !Object.hasOwn(GOVERNANCE_KEYS_NOT_OVER_MCP, key), + ).toSorted(); + return [ + ...header, + 'Each policy, by its key (the id), with its config:', + '', + ...policies.flatMap((key) => [ + `- \`${key}\``, + '', + fieldsOf(POLICY_SCHEMAS[key]), + '', + ]), + 'Not over MCP:', + '', + ...Object.entries(GOVERNANCE_KEYS_NOT_OVER_MCP).map( + ([key, reason]) => `- \`${key}\` ${reason}.`, + ), + '', + ]; +} + +export function settingsReference(): string { + return [ + '# Settings reference', + '', + "What a coding agent may read and change of the organization's settings through get_settings, plan_settings and apply_settings: the same changes the person's role allows in Tale, through the code Tale's own Settings pages use.", + '', + ...WORKFLOW, + '', + ...effectsSection(), + '', + '## Kinds', + '', + ...SETTINGS_KINDS.flatMap(kindSection), + 'Not settings kinds, on purpose:', + '', + ...SETTINGS_KINDS_NOT_OVER_MCP.map( + (entry) => `- \`${entry.kind}\`: ${entry.reason}`, + ), + '', + '## Refusals', + '', + "A refusal is data `{error, code, hint, data}`. Besides each kind's own codes:", + '', + '| Code | What it means |', + '| --- | --- |', + ...REFUSALS.map(([code, meaning]) => `| ${code} | ${meaning} |`), + '', + ].join('\n'); +} diff --git a/services/platform/lib/mcp/docs/topics.ts b/services/platform/lib/mcp/docs/topics.ts index f704825a4f..2c0292bb2e 100644 --- a/services/platform/lib/mcp/docs/topics.ts +++ b/services/platform/lib/mcp/docs/topics.ts @@ -11,6 +11,7 @@ export const MCP_DOC_TOPICS = [ 'authoring', 'triggers', 'validation', + 'settings', 'skill', ] as const; diff --git a/services/platform/lib/mcp/instructions.ts b/services/platform/lib/mcp/instructions.ts index 4732ccd5b8..d3ad1e887d 100644 --- a/services/platform/lib/mcp/instructions.ts +++ b/services/platform/lib/mcp/instructions.ts @@ -75,8 +75,8 @@ export const INSTRUCTION_FRAGMENTS: readonly InstructionFragment[] = [ tools: [], }, { - text: "Settings: get_settings -> plan_settings -> show the plan -> apply_settings with each resource's expected hash.", - tools: ['get_settings', 'plan_settings', 'apply_settings'], + text: 'Settings: get_settings -> plan_settings -> show the plan -> apply_settings with each resource\'s expected hash; get_docs topic "settings" has the fields.', + tools: ['get_settings', 'plan_settings', 'apply_settings', 'get_docs'], }, { text: "A failed run: read it with get_run, fix the document, reproduce with run_automation and the run's input.", diff --git a/services/platform/lib/mcp/resources.test.ts b/services/platform/lib/mcp/resources.test.ts index 8a264909c6..c7469c1bdd 100644 --- a/services/platform/lib/mcp/resources.test.ts +++ b/services/platform/lib/mcp/resources.test.ts @@ -113,7 +113,7 @@ describe('the resource addresses', () => { test('an address it does not serve is unknown; a served one with a part that cannot be one is invalid', () => { for (const uri of [ 'https://example.test/x', - 'tale://docs/settings', + 'tale://docs/billing', 'tale://catalog/connectors', 'tale://projects/p1', 'tale://docs/', diff --git a/services/platform/lib/mcp/resources.ts b/services/platform/lib/mcp/resources.ts index a98ba07b50..acb079c8ae 100644 --- a/services/platform/lib/mcp/resources.ts +++ b/services/platform/lib/mcp/resources.ts @@ -64,6 +64,11 @@ const DOC_TITLES: Readonly< description: 'How to read what validate_automation answers, and every issue code with its level and the rule it protects.', }, + settings: { + title: 'Settings reference', + description: + "How to read, plan and change the organization's settings: every kind with its config's fields, what each effect of a plan means, and every refusal.", + }, skill: { title: 'The Tale skill (SKILL.md)', description: diff --git a/services/platform/lib/mcp/skill.snapshot.md b/services/platform/lib/mcp/skill.snapshot.md index 63776f444a..67a109e907 100644 --- a/services/platform/lib/mcp/skill.snapshot.md +++ b/services/platform/lib/mcp/skill.snapshot.md @@ -1,11 +1,11 @@ --- name: tale -description: "Edit, check, test, save, deploy and debug Tale automations through Tale's MCP server (get_automation, validate_automation, run_automation, test_automation, save_automation, deploy_automation, get_run). Use when the user asks to create or change a Tale automation, workflow, trigger or schedule, or to find out why a Tale run failed." +description: "Edit, check, test, save, deploy and debug Tale automations through Tale's MCP server (get_automation, validate_automation, run_automation, test_automation, save_automation, deploy_automation, get_run). Also reads and changes the organization's settings within the person's role (get_settings, plan_settings, apply_settings). Use when the user asks to create or change a Tale automation, workflow, trigger or schedule, to find out why a Tale run failed, or to change a Tale setting." license: MIT compatibility: "Needs Tale's MCP server connected (https:///api/v1/mcp); works with any MCP client that reads skills." metadata: publisher: tale - contract: "3.28.0" + contract: "3.30.0" --- # Tale @@ -16,6 +16,7 @@ Tale runs automations: node graphs that a schedule, a webhook, a platform event - Creating or changing a Tale automation, or what starts it (a schedule, a webhook, an event). - Finding out why a Tale run failed, and fixing the automation. +- Changing the organization's settings — a policy, a provider, the branding, a project's or an agent's instructions — when the person asks. - Not for acting on real systems on your own: deploying, triggers and live runs act for real, so they wait for the person's yes. ## Before you start @@ -55,6 +56,14 @@ A save refused with AUTOMATION_VERSION_STALE means someone saved meanwhile: read 3. Reproduce it with run_automation and the run's input, and propose the smallest fix; save it only once the person agrees. 4. When the cause is outside the document (a connector nobody connected, a secret nobody stored, a model the organization does not serve), say which and where in Tale it is set. +## Settings + +1. Read the settings reference once: tale://docs/settings, or get_docs with topic "settings". +2. get_settings without kinds lists every kind and what the person's role may do with it; with kinds (and ids), each resource with its key, config and hash. +3. plan_settings shows what a change would do — its diff, effects and risk — and writes nothing. Show the plan to the person; apply only once they agree. +4. apply_settings with the same changes and expected: each key with the hash you read (null for one you create). A set replaces the whole resource, so send every field it should keep. +- A secret reads as {masked: true, preview} in get_settings: send it back unchanged in apply_settings to keep it. Never put a secret in a change; the person enters it in Tale. + ## Reading refusals A refusal is data, never a crash: {error, code, hint, data}. Branch on code and follow hint. @@ -67,12 +76,16 @@ A refusal is data, never a crash: {error, code, hint, data}. Branch on code and | AUTOMATION_DEPLOYMENT_STALE | Another version went live meanwhile: tell the person and ask again. | | AUTOMATION_NOT_FOUND | Check the name with list_automations; it may be one the person cannot see. | | FORBIDDEN_DEVELOPER_SETTINGS | The person's role cannot do this. Say so; do not retry. | +| SETTINGS_STALE | The setting changed since you read it: read it again with get_settings, plan against what is stored, apply with data.currentHash. | +| SECRET_ARGUMENT_REFUSED | Take the secret out of the change (data.places says where); the person enters it in Tale. | +| SETTINGS_TALE_ONLY | The change is made in Tale alone: tell the person where. | | RATE_LIMITED | Wait data.retryAfterMs, then call again. | | INTERNAL_ERROR | Tell the person data.requestId; whoever runs Tale can look it up. | ## Rules - Ask the person before anything that acts for real or for others: deploy_automation, set_trigger, delete_automation, set_automation_projects, run_deployed, a live start_run, answer_run_ask. +- Ask the person before apply_settings, with the plan's effects and risk in front of them. - Approvals are human-only: never try to decide one. - Never read local credential files, and never ask for, accept or print a secret (an API key, a token, a password). A document never holds one: the organization's secrets reach a run by name. @@ -81,4 +94,5 @@ A refusal is data, never a crash: {error, code, hint, data}. Branch on code and - tale://docs/authoring: the automation grammar and the automation tools (get_docs). - tale://docs/triggers: trigger kinds, their fields and the events (get_docs with topic "triggers"). - tale://docs/validation: reading a validation result, and every issue code (get_docs with topic "validation"). +- tale://docs/settings: every kind of setting with its fields, the effects of a plan and every refusal (get_docs with topic "settings"). - tale://automations/{name} and tale://runs/{runId}: an automation and a run, as get_automation and get_run read them; write "/" in a name as %2F. diff --git a/services/platform/lib/mcp/skill.test.ts b/services/platform/lib/mcp/skill.test.ts index 90fe9a118b..191a1a6c95 100644 --- a/services/platform/lib/mcp/skill.test.ts +++ b/services/platform/lib/mcp/skill.test.ts @@ -102,6 +102,9 @@ describe('the Tale skill', () => { '../engine/api/dispatch.ts', '../../backend/domains/mcp/tools.ts', '../../backend/domains/automations/store.ts', + '../../backend/domains/mcp/settings/apply.ts', + '../../backend/domains/mcp/settings/secrets.ts', + '../../backend/domains/governance/settings-resource.ts', ] .map((file) => readFileSync(new URL(file, import.meta.url), 'utf8')) .join('\n'); diff --git a/services/platform/lib/mcp/skill.ts b/services/platform/lib/mcp/skill.ts index 49d4a5649c..f3d3d65da4 100644 --- a/services/platform/lib/mcp/skill.ts +++ b/services/platform/lib/mcp/skill.ts @@ -54,7 +54,11 @@ export const SKILL_DESCRIPTION: readonly SkillLine[] = [ ], }, { - text: 'Use when the user asks to create or change a Tale automation, workflow, trigger or schedule, or to find out why a Tale run failed.', + text: "Also reads and changes the organization's settings within the person's role (get_settings, plan_settings, apply_settings).", + tools: ['get_settings', 'plan_settings', 'apply_settings'], + }, + { + text: 'Use when the user asks to create or change a Tale automation, workflow, trigger or schedule, to find out why a Tale run failed, or to change a Tale setting.', tools: [], }, ]; @@ -79,6 +83,10 @@ export const SKILL_SECTIONS: readonly SkillSection[] = [ text: '- Finding out why a Tale run failed, and fixing the automation.', tools: [], }, + { + text: "- Changing the organization's settings — a policy, a provider, the branding, a project's or an agent's instructions — when the person asks.", + tools: [], + }, { text: "- Not for acting on real systems on your own: deploying, triggers and live runs act for real, so they wait for the person's yes.", tools: [], @@ -200,6 +208,31 @@ export const SKILL_SECTIONS: readonly SkillSection[] = [ }, ], }, + { + heading: 'Settings', + lines: [ + { + text: '1. Read the settings reference once: tale://docs/settings, or get_docs with topic "settings".', + tools: ['get_docs'], + }, + { + text: "2. get_settings without kinds lists every kind and what the person's role may do with it; with kinds (and ids), each resource with its key, config and hash.", + tools: ['get_settings'], + }, + { + text: '3. plan_settings shows what a change would do — its diff, effects and risk — and writes nothing. Show the plan to the person; apply only once they agree.', + tools: ['plan_settings'], + }, + { + text: '4. apply_settings with the same changes and expected: each key with the hash you read (null for one you create). A set replaces the whole resource, so send every field it should keep.', + tools: ['apply_settings'], + }, + { + text: '- A secret reads as {masked: true, preview} in get_settings: send it back unchanged in apply_settings to keep it. Never put a secret in a change; the person enters it in Tale.', + tools: ['get_settings', 'apply_settings'], + }, + ], + }, { heading: 'Reading refusals', lines: [ @@ -234,6 +267,18 @@ export const SKILL_SECTIONS: readonly SkillSection[] = [ text: "| FORBIDDEN_DEVELOPER_SETTINGS | The person's role cannot do this. Say so; do not retry. |", tools: [], }, + { + text: '| SETTINGS_STALE | The setting changed since you read it: read it again with get_settings, plan against what is stored, apply with data.currentHash. |', + tools: ['get_settings'], + }, + { + text: '| SECRET_ARGUMENT_REFUSED | Take the secret out of the change (data.places says where); the person enters it in Tale. |', + tools: [], + }, + { + text: '| SETTINGS_TALE_ONLY | The change is made in Tale alone: tell the person where. |', + tools: [], + }, { text: '| RATE_LIMITED | Wait data.retryAfterMs, then call again. |', tools: [], @@ -259,6 +304,10 @@ export const SKILL_SECTIONS: readonly SkillSection[] = [ 'answer_run_ask', ], }, + { + text: "- Ask the person before apply_settings, with the plan's effects and risk in front of them.", + tools: ['apply_settings'], + }, { text: '- Approvals are human-only: never try to decide one.', tools: [], @@ -284,6 +333,10 @@ export const SKILL_SECTIONS: readonly SkillSection[] = [ text: '- tale://docs/validation: reading a validation result, and every issue code (get_docs with topic "validation").', tools: ['get_docs'], }, + { + text: '- tale://docs/settings: every kind of setting with its fields, the effects of a plan and every refusal (get_docs with topic "settings").', + tools: ['get_docs'], + }, { text: '- tale://automations/{name} and tale://runs/{runId}: an automation and a run, as get_automation and get_run read them; write "/" in a name as %2F.', tools: ['get_automation', 'get_run'], diff --git a/services/platform/lib/mcp/tools.schema.snapshot.json b/services/platform/lib/mcp/tools.schema.snapshot.json index bfd6684799..7f3636c188 100644 --- a/services/platform/lib/mcp/tools.schema.snapshot.json +++ b/services/platform/lib/mcp/tools.schema.snapshot.json @@ -4,9 +4,9 @@ "type": "object", "properties": { "topic": { - "description": "Which reference: \"authoring\" (the default — the automation grammar and every method), \"triggers\" (what starts an automation, each kind's fields and the events), \"validation\" (how to read a validation result, and every issue code) or \"skill\" (the Tale skill, SKILL.md). Each is also the resource tale://docs/.", + "description": "Which reference: \"authoring\" (the default — the automation grammar and every method), \"triggers\" (what starts an automation, each kind's fields and the events), \"validation\" (how to read a validation result, and every issue code), \"settings\" (every kind of setting with its fields, the effects of a plan and every refusal) or \"skill\" (the Tale skill, SKILL.md). Each is also the resource tale://docs/.", "type": "string", - "enum": ["authoring", "triggers", "validation", "skill"] + "enum": ["authoring", "triggers", "validation", "settings", "skill"] } }, "additionalProperties": false diff --git a/services/platform/lib/shared/constants/api-contract.ts b/services/platform/lib/shared/constants/api-contract.ts index e4d6154e56..e8fbae9bed 100644 --- a/services/platform/lib/shared/constants/api-contract.ts +++ b/services/platform/lib/shared/constants/api-contract.ts @@ -538,7 +538,7 @@ * No other REST operation changes. A script that matched the -32602 * argument error, or read the indented text, reads the tool result instead. * - * 3.28.0 — 2026-10-09: the MCP endpoint reads, plans and changes the + * 3.30.0 — 2026-10-10: the MCP endpoint reads, plans and changes the * organization's settings, in a new `settings` group. `get_settings` * answers, without `kinds`, the catalog of setting kinds (what each is, its * `ops` and `acts`, `baseRisk`, the Settings pages it covers, whether this @@ -555,7 +555,14 @@ * `skipped`. It asks the person before every call and draws from a new * `rest:settings` budget (30 a minute, 60 at once). No argument may carry a * secret (`SECRET_ARGUMENT_REFUSED`); further codes `SETTINGS_KIND_UNAVAILABLE`, - * `SETTINGS_NOT_FOUND` and `SETTINGS_DUPLICATE`. The server instructions - * name the settings loop. No REST operation changes. + * `SETTINGS_NOT_FOUND` and `SETTINGS_DUPLICATE`. The kinds served are the + * organization's own providers and their environment credentials, its + * policies, embedding model and branding, the deployment's settings, and a + * project's instructions and its agents' instructions and tools and a + * task's description, each through the writer its Settings page uses. + * `get_docs` takes the topic `settings` (also `tale://docs/settings`): every + * kind with its config's fields, the effects of a plan and every refusal. + * The server instructions and the Tale skill name the settings loop. No + * REST operation changes. */ -export const API_CONTRACT_VERSION = '3.28.0'; +export const API_CONTRACT_VERSION = '3.30.0'; diff --git a/services/platform/public/openapi.json b/services/platform/public/openapi.json index 41df6b349f..53f4369d08 100644 --- a/services/platform/public/openapi.json +++ b/services/platform/public/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "Tale Platform API", - "version": "3.28.0", + "version": "3.30.0", "contact": { "name": "Tale", "url": "https://tale.dev" @@ -39477,7 +39477,7 @@ "description": "The version of this contract (`info.version`) the serving instance implements — semver for the wire", "schema": { "type": "string", - "example": "3.28.0" + "example": "3.30.0" } }, "Location": { diff --git a/services/platform/scripts/openapi/contract-fingerprint.json b/services/platform/scripts/openapi/contract-fingerprint.json index 7316328883..436e9f1d17 100644 --- a/services/platform/scripts/openapi/contract-fingerprint.json +++ b/services/platform/scripts/openapi/contract-fingerprint.json @@ -1,5 +1,5 @@ { - "version": "3.28.0", + "version": "3.30.0", "operations": "26c9424b511a9ddaac1a98af5ae5b14a95502e15fd7ed39ff7bfba6cb02de6e6", "schemas": "5d6d0095d67ad88656e35fdea3f9c05c8f68e1d73008beb0d5b28d8154ddf978" } diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 1016eab9ac..99d4d2ce74 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -494,7 +494,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [mcp](../suites/mcp.md) | The MCP door's rules in the [MCP spec](../../../backend/domains/mcp/spec.md): saving, deploying, setting or removing a trigger and starting or stopping a live run refused for a member's key as data (`FORBIDDEN_DEVELOPER_SETTINGS`) before anything runs or is charged, while reads stay open; every execution (mock run, tests, deploy gate, live start, capability) drawing one `rest:execute` after its role check, refused as `RATE_LIMITED` with `retryAfterMs` when spent; a refusal answered as a tool result flagged `isError`, never a protocol error; arguments checked against each tool's zod schema with every problem in one `INVALID_ARGUMENTS` tool error (sorted, bounded at 50, unknown keys named, values never echoed), and every advertised input schema a client keeps (root object, no root combinator, 2020-12 meta-schema); every read tool advertising an `outputSchema` and answering `structuredContent` that draft-07 and 2020-12 validators accept (driven through the real dispatch on the selftest host), compact JSON text, refusals and acting tools text only, `_meta` asking the person before `deploy_automation` and `set_trigger` and naming the large-answer sizes; a thrown refusal keeping its code and own sentence (an `AppError` never its serialized payload) and a fault answered as `INTERNAL_ERROR` with the request id only; a batch capped at 20 messages and charged to the key holder's `rest:api` budget per call after the first; an `Idempotency-Key` header refused before anything runs; a request with an `Origin` outside the site's own and `TALE_MCP_ALLOWED_ORIGINS` logged as `[mcp] origin-mismatch` (never a value that is not an origin) and refused with 403 `ORIGIN_FORBIDDEN` only under `TALE_MCP_ORIGIN_ENFORCE=true`, a request without `Origin` never judged, a malformed list refused at boot; the revisions 2025-11-25, 2025-06-18 and 2025-03-26 negotiated on `initialize` and an unknown one in the header refused as `-32022` with `data.supported`; `initialize` answering the server instructions (assembled from fragments whose tools exist, at most 2,048 ASCII characters, a first paragraph of at most 512) and the contract version as `serverInfo.version`, with the inventory's fingerprint pinned to that version and every advertised schema in a reviewed snapshot; and the door's seam — the caller the REST door proved (organization, person, role, key, request id) reaches the engine, which records it as `api-key:` with the key; every answered call counted per organization, person, key, method, tool and UTC day (`app.mcp_client_activity`, 0180) with one log line, neither holding an argument, the client's own name cleaned on `initialize`, a failed count never failing the call, the counters swept after 90 days and erased with the person; authoring parity with the editor (MCP-R1–R4, R9, R14): a save carrying the settings, task contract and presentation it leaves out, refused on a stale `baseVersion` naming the latest, a deploy refused on a stale `expectedDeployedVersion` answering `previousVersion`, `delete_automation` with `expectedLatestVersion`, `get_automation`'s full version view (`createdVia`, `clientName`, `latestVersion`, projects, trigger without the secret), a member's mock `start_run` of any saved version while a live one takes a developer, `list_runs` pages with a cursor signed for its listing and organization, `list_versions` deployments, `set_automation_projects` behind every project's edit gate, `answer_run_ask` as the key holder, `get_automation_metrics`, reads hiding an automation installed only in projects the person cannot read, and every write in a channel naming the agent | ✅ unit | `lib/engine/api/dispatch.authoring.test.ts`, `backend/domains/automations/dispatch-store.authoring.test.ts`, `backend/domains/mcp/protocol.test.ts`, `backend/domains/mcp/caller.test.ts`, `backend/domains/mcp/engine-host.test.ts`, `backend/rest/v1-mcp.test.ts`, `backend/domains/mcp/origin.test.ts`, `backend/env.test.ts`, `lib/mcp/tools.test.ts`, `lib/mcp/instructions.test.ts`, `lib/mcp/contract.test.ts`, `backend/domains/mcp/tools.test.ts`, `lib/engine/api/dispatch.refusals.test.ts`, `backend/domains/mcp/activity.test.ts`, `lib/shared/client-name.test.ts`, `backend/domains/erasure/service.lifecycle.test.ts` | | [mcp](../suites/mcp.md) / [automations](../suites/automations.md) | Validation compares a document with the organization (MCP-R15): an agent step's skill no run of the automation can reach — the organization's skills plus the team skills of the projects it is installed in that the caller can read (`SKILL_UNKNOWN`), a connector not connected or not in the catalog, also for a step running a connector action (`CONNECTOR_NOT_CONNECTED`), a secret nobody stored, told only to owners, admins and developers (`SECRET_UNKNOWN`), a runtime the managed lane cannot run (`HARNESS_UNKNOWN`), and an enabled event trigger waiting for an event Tale does not raise (`EVENT_UNKNOWN`) — warnings only, with the closest name; only the facts a document names are read, each in the caller's organization, and a fact not read within 5 s or whose read fails warns about nothing; the upload door keeps its own skill check and reads no organization facts; the editor's Problems panel shows them (AUTO-F92) | ✅ unit + golden + corpus | `lib/engine/core/analysis/org-state.test.ts`, `lib/engine/core/validate/golden-errors.test.ts` (`golden-errors.yml`), `lib/engine/core/analysis/corpus.test.ts`, `backend/domains/automations/org-facts.test.ts`, `backend/domains/automations/dispatch-store.org-facts.test.ts`, `backend/domains/automations/upload.pool.test.ts`, `lib/i18n/automation-issue-keys.test.ts` | | [mcp](../suites/mcp.md) | The discovery tools (MCP-R23): `list_models` from the member's governed model listing, each with its lane, the step types it suits and the managed runtimes it is offered to (the pickers' `offeredToHarness`), an unknown runtime answering no model; `list_harnesses` with the default and the subscription flag; `list_skills` of the organization or of a readable project (another project or organization → `PROJECT_NOT_FOUND`); `list_connectors` with `connected`; `list_agent_secrets` names and masked previews for owners, admins and developers only, never a value; `list_projects` the readable projects with only the automations the person may see; `list_events` every raised event with its description and no reserved one; `validate_automation` takes `detail`; on the real schema, another organization's project, secret and connector stay invisible and the five organization warnings reach both `validate_automation` and the editor's validate route | ✅ unit + integration | `backend/domains/mcp/platform-tools.test.ts`, `lib/mcp/tools.test.ts`, `lib/mcp/contract.test.ts`, `lib/mcp/instructions.test.ts`, `lib/shared/event-types.test.ts`, `lib/shared/harness-offer.test.ts`, `app/features/settings/connectors/components/mcp-endpoint-section.test.tsx`, the `checkMcpDiscovery` lane in `backend:integration` | -| [mcp](../suites/mcp.md) | Resources, prompts and the Tale skill (MCP-R24, MCP-R25): `initialize` advertising resources and prompts; `resources/list` naming the four references (`tale://docs/{authoring,triggers,validation,skill}`), the five catalog kinds and then the automations `list_automations` answers the key holder, 100 a page with a cursor it issued (a forged one refused `-32602`); `resources/templates/list` and `prompts/list` answered whole; `resources/read` going through the matching tool call (`get_docs` with its `topic`, `get_catalog`, `get_automation` with a percent-encoded name and a version number or `deployed`, `get_run`) with its checks, answering a refusal as `-32002` with `data.code` (a hidden automation exactly like a missing one), a malformed or over-long address as `-32602` without echoing it, a fault as `-32603` with the request id; `prompts/get` (`edit_automation`, `debug_failed_run`, `add_trigger`) attaching what it is about, read as the caller, refusing one whose required read fails, its arguments one word each; reads, listings and prompts charged like tool calls after the first of a batch and counted per method without the address; the lines of prompts, instructions and skill naming exactly the tools they declare and only addresses the server reads; `get_docs {topic}` and `get_catalog`'s core-kind `reference`; the triggers reference built from the trigger schema, the raised events and the backend's delivery constants; the validation reference listing every issue code once; the skill within the Agent Skills limits, MIT, the contract version, deployment-agnostic (a reviewed snapshot), and `GET /api/app/mcp/skill` serving the same bytes as `SKILL.md` to a session only | ✅ unit + integration | `lib/mcp/resources.test.ts`, `lib/mcp/prompts.test.ts`, `lib/mcp/skill.test.ts` (`skill.snapshot.md`), `lib/mcp/docs/triggers.test.ts`, `lib/mcp/docs/validation.test.ts`, `lib/mcp/instructions.test.ts`, `lib/mcp/contract.test.ts`, `backend/domains/mcp/resources.test.ts`, `backend/domains/mcp/prompts.test.ts`, `backend/domains/mcp/routes.test.ts`, `backend/domains/mcp/docs.test.ts`, `lib/engine/selftest/dispatch.test.ts`, `lib/engine/api/dispatch.refusals.test.ts`, the `checkMcpResourcesPrompts` lane in `backend:integration`; Claude Code's `/tale:` menu, `@tale:` mentions and the installed skill stay manual (`MCP-F3`, `MCP-F7`, `MCP-F8`, `MCP-F11`) | +| [mcp](../suites/mcp.md) | Resources, prompts and the Tale skill (MCP-R24, MCP-R25): `initialize` advertising resources and prompts; `resources/list` naming the five references (`tale://docs/{authoring,triggers,validation,settings,skill}`), the five catalog kinds and then the automations `list_automations` answers the key holder, 100 a page with a cursor it issued (a forged one refused `-32602`); `resources/templates/list` and `prompts/list` answered whole; `resources/read` going through the matching tool call (`get_docs` with its `topic`, `get_catalog`, `get_automation` with a percent-encoded name and a version number or `deployed`, `get_run`) with its checks, answering a refusal as `-32002` with `data.code` (a hidden automation exactly like a missing one), a malformed or over-long address as `-32602` without echoing it, a fault as `-32603` with the request id; `prompts/get` (`edit_automation`, `debug_failed_run`, `add_trigger`) attaching what it is about, read as the caller, refusing one whose required read fails, its arguments one word each; reads, listings and prompts charged like tool calls after the first of a batch and counted per method without the address; the lines of prompts, instructions and skill naming exactly the tools they declare and only addresses the server reads; `get_docs {topic}` and `get_catalog`'s core-kind `reference`; the triggers reference built from the trigger schema, the raised events and the backend's delivery constants; the validation reference listing every issue code once; the skill within the Agent Skills limits, MIT, the contract version, deployment-agnostic (a reviewed snapshot), and `GET /api/app/mcp/skill` serving the same bytes as `SKILL.md` to a session only | ✅ unit + integration | `lib/mcp/resources.test.ts`, `lib/mcp/prompts.test.ts`, `lib/mcp/skill.test.ts` (`skill.snapshot.md`), `lib/mcp/docs/triggers.test.ts`, `lib/mcp/docs/validation.test.ts`, `lib/mcp/instructions.test.ts`, `lib/mcp/contract.test.ts`, `backend/domains/mcp/resources.test.ts`, `backend/domains/mcp/prompts.test.ts`, `backend/domains/mcp/routes.test.ts`, `backend/domains/mcp/docs.test.ts`, `lib/engine/selftest/dispatch.test.ts`, `lib/engine/api/dispatch.refusals.test.ts`, the `checkMcpResourcesPrompts` lane in `backend:integration`; Claude Code's `/tale:` menu, `@tale:` mentions and the installed skill stay manual (`MCP-F3`, `MCP-F7`, `MCP-F8`, `MCP-F11`) | | [mcp](../suites/mcp.md) | Both protocol eras on one endpoint (MCP-R16, MCP-R26): a message whose `params._meta` names its revision, or whose `MCP-Protocol-Version` names 2026-07-28, served on the modern rules and everything else as before; on 2026-07-28 a header naming another revision than the body (`-32020`), a missing or malformed `_meta` envelope (`-32602`, `data.missing`/`data.malformed`), a revision it does not speak (`-32022` listing all four, a legacy one in `_meta` told to use `initialize`), then a missing `MCP-Protocol-Version`, a missing or contradicting `Mcp-Method` or `Mcp-Name` (decoded from `=?base64?…?=`, refused when not Base64 or not UTF-8) refused with 400 before anything runs; `server/discover` answering the four revisions, the capabilities, the instructions and the server; `initialize`, `ping` and unknown methods 404 `-32601`; one message per request (a batch naming 2026-07-28 refused whole); every result `resultType: "complete"` with the server under `_meta`, `ttlMs` + `cacheScope: "private"` on discover, the lists and reads (an hour for what a release fixes, a minute for the resource list and the connector catalog, nothing for an automation or a run); a read that finds nothing `-32602` with the tool's code; the client's name from each request's `_meta` reaching the call record, the audit channel and the engine; `initialize` never negotiating 2026-07-28; on the real door, legacy and modern calls interleaved on one key | ✅ unit + integration | `backend/domains/mcp/eras.test.ts`, `backend/domains/mcp/protocol.test.ts`, `lib/mcp/resources.test.ts`, `lib/mcp/contract.test.ts`, the `checkMcpEras` lane in `backend:integration`; a real 2026-07-28 client (Claude Code) beside a legacy one stays manual (`MCP-F12`) | | [mcp](../suites/mcp.md) | No tool decides an approval (MCP-R6): the MCP door's module graph, walked from `backend/rest/v1-mcp.ts` through every static and literal dynamic import, never reaches the approvals domain (`decideApproval` and the session routes that call it); no tool, prompt or resource address is named for an approval, and `answer_run_ask` takes only a run, a question and an answer; a capability whose run waits is answered as the waiting run, not flagged as an error and not a decision | ✅ unit | `backend/domains/mcp/approvals.test.ts`; a real gated step reached from a coding agent and decided in Tale stays unproven end to end | | [automations](../suites/automations.md) | Definition writes audited and attributed (AUTO-R27, AUTO-R28): every saved version, deploy, delete, trigger set or removed and installation added or removed writes one `workflow` audit row in its own transaction, after the organization's audit chain and before the name and the trigger row, naming versions, kinds and project ids but never a document, a webhook token or its hash, and none for a change that changed nothing; a version records the door, key and client it was saved through (0181) and the REST version list keeps its documented fields; an automation installed only in projects the key holder cannot read is left out of `GET /api/v1/automations` and answers 404 on its read, versions and triggers | ✅ unit | `backend/domains/automations/audit.test.ts`, `backend/domains/automations/store.definition-audit.test.ts`, `backend/domains/automations/store.save-version.test.ts`, `backend/rest/v1-automations.contract.test.ts`, `backend/rest/v1-automations.project-scope.test.ts` | From 81676c19655d876a732fc4554a8af3590e9a7f06 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 10:00:09 +0200 Subject: [PATCH 30/35] docs(platform): explain settings over MCP A new page, Settings over MCP, in English, German and French: what each kind of setting holds and who may change it, what stays in Tale, how an agent reads, plans and applies a change with the hash it read, the effects a plan names, secrets and the refusals an agent meets. Its kinds table is held to the served kinds by a test. The MCP endpoint page names the settings reference among the resources and links the page, and the admin overview tells admins their agents can change many settings. --- docs/de/develop/mcp-endpoint.md | 6 +- docs/de/develop/mcp-settings.md | 127 ++++++++++++++++++ docs/de/platform/admin/overview.md | 2 +- docs/en/develop/mcp-endpoint.md | 6 +- docs/en/develop/mcp-settings.md | 127 ++++++++++++++++++ docs/en/platform/admin/overview.md | 2 +- docs/fr/develop/mcp-endpoint.md | 6 +- docs/fr/develop/mcp-settings.md | 127 ++++++++++++++++++ docs/fr/platform/admin/overview.md | 2 +- docs/nav.json | 1 + docs/published.json | 1 + services/docs/app/content/frontmatter.json | 24 ++++ .../platform/lib/mcp/settings-docs.test.ts | 64 +++++++++ services/platform/turbo.json | 1 + 14 files changed, 487 insertions(+), 9 deletions(-) create mode 100644 docs/de/develop/mcp-settings.md create mode 100644 docs/en/develop/mcp-settings.md create mode 100644 docs/fr/develop/mcp-settings.md create mode 100644 services/platform/lib/mcp/settings-docs.test.ts diff --git a/docs/de/develop/mcp-endpoint.md b/docs/de/develop/mcp-endpoint.md index 42289cb056..0ab5e076cf 100644 --- a/docs/de/develop/mcp-endpoint.md +++ b/docs/de/develop/mcp-endpoint.md @@ -50,7 +50,7 @@ curl --fail-with-body "$TALE_URL/api/v1/mcp" \ --data '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_docs","arguments":{}}}' ``` -Bei Erfolg enthält `get_docs` die Automatisierungsreferenz als Text, ohne gesetztes Fehlerkennzeichen. Mit `"arguments":{"topic":"triggers"}` erhältst du die Trigger-Referenz (die Felder jeder Trigger-Art, die Eingabe, mit der ihre Läufe starten, und die Ereignisse), mit `"validation"` die Anleitung zum Lesen eines Validierungsergebnisses samt jedem Fehlercode und mit `"skill"` den [Tale-Skill](/de/develop/use-tale-from-your-editor#tale-skill). Mit `method: "tools/list"` erhältst du stattdessen die Tool-Schemas. Bewahre die JSON-RPC-`id`, damit dein Client Antwort und Anfrage zuordnen kann. +Bei Erfolg enthält `get_docs` die Automatisierungsreferenz als Text, ohne gesetztes Fehlerkennzeichen. Mit `"arguments":{"topic":"triggers"}` erhältst du die Trigger-Referenz (die Felder jeder Trigger-Art, die Eingabe, mit der ihre Läufe starten, und die Ereignisse), mit `"validation"` die Anleitung zum Lesen eines Validierungsergebnisses samt jedem Fehlercode, mit `"settings"` jede Art von Einstellung mit ihren Feldern ([Einstellungen über MCP](/de/develop/mcp-settings)) und mit `"skill"` den [Tale-Skill](/de/develop/use-tale-from-your-editor#tale-skill). Mit `method: "tools/list"` erhältst du stattdessen die Tool-Schemas. Bewahre die JSON-RPC-`id`, damit dein Client Antwort und Anfrage zuordnen kann. ### Transport und Sammelanfragen @@ -192,6 +192,8 @@ Jede Antwort trägt einen `hint`, der das Tool oder die Einstellung nennt, mit d Eine Änderung nennt ihre Art (`kind`), die `id` der Ressource (entfällt bei einer Art mit nur einer Ressource) und ihre Operation (`op`): `set` ersetzt die Ressource durch die ganze `config` und legt sie an, wenn es sie noch nicht gibt; `delete` entfernt sie; `act` führt eine der Aktionen der Art mit ihren `args` aus. Plane zuerst, zeig der Person den Plan und nimm dann dieselben Änderungen vor: `apply_settings` fragt die Person vor jedem Aufruf und hat ein eigenes [Budget](/de/develop/rate-limits). +[Einstellungen über MCP](/de/develop/mcp-settings) listet jede Art von Einstellung, wer sie ändern darf und was in Tale bleibt. + Kein Secret geht durch diese Tools. Ein gespeichertes Secret erscheint als `{"masked": true, "preview": "…"}`; schick diesen Wert unverändert zurück, um es zu behalten. Eine Änderung mit einem anderen Wert an der Stelle eines Secrets oder mit Zugangsdaten irgendwo in ihrer Konfiguration wird mit `SECRET_ARGUMENT_REFUSED` abgelehnt; ein neues Secret gibt eine Person in Tale ein. ### Capabilities und Wissen {#capabilities} @@ -214,7 +216,7 @@ Neben Tools liefert der Endpunkt Ressourcen, die ein Client über ihre Adresse l | Adresse | Inhalt | Liest sich wie | | --- | --- | --- | -| `tale://docs/authoring`, `tale://docs/triggers`, `tale://docs/validation`, `tale://docs/skill` | Die Referenzen als Markdown | `get_docs` mit diesem `topic` | +| `tale://docs/authoring`, `tale://docs/triggers`, `tale://docs/validation`, `tale://docs/settings`, `tale://docs/skill` | Die Referenzen als Markdown | `get_docs` mit diesem `topic` | | `tale://catalog/{kind}` (`transform`, `llm`, `agent`, `subautomation`, `connector`) | Den Abschnitt der Referenz zu einer Kern-Knotenart oder die Connector-Aktionen | `get_catalog` mit diesem `kind` | | `tale://automations/{name}` | Die zuletzt gespeicherte Version als JSON | `get_automation` | | `tale://automations/{name}/versions/{version}` | Eine gespeicherte Version; `{version}` ist eine Nummer oder `deployed` | `get_automation` mit `version` | diff --git a/docs/de/develop/mcp-settings.md b/docs/de/develop/mcp-settings.md new file mode 100644 index 0000000000..517d2a31dd --- /dev/null +++ b/docs/de/develop/mcp-settings.md @@ -0,0 +1,127 @@ +--- +title: Einstellungen über MCP +description: Lass einen Coding-Agenten die Einstellungen von Tale über den MCP-Endpunkt lesen und ändern — im Rahmen der Rolle der Person, deren API-Schlüssel er nutzt. +--- + +Ein Coding-Agent, der mit dem [MCP-Endpunkt](/de/develop/mcp-endpoint) verbunden ist, liest die Einstellungen deiner Organisation, plant eine Änderung und nimmt sie vor — mit drei Tools: `get_settings`, `plan_settings` und `apply_settings`. Er handelt mit der Rolle der Person, deren API-Schlüssel er nutzt. Er darf ändern, was diese Person in der App ändern dürfte, und durchläuft dieselben Prüfungen. Die [Audit-Logs](/de/platform/admin/governance/audit-logs) halten jede Änderung als Änderung dieser Person fest, vorgenommen über MCP. + +## Was ein Agent ändern kann {#kinds} + +Tale liest und schreibt jede Art von Einstellung mit seinem eigenen Code und den Prüfungen, die auch die App vornimmt. Deshalb gelten dieselben Rollenregeln wie in der App. + +| Art | Was sie enthält | Änderungen | Wer sie ändern darf | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `provider` | Ein KI-Anbieter, den deine Organisation selbst angelegt hat: sein Endpunkt, sein API-Format und sein Modellkatalog. Die Anbieter, die Tale mitbringt, sind keine Einstellungen. | Setzen, löschen; den Modellkatalog neu einlesen (`refresh-catalogs`) | Inhaber, Admins und Entwickler | +| `provider-credential` | Zugangsdaten, die ihren Schlüssel aus einer Umgebungsvariable des Deployments lesen. Zugangsdaten mit Schlüssel oder Abonnement erscheinen ohne ihr Secret und lassen sich entfernen. | Setzen, löschen | Inhaber, Admins und Entwickler | +| `governance` | Eine Richtlinie der Organisation, benannt nach ihrem Schlüssel: Modelle und Modellzugriff, Budgets und Limits, Anmelde- und Sitzungssicherheit, Guardrails, Sandbox-Kontingente. | Setzen | Inhaber und Admins | +| `knowledge-embedding` | Das Embedding-Modell des Wissens deiner Organisation, mit seiner Ähnlichkeitsschwelle und seinen Nutzungsgrenzen. | Setzen | Inhaber und Admins | +| `branding` | Die Akzentfarbe und die Dateinamen von Logo und Favicons. | Setzen | Inhaber und Admins | +| `project-instructions` | Die festen Anweisungen eines Projekts. | Setzen | Wer das Projekt bearbeiten darf | +| `agent-instructions` | Die Anweisungen eines Projekt-Agenten. | Setzen | Wer das Projekt bearbeiten darf | +| `agent-tools` | Die Tools, die ein Projekt-Agent nutzen darf. | Setzen | Wer das Projekt bearbeiten darf | +| `task-instructions` | Die Beschreibung einer Aufgabe. | Setzen | Wer die Aufgabe ändern darf | +| `deployment` | Die eigenen Einstellungen des Deployments, die für jede Organisation darauf gelten, etwa die Sandbox-Laufzeit. | Setzen | Lesen darf sie jeder Inhaber und Admin einer Organisation auf dem Deployment; ändern dürfen sie nur die Adressen auf der Editor-Freigabeliste des Deployments | + +Eine Ressource hat innerhalb ihrer Art eine ID: ein Anbieter seinen Namen, Zugangsdaten `/` mit URI-kodiertem Namen, eine Richtlinie ihren Schlüssel wie `password_policy`, ein Projekt seine ID, ein Agent `/` und eine Aufgabe `/`. Embedding-Modell, Branding und Deployment-Einstellungen haben keine ID. `get_settings` listet Projekt- und Agenteneinstellungen seitenweise über die Projekte, die du lesen darfst; die Beschreibung einer Aufgabe liest es nur über ihre ID. + +Manche Änderungen bleiben in Tale: + +- Jedes Secret, etwa der API-Schlüssel eines Anbieters, ein Abonnement oder der Schlüssel des Moderationsanbieters, gibt eine Person in Tale ein. +- Die Aufbewahrungsrichtlinie und die Richtlinie für Anfragen betroffener Personen ändern sich nur über ihre eigenen, gestuften Abläufe. +- Branding-Bilder werden in Tale hochgeladen. Ein Dateiname, den ein Agent setzt, muss ein bereits hochgeladenes Bild nennen. +- Über MCP ändert sich das Embedding-Modell selbst nur, solange das Wissen der Organisation kein Dokument und keine Website enthält. So treffen Vektoren zweier Modelle nie in einer Suche aufeinander. Ähnlichkeitsschwelle und Nutzungsgrenzen ändern sich jederzeit; sind Dokumente indexiert, ändert eine Person das Modell in Tale. +- Der Standard-Agent eines Projekts folgt der Richtlinie `standard_agent`, die die Art `governance` ändert; seine eigenen Anweisungen und Tools sind keine Einstellungen. +- Mitglieder, Teams, Connectors, Skills, Kompetenzen, Legal Holds, die Audit-Logs, Metriken und persönliche Einstellungen deckt keine Art ab. `get_settings` ohne Argumente zeigt, was jede Art abdeckt. + +## Eine Änderung vornehmen {#make-a-change} + +1. Ruf `get_settings` ohne Argumente auf. Die Antwort listet jede Art, ob dieses Deployment sie bedient und ob deine Rolle sie lesen und ändern darf. +2. Lies mit `get_settings` und `kinds` (und `ids`), was du ändern willst. Jede Ressource kommt mit ihrem `key`, ihrer `config` und ihrem `hash`. +3. Plane die Änderung mit `plan_settings`. Ein `set` ersetzt die ganze Ressource durch ihre `config`. Schick deshalb jedes Feld mit, das erhalten bleiben soll, so wie du es gelesen hast. Der Plan nennt für jede Änderung ihre Aktion, ihren Diff, ihre Auswirkungen und ihr Risiko oder die Ablehnung, an der sie scheitert. Geschrieben wird dabei nichts. +4. Zeig der Person den Plan und warte auf ihre Entscheidung. Stell die Auswirkungen und das Risiko an den Anfang. +5. Nimm dieselben Änderungen mit `apply_settings` vor. `expected` ordnet dem `key` jeder geänderten Ressource den Hash zu, den du gelesen hast, oder `null` für eine, die du anlegst. + +So sehen die Argumente eines Plans aus, der die Passwort-Rotation einschaltet: + +```json +{ + "changes": [ + { + "kind": "governance", + "id": "password_policy", + "op": "set", + "config": { + "minLength": 12, + "requireUpper": true, + "requireLower": true, + "requireDigit": true, + "requireSpecial": true, + "rotationDays": 90 + } + } + ] +} +``` + +Der Plan nennt die Auswirkung auf die Mitglieder, denn die Rotation lässt bereits gesetzte Passwörter ablaufen. Der Hash ist hier gekürzt: + +```json +{ + "ok": true, + "changes": [ + { + "kind": "governance", + "id": "password_policy", + "key": "governance/password_policy", + "op": "set", + "action": "update", + "currentHash": "5c1f…", + "diff": [{ "path": "/rotationDays", "before": 0, "after": 90 }], + "effects": ["may-lock-out-members"], + "risk": "critical" + } + ] +} +``` + +Zum Übernehmen schickst du dieselben `changes` mit `"expected": { "governance/password_policy": "5c1f…" }`, mit dem vollständigen Hash. Bevor etwas geschrieben wird, plant Tale jede Änderung noch einmal gegen das, was jetzt gespeichert ist. Wird eine abgelehnt oder hat sich eine Ressource seit dem Lesen geändert, wird nichts übernommen. Sonst laufen die Änderungen in einer festen Reihenfolge über die Arten hinweg, damit das, worauf eine Ressource verweist, zuerst existiert. Die erste Änderung, die scheitert, hält die übrigen an, und die Antwort listet, was übernommen wurde (`applied`), was gescheitert ist (`failed`) und was übersprungen wurde (`skipped`). Was bereits übernommen wurde, wird nicht rückgängig gemacht. + +`apply_settings` fragt die Person vor jedem Aufruf und hat ein eigenes [Budget](/de/develop/rate-limits). + +## Die Auswirkungen eines Plans lesen {#effects} + +Das Risiko eines Plans ist das höchste aus dem Grundrisiko seiner Art und dem Risiko seiner Auswirkungen. Diese Auswirkungen können die heute bedienten Arten nennen: + +| Auswirkung | Risiko | Wann ein Plan sie nennt | +| ------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `may-lock-out-members` | critical | Die Anmeldesperre ist nach der Änderung aktiv, die Passwort-Rotation beginnt oder wird kürzer, oder die Zwei-Faktor-Authentifizierung wird strenger | +| `signs-out-members` | critical | Das Inaktivitätslimit wird eingeschaltet oder kürzer | +| `removes-human-approval` | critical | Eine Freigaberegel oder eine Prüfpflicht fragt keine Person mehr | +| `changes-serving-account` | high | Der Endpunkt eines Anbieters ändert sich, oder andere Zugangsdaten bedienen seine Anfragen | +| `breaks-dependents` | high | Die aktiven Standard-Zugangsdaten des Anbieters werden entfernt, und nichts ersetzt sie | +| `requires-empty-corpus` | critical | Das Embedding-Modell ändert sich; das setzt voraus, dass das Wissen der Organisation leer ist | +| `restart-required` | critical | Die Sandbox-Laufzeit des Deployments ändert sich | +| `reaches-vendor` | high | Der Modellkatalog eines Anbieters wird mit dem Schlüssel deiner Organisation neu eingelesen | + +Die Einstellungsreferenz, die `get_docs` für das Thema `settings` liefert (auch `tale://docs/settings`), listet das ganze Vokabular, die Felder jeder Art und jede Richtlinie. + +## Secrets {#secrets} + +Kein Secret geht in einen Einstellungsaufruf hinein oder kommt aus ihm heraus. Ein gespeichertes Secret erscheint als `{"masked": true, "preview": "…"}`, ebenso alle Zugangsdaten, die irgendwo sonst in einer gespeicherten Einstellung stehen — etwa ein Schlüssel, den jemand in Tale in eine Richtlinie eingefügt hat. Schick diesen Wert unverändert zurück, um zu behalten, was dort gespeichert ist. Eine Änderung, die ein Secret enthält, wird mit `SECRET_ARGUMENT_REFUSED` abgelehnt; die Ablehnung nennt die Stelle, nie den Wert. Ein neues Secret gibt eine Person in Tale ein. + +## Wenn eine Änderung abgelehnt wird {#refusals} + +Eine Ablehnung kommt als Daten zurück, mit `error`, `code`, `hint` und manchmal `data`, nie als abgebrochene Verbindung. Diese Codes begegnen einem Agenten am häufigsten: + +| Code | Was er bedeutet | +| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SETTINGS_STALE` | Die Ressource hat sich seit dem Lesen geändert. Lies sie erneut, plane gegen den aktuellen Stand und übernimm mit `data.currentHash`. | +| `SETTINGS_INVALID` | Die Konfiguration passt nicht zur Art. `data.issues` nennt jedes Problem mit seiner Stelle in der Konfiguration, auch ein Feld, das die Einstellung nicht kennt. | +| `SECRET_ARGUMENT_REFUSED` | Die Änderung enthält ein Secret. `data.places` nennt die Stelle. | +| `SETTINGS_TALE_ONLY` | Diese Änderung geht nur in Tale, zum Beispiel bei Zugangsdaten mit Schlüssel. | +| `FORBIDDEN`, `ORG_FORBIDDEN`, `FORBIDDEN_DEVELOPER_SETTINGS` | Die Rolle der Person erlaubt diese Änderung auch in Tale nicht. Ein neuer Versuch hilft nicht. | +| `EMBEDDING_CORPUS_NOT_EMPTY` | Das Embedding-Modell ändert sich nur, solange das Wissen der Organisation leer ist. `data` nennt, wie viele Dokumente und Websites es enthält. | +| `BRANDING_IMAGE_UNKNOWN` | Ein Branding-Dateiname nennt kein Bild, das in die Organisation hochgeladen wurde. | +| `PROVIDER_IN_USE`, `CREDENTIAL_IN_USE` | Zugangsdaten nennen den Anbieter noch, oder das Embedding-Modell nutzt die Zugangsdaten. Ändere zuerst diese. | + +Die Einstellungsreferenz listet jeden Code. Die Seite zum [MCP-Endpunkt](/de/develop/mcp-endpoint#settings) beschreibt die Argumente und Antworten der Tools. diff --git a/docs/de/platform/admin/overview.md b/docs/de/platform/admin/overview.md index d7ed2e5490..04b9ce41a4 100644 --- a/docs/de/platform/admin/overview.md +++ b/docs/de/platform/admin/overview.md @@ -32,7 +32,7 @@ Inhaber und Admins verwalten die Organisationseinstellungen. Entwickler erreiche ## Anmeldung, Integrationen und Darstellung -Richte [Enterprise SSO](/de/platform/admin/enterprise-sso) für deinen Identitätsanbieter und [Zwei-Faktor-Authentifizierung](/de/platform/admin/two-factor-authentication) zum Schutz der Konten ein. [API-Schlüssel](/de/platform/admin/api-keys) ermöglichen Software den Zugriff auf Tale. +Richte [Enterprise SSO](/de/platform/admin/enterprise-sso) für deinen Identitätsanbieter und [Zwei-Faktor-Authentifizierung](/de/platform/admin/two-factor-authentication) zum Schutz der Konten ein. [API-Schlüssel](/de/platform/admin/api-keys) ermöglichen Software den Zugriff auf Tale. Ein Coding-Agent, der damit verbunden ist, kann viele dieser Einstellungen selbst ändern, im Rahmen der Rolle der Person, deren Schlüssel er nutzt; welche, steht unter [Einstellungen über MCP](/de/develop/mcp-settings). Unter [Branding](/de/platform/admin/branding) änderst du Logo und Farben der Organisation. [Sandboxes](/de/platform/admin/sandboxes) zeigt Ausführungskapazität und Limits für die einzelnen Aufgabenarten; mit [Sandbox-Geräten](/de/platform/admin/sandbox-devices) laufen die Sandboxes deiner Organisation auf eigenen Rechnern. Wie ein Projekt-Agent diese Ressourcen nutzen darf, erklärt [Agenten aus Administrationssicht](/de/platform/admin/agents). diff --git a/docs/en/develop/mcp-endpoint.md b/docs/en/develop/mcp-endpoint.md index cc0e93b5f1..dbe3243717 100644 --- a/docs/en/develop/mcp-endpoint.md +++ b/docs/en/develop/mcp-endpoint.md @@ -50,7 +50,7 @@ curl --fail-with-body "$TALE_URL/api/v1/mcp" \ --data '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_docs","arguments":{}}}' ``` -A successful `get_docs` result contains the automation reference as text and has no error flag set. Add `"arguments":{"topic":"triggers"}` for the triggers reference (each trigger kind's fields, the input its runs start with, and the events), `"validation"` for how to read a validation result and every issue code, or `"skill"` for the [Tale skill](/develop/use-tale-from-your-editor#tale-skill). To inspect tool schemas instead, send `method: "tools/list"`. Keep the JSON-RPC `id` so a client can match a result to its request. +A successful `get_docs` result contains the automation reference as text and has no error flag set. Add `"arguments":{"topic":"triggers"}` for the triggers reference (each trigger kind's fields, the input its runs start with, and the events), `"validation"` for how to read a validation result and every issue code, `"settings"` for every kind of setting with its fields ([Settings over MCP](/develop/mcp-settings)), or `"skill"` for the [Tale skill](/develop/use-tale-from-your-editor#tale-skill). To inspect tool schemas instead, send `method: "tools/list"`. Keep the JSON-RPC `id` so a client can match a result to its request. ### Transport and batches @@ -192,6 +192,8 @@ Each answer carries a `hint` that names the tool or the setting that changes it. A change names its `kind`, the resource's `id` (left out for a kind with one resource) and its `op`: `set` replaces the resource with the whole `config`, creating it when it does not exist; `delete` removes it; `act` runs one of the kind's actions, with its `args`. Plan first, show the plan to the person, then apply the same changes: `apply_settings` asks the person before every call and uses a [budget](/develop/rate-limits) of its own. +[Settings over MCP](/develop/mcp-settings) lists every kind of setting, who may change it and what stays in Tale. + No secret travels through these tools. A stored secret reads as `{"masked": true, "preview": "…"}`; send that value back unchanged to keep it. A change that carries any other value in a secret's place, or a credential anywhere in its config, is refused with `SECRET_ARGUMENT_REFUSED`; a person enters a new secret in Tale. ### Capabilities & knowledge {#capabilities} @@ -214,7 +216,7 @@ Besides tools, the endpoint serves resources, which a client reads by address, a | Address | Contents | Read like | | --- | --- | --- | -| `tale://docs/authoring`, `tale://docs/triggers`, `tale://docs/validation`, `tale://docs/skill` | The references, as Markdown | `get_docs` with that `topic` | +| `tale://docs/authoring`, `tale://docs/triggers`, `tale://docs/validation`, `tale://docs/settings`, `tale://docs/skill` | The references, as Markdown | `get_docs` with that `topic` | | `tale://catalog/{kind}` (`transform`, `llm`, `agent`, `subautomation`, `connector`) | A core node kind's section of the reference, or the connector actions | `get_catalog` with that `kind` | | `tale://automations/{name}` | The latest saved version, as JSON | `get_automation` | | `tale://automations/{name}/versions/{version}` | One saved version; `{version}` is a number or `deployed` | `get_automation` with `version` | diff --git a/docs/en/develop/mcp-settings.md b/docs/en/develop/mcp-settings.md new file mode 100644 index 0000000000..4966e2850c --- /dev/null +++ b/docs/en/develop/mcp-settings.md @@ -0,0 +1,127 @@ +--- +title: Settings over MCP +description: Let a coding agent read and change Tale settings through the MCP endpoint, within the role of the person whose API key it uses. +--- + +A coding agent connected to the [MCP endpoint](/develop/mcp-endpoint) can read your organization's settings, plan a change and make it with three tools: `get_settings`, `plan_settings` and `apply_settings`. It acts with the role of the person whose API key it uses. It can change what that person could change in the app, through the same checks, and the [audit log](/platform/admin/governance/audit-logs) records every change as that person's, made through MCP. + +## What an agent can change {#kinds} + +Tale reads and writes each kind of setting with its own code and the checks the app applies, so the role rules are the same as in the app. + +| Kind | What it holds | Changes | Who can change it | +| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `provider` | An AI provider your organization defined: its endpoint, API format and model catalog. The providers Tale ships are not settings. | Set, delete; read its model catalog again (`refresh-catalogs`) | Owners, admins and developers | +| `provider-credential` | A credential that reads its key from an environment variable of the deployment. Credentials with a key or a subscription are listed without their secret and can be removed. | Set, delete | Owners, admins and developers | +| `governance` | One organization policy, named by its key: models and model access, budgets and limits, sign-in and session security, guardrails, sandbox quotas. | Set | Owners and admins | +| `knowledge-embedding` | The embedding model of the organization's knowledge base, with its similarity floor and serving limits. | Set | Owners and admins | +| `branding` | The accent color and the file names of the logo and the favicons. | Set | Owners and admins | +| `project-instructions` | A project's standing instructions. | Set | Whoever can edit the project | +| `agent-instructions` | A project agent's instructions. | Set | Whoever can edit the project | +| `agent-tools` | The tools a project agent may use. | Set | Whoever can edit the project | +| `task-instructions` | A task's description. | Set | Whoever can change the task | +| `deployment` | The deployment's own settings, shared by every organization on it, such as the sandbox runtime. | Set | An owner or admin of any organization on the deployment reads them; only the addresses on the deployment's editor allowlist change them | + +A resource has an id within its kind: a provider by its name, a credential as `/` with the name URI-encoded, a policy by its key such as `password_policy`, a project by its id, an agent as `/` and a task as `/`. The embedding model, the branding and the deployment settings have no id. `get_settings` lists project and agent settings page by page over the projects you can read; it reads a task's description only by its id. + +Some changes stay in Tale: + +- Every secret, such as a provider's API key, a subscription or the moderation provider's key, is entered by a person in Tale. +- The retention policy and the data subject request policy change through their own staged workflows. +- Branding images are uploaded in Tale. A file name an agent sets must name an image already uploaded. +- Over MCP, the embedding model itself changes only while the knowledge base holds no document and no website, so that vectors from two models never meet in one search. Its similarity floor and serving limits change at any time; with documents indexed, a person changes the model in Tale. +- A project's standard agent follows the `standard_agent` policy, which the `governance` kind changes; its own instructions and tools are not settings. +- No kind covers members, teams, connectors, skills, competences, legal holds, the audit log, metrics or personal settings. `get_settings` without arguments shows what each kind covers. + +## Make a change {#make-a-change} + +1. Call `get_settings` without arguments. It lists every kind, whether this deployment serves it, and whether your role may read and change it. +2. Read what you want to change with `get_settings` and `kinds` (and `ids`). Each resource comes with its `key`, its `config` and its `hash`. +3. Plan the change with `plan_settings`. A `set` replaces the whole resource with its `config`, so send every field it should keep, as you read it. The plan names each change's action, its diff, its effects and its risk, or the refusal that stops it. Nothing is written. +4. Show the plan to the person and wait for their decision. Put the effects and the risk first. +5. Apply the same changes with `apply_settings`. `expected` maps each changed resource's `key` to the hash you read, or to `null` for one you create. + +These are the arguments of a plan that turns on password rotation: + +```json +{ + "changes": [ + { + "kind": "governance", + "id": "password_policy", + "op": "set", + "config": { + "minLength": 12, + "requireUpper": true, + "requireLower": true, + "requireDigit": true, + "requireSpecial": true, + "rotationDays": 90 + } + } + ] +} +``` + +The plan answers the change with its effect on members, because rotation expires passwords that are already set. The hash is shortened here: + +```json +{ + "ok": true, + "changes": [ + { + "kind": "governance", + "id": "password_policy", + "key": "governance/password_policy", + "op": "set", + "action": "update", + "currentHash": "5c1f…", + "diff": [{ "path": "/rotationDays", "before": 0, "after": 90 }], + "effects": ["may-lock-out-members"], + "risk": "critical" + } + ] +} +``` + +To apply it, send the same `changes` with `"expected": { "governance/password_policy": "5c1f…" }`, using the full hash. Before anything is written, every change is planned again against what is stored now. If one is refused, or a resource changed since you read it, nothing is applied. Otherwise the changes run in a fixed order across kinds, so that what a resource refers to exists first. The first failure stops the rest, and the answer lists what was `applied`, what `failed` and what was `skipped`. A change that already landed is not undone. + +`apply_settings` asks the person before every call and uses a [budget](/develop/rate-limits) of its own. + +## Read a plan's effects {#effects} + +A plan's risk is the highest of its kind's base risk and its effects' risk. These are the effects the kinds served today can name: + +| Effect | Risk | When a plan names it | +| ------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------- | +| `may-lock-out-members` | critical | The sign-in lockout is on after the change, password rotation starts or gets shorter, or two-factor authentication becomes stricter | +| `signs-out-members` | critical | The idle timeout is turned on or gets shorter | +| `removes-human-approval` | critical | An approval rule or a review requirement no longer asks a person | +| `changes-serving-account` | high | A provider's endpoint changes, or another credential serves its requests | +| `breaks-dependents` | high | The provider's active default credential is removed and nothing replaces it | +| `requires-empty-corpus` | critical | The embedding model changes, which needs an empty knowledge base | +| `restart-required` | critical | The deployment's sandbox runtime changes | +| `reaches-vendor` | high | A provider's model catalog is read again with your organization's key | + +The settings reference that `get_docs` returns for the topic `settings` (also `tale://docs/settings`) lists the whole vocabulary, every kind's fields and every governance policy. + +## Secrets {#secrets} + +No secret goes into or comes out of a settings call. A stored secret reads as `{"masked": true, "preview": "…"}`, and so does any credential found elsewhere in a stored setting, such as a key someone pasted into a policy in Tale. Send that value back unchanged to keep what is stored there. A change that carries a secret is refused with `SECRET_ARGUMENT_REFUSED`, which names where the secret was found and never its value. A person enters a new secret in Tale. + +## When a change is refused {#refusals} + +A refusal is data with an `error`, a `code`, a `hint` and sometimes `data`, never a failed connection. These are the codes an agent meets most often: + +| Code | What it means | +| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `SETTINGS_STALE` | The resource changed since it was read. Read it again, plan against what is stored now, and apply with `data.currentHash`. | +| `SETTINGS_INVALID` | The config is not the kind's. `data.issues` names every problem by its place in the config, including a field the setting does not have. | +| `SECRET_ARGUMENT_REFUSED` | The change carries a secret. `data.places` says where. | +| `SETTINGS_TALE_ONLY` | The change is made in Tale alone, for example a credential with a key. | +| `FORBIDDEN`, `ORG_FORBIDDEN`, `FORBIDDEN_DEVELOPER_SETTINGS` | The person's role cannot make this change in Tale either. Retrying does not help. | +| `EMBEDDING_CORPUS_NOT_EMPTY` | The embedding model changes only while the knowledge base is empty. `data` names how many documents and websites it holds. | +| `BRANDING_IMAGE_UNKNOWN` | A branding file name names no image uploaded to the organization. | +| `PROVIDER_IN_USE`, `CREDENTIAL_IN_USE` | Credentials still name the provider, or the embedding model uses the credential. Change those first. | + +The settings reference lists every code. The [MCP endpoint](/develop/mcp-endpoint#settings) page describes the tools' arguments and answers. diff --git a/docs/en/platform/admin/overview.md b/docs/en/platform/admin/overview.md index 55d607f8b2..551f030bf8 100644 --- a/docs/en/platform/admin/overview.md +++ b/docs/en/platform/admin/overview.md @@ -32,7 +32,7 @@ Owners and Admins manage organization settings. Developers can reach the technic ## Sign-in, integrations, and appearance -Configure [enterprise SSO](/platform/admin/enterprise-sso) for your identity provider and [two-factor authentication](/platform/admin/two-factor-authentication) for account protection. Use [API keys](/platform/admin/api-keys) when software needs to call Tale. +Configure [enterprise SSO](/platform/admin/enterprise-sso) for your identity provider and [two-factor authentication](/platform/admin/two-factor-authentication) for account protection. Use [API keys](/platform/admin/api-keys) when software needs to call Tale. A coding agent connected with one can change many of these settings itself, within the role of the key's owner; [Settings over MCP](/develop/mcp-settings) lists which. [Branding](/platform/admin/branding) changes the organization's logo and colors. [Sandboxes](/platform/admin/sandboxes) shows execution capacity and workload limits; with [sandbox devices](/platform/admin/sandbox-devices), your organization's sandboxes run on machines of your own. For a project agent's access to these resources, read [Agents (admin view)](/platform/admin/agents). diff --git a/docs/fr/develop/mcp-endpoint.md b/docs/fr/develop/mcp-endpoint.md index cd0a4bc058..7fa7ca970f 100644 --- a/docs/fr/develop/mcp-endpoint.md +++ b/docs/fr/develop/mcp-endpoint.md @@ -50,7 +50,7 @@ curl --fail-with-body "$TALE_URL/api/v1/mcp" \ --data '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_docs","arguments":{}}}' ``` -Un résultat `get_docs` réussi contient la référence des automatisations en texte et ne porte pas d'indicateur d'erreur. Ajoute `"arguments":{"topic":"triggers"}` pour la référence des déclencheurs (les champs de chaque type de déclencheur, l’entrée avec laquelle ses exécutions démarrent et les événements), `"validation"` pour lire un résultat de validation et connaître chaque code d’erreur, ou `"skill"` pour le [skill Tale](/fr/develop/use-tale-from-your-editor#tale-skill). Pour consulter les schémas des outils, envoie plutôt `method: "tools/list"`. Conserve l'`id` JSON-RPC pour associer chaque résultat à sa requête. +Un résultat `get_docs` réussi contient la référence des automatisations en texte et ne porte pas d'indicateur d'erreur. Ajoute `"arguments":{"topic":"triggers"}` pour la référence des déclencheurs (les champs de chaque type de déclencheur, l’entrée avec laquelle ses exécutions démarrent et les événements), `"validation"` pour lire un résultat de validation et connaître chaque code d’erreur, `"settings"` pour chaque type de paramètre avec ses champs ([Paramètres par MCP](/fr/develop/mcp-settings)), ou `"skill"` pour le [skill Tale](/fr/develop/use-tale-from-your-editor#tale-skill). Pour consulter les schémas des outils, envoie plutôt `method: "tools/list"`. Conserve l'`id` JSON-RPC pour associer chaque résultat à sa requête. ### Transport et lots @@ -192,6 +192,8 @@ Chaque réponse porte un `hint` qui nomme l’outil ou le paramètre qui la fait Une modification indique son type (`kind`), l’`id` de la ressource (absent pour un type qui n’a qu’une ressource) et son opération (`op`) : `set` remplace la ressource par toute la `config` et la crée si elle n’existe pas ; `delete` la supprime ; `act` lance une des actions du type, avec ses `args`. Planifie d’abord, montre le plan à la personne, puis applique les mêmes modifications : `apply_settings` demande à la personne avant chaque appel et dispose de son propre [budget](/fr/develop/rate-limits). +[Paramètres par MCP](/fr/develop/mcp-settings) liste chaque type de paramètre, qui peut le modifier et ce qui reste dans Tale. + Aucun secret ne passe par ces outils. Un secret enregistré se lit `{"masked": true, "preview": "…"}` ; renvoie cette valeur telle quelle pour le garder. Une modification qui porte une autre valeur à la place d’un secret, ou des identifiants n’importe où dans sa configuration, est refusée avec `SECRET_ARGUMENT_REFUSED` ; une personne saisit un nouveau secret dans Tale. ### Capacités & connaissances {#capabilities} @@ -214,7 +216,7 @@ En plus des outils, le point d’accès sert des ressources, qu’un client lit | Adresse | Contenu | Se lit comme | | --- | --- | --- | -| `tale://docs/authoring`, `tale://docs/triggers`, `tale://docs/validation`, `tale://docs/skill` | Les références, en Markdown | `get_docs` avec ce `topic` | +| `tale://docs/authoring`, `tale://docs/triggers`, `tale://docs/validation`, `tale://docs/settings`, `tale://docs/skill` | Les références, en Markdown | `get_docs` avec ce `topic` | | `tale://catalog/{kind}` (`transform`, `llm`, `agent`, `subautomation`, `connector`) | La section de la référence consacrée à un type de nœud de base, ou les actions des connectors | `get_catalog` avec ce `kind` | | `tale://automations/{name}` | La dernière version enregistrée, en JSON | `get_automation` | | `tale://automations/{name}/versions/{version}` | Une version enregistrée ; `{version}` est un numéro ou `deployed` | `get_automation` avec `version` | diff --git a/docs/fr/develop/mcp-settings.md b/docs/fr/develop/mcp-settings.md new file mode 100644 index 0000000000..d548218d1c --- /dev/null +++ b/docs/fr/develop/mcp-settings.md @@ -0,0 +1,127 @@ +--- +title: Paramètres par MCP +description: Laisse un agent de code lire et modifier les paramètres de Tale par le point d’accès MCP, dans les limites du rôle de la personne dont il utilise la clé API. +--- + +Un agent de code connecté au [point d’accès MCP](/fr/develop/mcp-endpoint) lit les paramètres de ton organisation, planifie une modification et l’applique avec trois outils : `get_settings`, `plan_settings` et `apply_settings`. Il agit avec le rôle de la personne dont il utilise la clé API. Il peut modifier ce que cette personne pourrait modifier dans l’application, avec les mêmes contrôles, et les [journaux d’audit](/fr/platform/admin/governance/audit-logs) enregistrent chaque modification comme faite par cette personne, par MCP. + +## Ce qu’un agent peut modifier {#kinds} + +Tale lit et écrit chaque type de paramètre avec son propre code et les contrôles qu’applique l’application : les règles de rôle sont donc les mêmes que dans l’application. + +| Type | Ce qu’il contient | Modifications | Qui peut le modifier | +| --- | --- | --- | --- | +| `provider` | Un fournisseur IA que ton organisation a défini : son point d’accès, son format d’API et son catalogue de modèles. Les fournisseurs livrés avec Tale ne sont pas des paramètres. | Définir, supprimer ; relire son catalogue de modèles (`refresh-catalogs`) | Propriétaires, admins et développeurs | +| `provider-credential` | Des identifiants qui lisent leur clé dans une variable d’environnement du déploiement. Les identifiants avec une clé ou un abonnement sont listés sans leur secret et peuvent être supprimés. | Définir, supprimer | Propriétaires, admins et développeurs | +| `governance` | Une politique de l’organisation, désignée par sa clé : modèles et accès aux modèles, budgets et limites, sécurité de connexion et de session, garde-fous, quotas de sandbox. | Définir | Propriétaires et admins | +| `knowledge-embedding` | Le modèle d’embedding des connaissances de l’organisation, avec son seuil de similarité et ses limites d’utilisation. | Définir | Propriétaires et admins | +| `branding` | La couleur d’accentuation et les noms de fichier du logo et des favicons. | Définir | Propriétaires et admins | +| `project-instructions` | Les instructions permanentes d’un projet. | Définir | Qui peut modifier le projet | +| `agent-instructions` | Les instructions d’un agent de projet. | Définir | Qui peut modifier le projet | +| `agent-tools` | Les outils qu’un agent de projet peut utiliser. | Définir | Qui peut modifier le projet | +| `task-instructions` | La description d’une tâche. | Définir | Qui peut modifier la tâche | +| `deployment` | Les paramètres propres au déploiement, communs à toutes les organisations qu’il héberge, comme l’environnement d’exécution des sandboxes. | Définir | Tout propriétaire ou admin d’une organisation du déploiement peut les lire ; seules les adresses de la liste d’autorisation des éditeurs du déploiement peuvent les modifier | + +Une ressource a un identifiant au sein de son type : un fournisseur, son nom ; des identifiants, `/` avec le nom encodé en URI ; une politique, sa clé, comme `password_policy` ; un projet, son identifiant ; un agent, `/` ; une tâche, `/`. Le modèle d’embedding, le branding et les paramètres du déploiement n’ont pas d’identifiant. `get_settings` liste les paramètres des projets et des agents page par page, sur les projets que tu peux lire ; il ne lit la description d’une tâche que par son identifiant. + +Certaines modifications restent dans Tale : + +- Chaque secret, comme la clé API d’un fournisseur, un abonnement ou la clé du fournisseur de modération, est saisi par une personne dans Tale. +- La politique de conservation et la politique des demandes des personnes concernées changent uniquement par leurs propres procédures échelonnées. +- Les images du branding sont téléversées dans Tale. Un nom de fichier qu’un agent définit doit désigner une image déjà téléversée. +- Par MCP, le modèle d’embedding lui-même ne change que tant que les connaissances de l’organisation ne contiennent aucun document et aucun site web : ainsi, les vecteurs de deux modèles ne se rencontrent jamais dans une même recherche. Son seuil de similarité et ses limites d’utilisation changent à tout moment ; si des documents sont indexés, une personne change le modèle dans Tale. +- L’agent standard d’un projet suit la politique `standard_agent`, que modifie le type `governance` ; ses propres instructions et outils ne sont pas des paramètres. +- Aucun type ne couvre les membres, les équipes, les connectors, les skills, les compétences, les conservations légales, les journaux d’audit, les métriques ni les paramètres personnels. `get_settings` sans arguments indique ce que couvre chaque type. + +## Faire une modification {#make-a-change} + +1. Appelle `get_settings` sans arguments. La réponse liste chaque type, indique si ce déploiement le sert et si ton rôle peut le lire et le modifier. +2. Lis ce que tu veux modifier avec `get_settings` et `kinds` (et `ids`). Chaque ressource arrive avec sa `key`, sa `config` et son `hash`. +3. Planifie la modification avec `plan_settings`. Un `set` remplace toute la ressource par sa `config` : envoie donc chaque champ qui doit rester, tel que tu l’as lu. Le plan indique pour chaque modification son action, son diff, ses effets et son risque, ou le refus qui l’arrête. Rien n’est écrit. +4. Montre le plan à la personne et attends sa décision. Commence par les effets et le risque. +5. Applique les mêmes modifications avec `apply_settings`. `expected` associe la `key` de chaque ressource modifiée au hash que tu as lu, ou `null` pour une ressource que tu crées. + +Voici les arguments d’un plan qui active la rotation des mots de passe : + +```json +{ + "changes": [ + { + "kind": "governance", + "id": "password_policy", + "op": "set", + "config": { + "minLength": 12, + "requireUpper": true, + "requireLower": true, + "requireDigit": true, + "requireSpecial": true, + "rotationDays": 90 + } + } + ] +} +``` + +Le plan indique l’effet sur les membres, car la rotation fait expirer les mots de passe déjà définis. Le hash est raccourci ici : + +```json +{ + "ok": true, + "changes": [ + { + "kind": "governance", + "id": "password_policy", + "key": "governance/password_policy", + "op": "set", + "action": "update", + "currentHash": "5c1f…", + "diff": [{ "path": "/rotationDays", "before": 0, "after": 90 }], + "effects": ["may-lock-out-members"], + "risk": "critical" + } + ] +} +``` + +Pour l’appliquer, envoie les mêmes `changes` avec `"expected": { "governance/password_policy": "5c1f…" }`, en utilisant le hash complet. Avant toute écriture, chaque modification est de nouveau planifiée par rapport à ce qui est enregistré maintenant. Si l’une est refusée, ou si une ressource a changé depuis ta lecture, rien n’est appliqué. Sinon, les modifications s’exécutent dans un ordre fixe d’un type à l’autre, pour que ce à quoi une ressource fait référence existe d’abord. La première modification qui échoue arrête les suivantes, et la réponse indique ce qui a été appliqué (`applied`), ce qui a échoué (`failed`) et ce qui a été ignoré (`skipped`). Une modification déjà appliquée n’est pas annulée. + +`apply_settings` demande à la personne avant chaque appel et dispose de son propre [budget](/fr/develop/rate-limits). + +## Lire les effets d’un plan {#effects} + +Le risque d’un plan est le plus élevé entre le risque de base de son type et celui de ses effets. Voici les effets que peuvent nommer les types servis aujourd’hui : + +| Effet | Risque | Quand un plan le nomme | +| --- | --- | --- | +| `may-lock-out-members` | critical | Le verrouillage de connexion est actif après la modification, la rotation des mots de passe commence ou se raccourcit, ou l’authentification à deux facteurs devient plus stricte | +| `signs-out-members` | critical | Le délai d’inactivité est activé ou raccourci | +| `removes-human-approval` | critical | Une règle d’approbation ou une exigence de relecture ne demande plus l’avis d’une personne | +| `changes-serving-account` | high | Le point d’accès d’un fournisseur change, ou d’autres identifiants servent ses requêtes | +| `breaks-dependents` | high | Les identifiants actifs par défaut du fournisseur sont supprimés et rien ne les remplace | +| `requires-empty-corpus` | critical | Le modèle d’embedding change, ce qui exige que les connaissances de l’organisation soient vides | +| `restart-required` | critical | L’environnement d’exécution des sandboxes du déploiement change | +| `reaches-vendor` | high | Le catalogue de modèles d’un fournisseur est relu avec la clé de ton organisation | + +La référence des paramètres que `get_docs` renvoie pour le sujet `settings` (aussi `tale://docs/settings`) liste tout le vocabulaire, les champs de chaque type et chaque politique. + +## Secrets {#secrets} + +Aucun secret n’entre dans un appel de paramètres ni n’en sort. Un secret enregistré se lit `{"masked": true, "preview": "…"}`, de même que tout identifiant trouvé ailleurs dans un paramètre enregistré, par exemple une clé que quelqu’un a collée dans une politique dans Tale. Renvoie cette valeur telle quelle pour garder ce qui y est enregistré. Une modification qui contient un secret est refusée avec `SECRET_ARGUMENT_REFUSED`, qui indique où le secret a été trouvé, jamais sa valeur. Une personne saisit un nouveau secret dans Tale. + +## Quand une modification est refusée {#refusals} + +Un refus arrive sous forme de données, avec un `error`, un `code`, un `hint` et parfois `data`, jamais comme une connexion interrompue. Voici les codes qu’un agent rencontre le plus souvent : + +| Code | Ce qu’il signifie | +| --- | --- | +| `SETTINGS_STALE` | La ressource a changé depuis sa lecture. Relis-la, planifie par rapport à ce qui est enregistré maintenant et applique avec `data.currentHash`. | +| `SETTINGS_INVALID` | La configuration ne correspond pas au type. `data.issues` indique chaque problème avec son emplacement dans la configuration, y compris un champ que le paramètre ne connaît pas. | +| `SECRET_ARGUMENT_REFUSED` | La modification contient un secret. `data.places` indique où. | +| `SETTINGS_TALE_ONLY` | Cette modification se fait uniquement dans Tale, par exemple pour des identifiants avec une clé. | +| `FORBIDDEN`, `ORG_FORBIDDEN`, `FORBIDDEN_DEVELOPER_SETTINGS` | Le rôle de la personne ne permet pas non plus cette modification dans Tale. Réessayer ne sert à rien. | +| `EMBEDDING_CORPUS_NOT_EMPTY` | Le modèle d’embedding ne change que tant que les connaissances de l’organisation sont vides. `data` indique combien de documents et de sites web elles contiennent. | +| `BRANDING_IMAGE_UNKNOWN` | Un nom de fichier du branding ne désigne aucune image téléversée dans l’organisation. | +| `PROVIDER_IN_USE`, `CREDENTIAL_IN_USE` | Des identifiants désignent encore le fournisseur, ou le modèle d’embedding utilise ces identifiants. Modifie-les d’abord. | + +La référence des paramètres liste chaque code. La page du [point d’accès MCP](/fr/develop/mcp-endpoint#settings) décrit les arguments et les réponses des outils. diff --git a/docs/fr/platform/admin/overview.md b/docs/fr/platform/admin/overview.md index 3985ec1409..82819d0626 100644 --- a/docs/fr/platform/admin/overview.md +++ b/docs/fr/platform/admin/overview.md @@ -32,7 +32,7 @@ Les propriétaires et les admins gèrent les paramètres de l’organisation. Le ## Connexion, intégrations et apparence -Configure [le SSO d’entreprise](/fr/platform/admin/enterprise-sso) pour ton fournisseur d’identité et [l’authentification à deux facteurs](/fr/platform/admin/two-factor-authentication) pour protéger les comptes. Les [clés API](/fr/platform/admin/api-keys) permettent à un logiciel d’appeler Tale. +Configure [le SSO d’entreprise](/fr/platform/admin/enterprise-sso) pour ton fournisseur d’identité et [l’authentification à deux facteurs](/fr/platform/admin/two-factor-authentication) pour protéger les comptes. Les [clés API](/fr/platform/admin/api-keys) permettent à un logiciel d’appeler Tale. Un agent de code connecté avec l’une d’elles peut modifier lui-même bon nombre de ces paramètres, dans les limites du rôle de la personne à qui appartient la clé ; [Paramètres par MCP](/fr/develop/mcp-settings) indique lesquels. La page [Personnalisation visuelle](/fr/platform/admin/branding) sert à modifier le logo et les couleurs. [Sandboxes](/fr/platform/admin/sandboxes) présente la capacité d’exécution et les limites par type de tâche ; avec les [appareils de sandbox](/fr/platform/admin/sandbox-devices), les sandboxes de ton organisation tournent sur tes propres machines. Pour les accès d’un agent de projet à ces ressources, consulte [Agents côté administration](/fr/platform/admin/agents). diff --git a/docs/nav.json b/docs/nav.json index 72ac22cd83..cc525198e2 100644 --- a/docs/nav.json +++ b/docs/nav.json @@ -276,6 +276,7 @@ "develop/contributing-docker", "develop/api-reference", "develop/mcp-endpoint", + "develop/mcp-settings", "develop/use-tale-from-your-editor", "develop/webhooks", "develop/webdav-api", diff --git a/docs/published.json b/docs/published.json index d2e385b98a..f59f93baa8 100644 --- a/docs/published.json +++ b/docs/published.json @@ -45,6 +45,7 @@ "develop/contributor-setup", "develop/integrations", "develop/mcp-endpoint", + "develop/mcp-settings", "develop/overview", "develop/rate-limits", "develop/status-page", diff --git a/services/docs/app/content/frontmatter.json b/services/docs/app/content/frontmatter.json index ccda517a98..a6c7d99bec 100644 --- a/services/docs/app/content/frontmatter.json +++ b/services/docs/app/content/frontmatter.json @@ -105,6 +105,14 @@ "i18nLintExclude": "" } }, + "de:develop/mcp-settings": { + "slug": "develop/mcp-settings", + "locale": "de", + "frontmatter": { + "title": "Einstellungen über MCP", + "description": "Lass einen Coding-Agenten die Einstellungen von Tale über den MCP-Endpunkt lesen und ändern — im Rahmen der Rolle der Person, deren API-Schlüssel er nutzt." + } + }, "de:develop/overview": { "slug": "develop/overview", "locale": "de", @@ -1257,6 +1265,14 @@ "i18nLintExclude": "" } }, + "en:develop/mcp-settings": { + "slug": "develop/mcp-settings", + "locale": "en", + "frontmatter": { + "title": "Settings over MCP", + "description": "Let a coding agent read and change Tale settings through the MCP endpoint, within the role of the person whose API key it uses." + } + }, "en:develop/overview": { "slug": "develop/overview", "locale": "en", @@ -2409,6 +2425,14 @@ "i18nLintExclude": "" } }, + "fr:develop/mcp-settings": { + "slug": "develop/mcp-settings", + "locale": "fr", + "frontmatter": { + "title": "Paramètres par MCP", + "description": "Laisse un agent de code lire et modifier les paramètres de Tale par le point d’accès MCP, dans les limites du rôle de la personne dont il utilise la clé API." + } + }, "fr:develop/overview": { "slug": "develop/overview", "locale": "fr", diff --git a/services/platform/lib/mcp/settings-docs.test.ts b/services/platform/lib/mcp/settings-docs.test.ts new file mode 100644 index 0000000000..e721c77a6b --- /dev/null +++ b/services/platform/lib/mcp/settings-docs.test.ts @@ -0,0 +1,64 @@ +// @vitest-environment node + +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { SETTINGS_KINDS } from '@tale/shared/schemas/settings-kinds'; +import { describe, expect, it } from 'vitest'; + +/** + * The settings over MCP page (`docs/{en,de,fr}/develop/mcp-settings.md`) + * tables every kind of setting under the heading `{#kinds}`, in apply + * order, one kind per row in the first column. The table is written by + * hand, so a kind that ships or leaves without its row fails here instead + * of the page teaching kinds the endpoint does not serve. The pages are + * outside this workspace: `services/platform/turbo.json` hashes them for + * this suite. + */ + +const REPO_ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../..', +); + +const LOCALES = ['en', 'de', 'fr'] as const; + +/** The first backticked name of each row of the first table under the + * heading `{#kinds}`. */ +function tabledKinds(page: string): string[] { + const lines = page.split('\n'); + const heading = lines.findIndex((line) => + /^#{2,4} .*\{#kinds\}\s*$/.test(line), + ); + expect(heading, 'no heading {#kinds}').toBeGreaterThanOrEqual(0); + const start = lines.findIndex( + (line, index) => index > heading && line.startsWith('|'), + ); + expect(start, 'no table under {#kinds}').toBeGreaterThan(heading); + const rows: string[] = []; + for (const line of lines.slice(start)) { + if (!line.startsWith('|')) break; + rows.push(line); + } + // The header row and its delimiter row name no kind. + return rows.slice(2).map((row) => { + const firstCell = row.split('|')[1] ?? ''; + return /`([a-z-]+)`/.exec(firstCell)?.[1] ?? firstCell.trim(); + }); +} + +describe('the settings over MCP page tables every kind', () => { + it.each(LOCALES.map((locale) => [locale] as const))( + 'docs/%s/develop/mcp-settings.md names exactly the kinds served, in apply order', + (locale) => { + const page = readFileSync( + path.join(REPO_ROOT, 'docs', locale, 'develop/mcp-settings.md'), + 'utf8', + ); + expect(tabledKinds(page)).toEqual( + SETTINGS_KINDS.map((descriptor) => descriptor.kind), + ); + }, + ); +}); diff --git a/services/platform/turbo.json b/services/platform/turbo.json index e63e26e6d0..c966644622 100644 --- a/services/platform/turbo.json +++ b/services/platform/turbo.json @@ -30,6 +30,7 @@ "!$TURBO_ROOT$/configs/platform/**/.turbo/**", "!$TURBO_ROOT$/configs/platform/**/*.tsbuildinfo", "$TURBO_ROOT$/docs/*/develop/mcp-endpoint.md", + "$TURBO_ROOT$/docs/*/develop/mcp-settings.md", "$TURBO_ROOT$/docs/*/platform/admin/connectors.md", "$TURBO_ROOT$/docs/*/platform/connectors/overview.md", "$TURBO_ROOT$/docs/*/platform/projects/tasks.md", From 17b9be734a6cebf3346b2366fe1a104485793714 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 10:00:25 +0200 Subject: [PATCH 31/35] docs(manual): box settings through a coding agent The MCP suite gains a section for settings: MCP-F9 changes the branding and turns on password rotation through Claude Code, judging the plan's effect, the question before apply_settings, the pages after a reload and the audit rows' Coding agent source; MCP-B1 holds a member's agent to what a member may change; MCP-B2 refuses a key pasted into the system prompt without repeating it. The suite's cost moves to 15 boxes. The error-code map provokes every settings refusal, and the coverage map names the tests that own the settings tools and kinds. --- .../tests/manual/reference/automation.md | 2 ++ .../tests/manual/reference/error-codes.md | 9 +++++ services/platform/tests/manual/suites/mcp.md | 34 ++++++++++++++++++- 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 99d4d2ce74..de5e795dbe 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -497,6 +497,8 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [mcp](../suites/mcp.md) | Resources, prompts and the Tale skill (MCP-R24, MCP-R25): `initialize` advertising resources and prompts; `resources/list` naming the five references (`tale://docs/{authoring,triggers,validation,settings,skill}`), the five catalog kinds and then the automations `list_automations` answers the key holder, 100 a page with a cursor it issued (a forged one refused `-32602`); `resources/templates/list` and `prompts/list` answered whole; `resources/read` going through the matching tool call (`get_docs` with its `topic`, `get_catalog`, `get_automation` with a percent-encoded name and a version number or `deployed`, `get_run`) with its checks, answering a refusal as `-32002` with `data.code` (a hidden automation exactly like a missing one), a malformed or over-long address as `-32602` without echoing it, a fault as `-32603` with the request id; `prompts/get` (`edit_automation`, `debug_failed_run`, `add_trigger`) attaching what it is about, read as the caller, refusing one whose required read fails, its arguments one word each; reads, listings and prompts charged like tool calls after the first of a batch and counted per method without the address; the lines of prompts, instructions and skill naming exactly the tools they declare and only addresses the server reads; `get_docs {topic}` and `get_catalog`'s core-kind `reference`; the triggers reference built from the trigger schema, the raised events and the backend's delivery constants; the validation reference listing every issue code once; the skill within the Agent Skills limits, MIT, the contract version, deployment-agnostic (a reviewed snapshot), and `GET /api/app/mcp/skill` serving the same bytes as `SKILL.md` to a session only | ✅ unit + integration | `lib/mcp/resources.test.ts`, `lib/mcp/prompts.test.ts`, `lib/mcp/skill.test.ts` (`skill.snapshot.md`), `lib/mcp/docs/triggers.test.ts`, `lib/mcp/docs/validation.test.ts`, `lib/mcp/instructions.test.ts`, `lib/mcp/contract.test.ts`, `backend/domains/mcp/resources.test.ts`, `backend/domains/mcp/prompts.test.ts`, `backend/domains/mcp/routes.test.ts`, `backend/domains/mcp/docs.test.ts`, `lib/engine/selftest/dispatch.test.ts`, `lib/engine/api/dispatch.refusals.test.ts`, the `checkMcpResourcesPrompts` lane in `backend:integration`; Claude Code's `/tale:` menu, `@tale:` mentions and the installed skill stay manual (`MCP-F3`, `MCP-F7`, `MCP-F8`, `MCP-F11`) | | [mcp](../suites/mcp.md) | Both protocol eras on one endpoint (MCP-R16, MCP-R26): a message whose `params._meta` names its revision, or whose `MCP-Protocol-Version` names 2026-07-28, served on the modern rules and everything else as before; on 2026-07-28 a header naming another revision than the body (`-32020`), a missing or malformed `_meta` envelope (`-32602`, `data.missing`/`data.malformed`), a revision it does not speak (`-32022` listing all four, a legacy one in `_meta` told to use `initialize`), then a missing `MCP-Protocol-Version`, a missing or contradicting `Mcp-Method` or `Mcp-Name` (decoded from `=?base64?…?=`, refused when not Base64 or not UTF-8) refused with 400 before anything runs; `server/discover` answering the four revisions, the capabilities, the instructions and the server; `initialize`, `ping` and unknown methods 404 `-32601`; one message per request (a batch naming 2026-07-28 refused whole); every result `resultType: "complete"` with the server under `_meta`, `ttlMs` + `cacheScope: "private"` on discover, the lists and reads (an hour for what a release fixes, a minute for the resource list and the connector catalog, nothing for an automation or a run); a read that finds nothing `-32602` with the tool's code; the client's name from each request's `_meta` reaching the call record, the audit channel and the engine; `initialize` never negotiating 2026-07-28; on the real door, legacy and modern calls interleaved on one key | ✅ unit + integration | `backend/domains/mcp/eras.test.ts`, `backend/domains/mcp/protocol.test.ts`, `lib/mcp/resources.test.ts`, `lib/mcp/contract.test.ts`, the `checkMcpEras` lane in `backend:integration`; a real 2026-07-28 client (Claude Code) beside a legacy one stays manual (`MCP-F12`) | | [mcp](../suites/mcp.md) | No tool decides an approval (MCP-R6): the MCP door's module graph, walked from `backend/rest/v1-mcp.ts` through every static and literal dynamic import, never reaches the approvals domain (`decideApproval` and the session routes that call it); no tool, prompt or resource address is named for an approval, and `answer_run_ask` takes only a run, a question and an answer; a capability whose run waits is answered as the waiting run, not flagged as an error and not a decision | ✅ unit | `backend/domains/mcp/approvals.test.ts`; a real gated step reached from a coding agent and decided in Tale stays unproven end to end | +| [mcp](../suites/mcp.md) / [settings](../suites/settings.md) | Settings over MCP, the tools (MCP-R11, MCP-R12): `get_settings` answering without `kinds` the catalog — every kind with its ops, acts, base risk, the Settings pages it covers, whether it is served and what the caller's role may do — and with `kinds` each resource with its key, config and native hash, a kind it may not read under `refused`; `plan_settings` answering each change's action, member-by-member diff, effects and risk (the highest of the kind's base risk and its effects') or its refusal, writing nothing; `apply_settings` refusing an `expected` that misses or names a resource beyond the call (`INVALID_ARGUMENTS`), planning every change again against fresh reads and applying nothing when one is refused or moved (`SETTINGS_STALE` with `data.currentHash`), then applying in the kinds' order and stopping at the first failure with what was applied, failed and skipped, a writer's own version conflict answered as stale, a fault as `INTERNAL_ERROR` with the request id; no secret in or out — a value at a kind's secret path or anything the credential detector recognises refused with its pointer (`SECRET_ARGUMENT_REFUSED`), every stored secret and every detected credential read masked, a masked value sent back keeping what is stored and refused where nothing masked is stored; one change per resource (`SETTINGS_DUPLICATE`); every Settings page held to a kind or a reason; the settings reference (`tale://docs/settings`) listing every kind's fields, every policy, every effect and every refusal a handler raises; the skill's settings lines and the docs page's kinds table held to the descriptors | ✅ unit | `backend/domains/mcp/settings/settings.test.ts`, `backend/domains/mcp/settings/secrets.test.ts`, `backend/domains/mcp/settings/kit.test.ts`, `backend/domains/mcp/settings/diff.test.ts`, `backend/domains/mcp/settings/coverage.test.ts`, `backend/domains/mcp/settings/handlers.test.ts`, `lib/mcp/docs/settings.test.ts`, `lib/mcp/skill.test.ts`, `lib/mcp/instructions.test.ts`, `lib/mcp/contract.test.ts`, `lib/mcp/settings-docs.test.ts`, `lib/mcp/endpoint-docs.test.ts`; a real coding agent planning, asking and applying stays manual (`MCP-F9`, `MCP-B1`, `MCP-B2`) | +| [mcp](../suites/mcp.md) / [settings](../suites/settings.md) | Settings over MCP, the kinds (MCP-R10, MCP-R14, MCP-R28): every kind read and written through its Settings page's writer and gate — policies (a member reads the member-readable ones and changes none; the retention and data subject request policies refused as Tale-only; the standard agent's runtime and the sandbox capacity checked as the save checks them; effects for lockouts, sign-outs and loosened approvals), the embedding model (owners and admins; a model change only on an empty corpus, `EMBEDDING_CORPUS_NOT_EMPTY`; its audit row, KNOW-R19), the branding (owners and admins; the old colour field read as the page shows it; file names only of uploaded images, `BRANDING_IMAGE_UNKNOWN`), the deployment settings (read by any organization's owner or admin, changed by the editor allowlist; a new sandbox runtime flagged `restart-required`), the organization's own providers (owners, admins and developers; endpoint changes flagged; a removal refused while credentials name the provider; `refresh-catalogs` without the provider's words), provider credentials (every credential listed without its secret; only environment credentials created or changed; a removal checked against the hash read inside its transaction; a removal refused while the embedding model uses it), and a project's, an agent's and a task's managed text (the project's and the task's own rules checked before anything is written; a standard agent refused; tasks read by id); the branding door's role gate (BRAND-R5) and the provider refresh door characterised before their writers were lifted; on a real database, an owner's agent changing a policy, the branding, a provider, its credential, the embedding model and a project's instructions, each leaving its page's audit row stamped `via: mcp`, `tool: apply_settings`, while a member's agent and a stale read are refused | ✅ unit + integration | `backend/domains/governance/settings-resource.test.ts`, `backend/domains/knowledge/settings-resource.test.ts`, `backend/domains/knowledge/embedding-audit.test.ts`, `backend/domains/branding/settings-resource.test.ts`, `backend/domains/branding/routes.test.ts`, `backend/domains/deployment/settings-resource.test.ts`, `backend/domains/providers/settings-resource.test.ts`, `backend/domains/providers/config-routes.test.ts`, `backend/domains/provider_credentials/settings-resource.test.ts`, `backend/domains/projects/settings-resource.test.ts`, `backend/domains/tasks/settings-resource.test.ts`, the `checkMcpSettingsConfig` lane in `backend:integration` | | [automations](../suites/automations.md) | Definition writes audited and attributed (AUTO-R27, AUTO-R28): every saved version, deploy, delete, trigger set or removed and installation added or removed writes one `workflow` audit row in its own transaction, after the organization's audit chain and before the name and the trigger row, naming versions, kinds and project ids but never a document, a webhook token or its hash, and none for a change that changed nothing; a version records the door, key and client it was saved through (0181) and the REST version list keeps its documented fields; an automation installed only in projects the key holder cannot read is left out of `GET /api/v1/automations` and answers 404 on its read, versions and triggers | ✅ unit | `backend/domains/automations/audit.test.ts`, `backend/domains/automations/store.definition-audit.test.ts`, `backend/domains/automations/store.save-version.test.ts`, `backend/rest/v1-automations.contract.test.ts`, `backend/rest/v1-automations.project-scope.test.ts` | | [projects](../suites/projects.md) | REST chat lifecycle: door-side model resolution (`CHAT_MODEL_UNKNOWN` / `CHAT_MODEL_AMBIGUOUS`), model facts and the default marker on `GET /models`, message `status` (a stop settles as `cancelled`) and `usage` (`costEstimateCents` included), the 202’s pre-minted `messageId` and the `queued` poll state until the worker opens the turn, streaming progress on the poll (`since` and `reasoningSince` slice the text and the reasoning independently, each with its offset/length pair and the reset-to-0 rule), `reasoningEffort` / `maxOutputTokens` on a send (a cap above the model’s ceiling refused; the cap a per-turn budget the tool rounds share — a later round gets what the earlier ones left, a round with nothing left is not run, a cut round marks the turn `finishReason: length` and its calls settle `invalid_args` unrun), `usage.costEstimateCents` rounded to a millionth of a cent, a named `locale` asking for the reply language on the system prompt and on the message (`localeFixed` through the job into the runtime directive and the wire-only notice; the app lane untouched), archive with `archivedAt` echoed from the domain’s own stamp / rename / delete / cancel routes, the stop of a send still queued (202 `cancelling` → a `cancelled` reply without a model call) and the 404’s `data.lastMessageId` / `data.lastStatus`, hidden regenerate-siblings invisible by id, blank-prompt and locale refusals | ✅ automated | `backend/rest/v1-threads.test.ts`, `backend/rest/v1-threads.contract.test.ts`, `backend/rest/v1-threads.scope.test.ts`, `backend/domains/chat/rest-turn.test.ts`, `backend/domains/chat/store.test.ts`, `lib/chat/turn.test.ts`, `lib/chat/context.test.ts`, `lib/chat/effort.test.ts`, `lib/chat/tools.test.ts`, `lib/shared/utils/language-name.test.ts`, `scripts/openapi/spec.test.ts`, the `REST resources` lane in `backend:integration` (the queued stop and the 404’s data on the real schema) | | [projects](../suites/projects.md) | REST contract guards: every handler code is in the error-code registry the OpenAPI `Error.code` enum publishes, every `/api/v1` operation documents `X-Organization-Slug`, `/openapi.json` binds `servers` to the request origin, knowledge hits carry `documentId` | ✅ automated | `backend/rest/error-codes.test.ts`, `scripts/openapi/spec.test.ts`, `server.test.ts`, `backend/domains/knowledge/service.document-ids.test.ts` | diff --git a/services/platform/tests/manual/reference/error-codes.md b/services/platform/tests/manual/reference/error-codes.md index eb96f8eb60..20a304daba 100644 --- a/services/platform/tests/manual/reference/error-codes.md +++ b/services/platform/tests/manual/reference/error-codes.md @@ -185,6 +185,15 @@ Never a rendered message — seeing one of these in the UI is itself a bug. | `AUTOMATION_NOT_INSTALLED` (MCP tool refusal) | `tools/call` `set_automation_projects` with `remove` naming a project the automation is not installed in; nothing changes, the other projects in the call included. | | `HUMAN_ASK_NOT_FOUND` / `HUMAN_ASK_NOT_PENDING` / `HUMAN_ASK_EXPIRED` (MCP tool refusal) | `tools/call` `answer_run_ask` with an `askId` the run never asked, a question already answered, or one past its expiry; the run stays where it is. `EMPTY_ANSWER` is the same tool's refusal of a blank answer when the call skips the argument check. | | `INVALID_CURSOR` (MCP tool refusal) | `tools/call` `list_runs` with a `cursor` edited by one character, one `list_runs` answered for other filters, or one from another organization; the first page is not repeated. | +| `SETTINGS_STALE` (MCP settings refusal) | Read a setting with `get_settings`, change it on its Settings page, then `tools/call` `apply_settings` naming the hash you read under `expected`: flagged `isError`, `data.currentHash` is the hash now, `failed` names the resource and nothing in the call is applied. A writer that finds the hash moved under its own lock answers the same. | +| `SECRET_ARGUMENT_REFUSED` (MCP settings refusal) | `plan_settings` (or `apply_settings`) with `sk-test-0000000000000000000000000000` anywhere in a change, such as the `mandatoryInstructions` of `governance/system_prompt` (MCP-B2), or `{"masked": true}` where nothing is stored: `data.places` names each pointer and what was found there, never the value; nothing is applied. | +| `SETTINGS_INVALID` / `SETTINGS_ID_INVALID` / `SETTINGS_ID_REQUIRED` / `SETTINGS_DUPLICATE` (MCP settings refusal) | `plan_settings` with `governance/password_policy` and `{"minLenght": 14}` (`data.issues` names `/config/minLenght` as a field the setting does not have), a `provider` change whose `id` is not its config's `name`, a `provider` change without an id, or the same resource twice in one call. Nothing is written. | +| `SETTINGS_TALE_ONLY` (MCP settings refusal) | `plan_settings` with `governance/retention_policy`, or a `provider-credential` change whose `authMethod` is `api-key`: the hint says where in Tale the change is made; nothing is written. | +| `SETTINGS_IDS_REQUIRED` (MCP settings refusal) | `get_settings` with `kinds: ["task-instructions"]` and no `ids`: listed under `refused`; the same call with `ids: ["/"]` reads the task. | +| `SETTINGS_NOT_FOUND` / `SETTINGS_KIND_UNAVAILABLE` (MCP settings refusal) | `plan_settings` with `{"kind": "provider", "id": "nope", "op": "act", "act": "refresh-catalogs"}` for a provider the organization never defined. `SETTINGS_KIND_UNAVAILABLE` is not reachable on a deployment that serves every kind; it answers a kind without a handler. | +| `EMBEDDING_CORPUS_NOT_EMPTY` (MCP settings refusal, 409) | With at least one document uploaded, `plan_settings` a `knowledge-embedding` change of `model` (a change of `minSimilarity` alone is planned): `data` names how many documents and websites the knowledge base holds; nothing is written. Changing the model in Settings > Data residency still works. | +| `BRANDING_IMAGE_UNKNOWN` (MCP settings refusal) | `plan_settings` a `branding` change whose `logoFilename` is `logo.png` when no logo was uploaded (or `../logo.svg`): the hint sends the person to Settings > Branding; nothing is written. | +| `UNKNOWN_POLICY_TYPE` / `PROJECT_AGENT_MANAGED` / `PROVIDER_IN_USE` / `CATALOG_REFRESH_FAILED` (MCP settings refusals) | `plan_settings` with `governance/conversation_access`; an `agent-instructions` change of a project's standard agent; a `provider` delete while a credential still names the provider; `apply_settings` of `refresh-catalogs` for a provider whose endpoint does not answer (the answer never repeats what the provider said). | | JSON-RPC `-32022` (400) on `/api/v1/mcp` | Any request with `MCP-Protocol-Version: 2024-11-05`, or a 2026-07-28 request whose `params._meta` names `io.modelcontextprotocol/protocolVersion: "2027-01-01"` (header and body alike): the error names the revisions the endpoint speaks under `data.supported` (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`) and the revision asked for under `data.requested` (at most 128 characters), and echoes the message's own `id`. A `_meta` naming `2025-11-25` gets it too, saying that revision is opened with `initialize`. Before 3.21.0 this was `-32600`. | | JSON-RPC `-32020` (400) on `/api/v1/mcp` | A 2026-07-28 request (its `params._meta` names `io.modelcontextprotocol/protocolVersion: "2026-07-28"` and carries `io.modelcontextprotocol/clientCapabilities: {}`) whose headers do not say what its body says: `MCP-Protocol-Version: 2025-11-25`, no `Mcp-Method` or one naming another method, or a `tools/call` `get_run` sent with `Mcp-Name: cancel_run` (or without `Mcp-Name`, or with `Mcp-Name: =?base64?not base64?=`). "Header mismatch" names which header; nothing runs. New in 3.21.0. | | JSON-RPC `-32602` (400) on `/api/v1/mcp`, 2026-07-28 envelope | `tools/list` with `MCP-Protocol-Version: 2026-07-28` and no `params._meta`: `data.missing` names `io.modelcontextprotocol/protocolVersion` and `io.modelcontextprotocol/clientCapabilities`; capabilities sent as an array (or `clientInfo` as a string) are named under `data.malformed`. New in 3.21.0. | diff --git a/services/platform/tests/manual/suites/mcp.md b/services/platform/tests/manual/suites/mcp.md index e54e6d3c4e..99392c14e0 100644 --- a/services/platform/tests/manual/suites/mcp.md +++ b/services/platform/tests/manual/suites/mcp.md @@ -1,6 +1,6 @@ # MCP -> **Prefix** `MCP-` · **Reset** none · **Cost** 12 boxes +> **Prefix** `MCP-` · **Reset** none · **Cost** 15 boxes Exercise Tale's MCP endpoint, `/api/v1/mcp`, from a real coding agent: connecting a client with an API key and working in the organization through it. A person drives the agent in a terminal beside @@ -133,6 +133,38 @@ earlier boxes left. calls `answer_run_ask`; after you accept, the run in `/dashboard/{org}/automations/{slug}/runs` leaves **Waiting** and goes on with your answer. +## Settings through the agent + +These boxes reuse `MCP-F1`'s Claude Code connection. They change the organization's branding and +password policy; put both back by hand afterwards if the organization is shared. + +- [ ] `MCP-F9` · **Change settings through the agent** — Ask the agent to set the organization's + accent color to `#1A6B4F` and to turn on password rotation every 90 days → before it changes + anything, the agent shows you a plan whose password change names the effect + `may-lock-out-members` and the risk `critical`; Claude Code asks you before it calls + `apply_settings`; after you accept, a reload of **Settings > Branding** shows `#1A6B4F` as the + **Accent color** (`settings.branding.accentColor`), and **Settings > Governance > Security** + shows **Enable password rotation** (`governance.passwordPolicy.rotationEnabled`) on with a + **Rotation period (days)** (`governance.passwordPolicy.rotationDays`) of 90; in + **Settings > Governance > Logs** the newest **Branding updated** row + (`settings.logs.audit.actionLabels.branding.updated`) and the newest row of the password policy + show **Source** (`settings.logs.audit.viaLabel`) as **Coding agent** + (`settings.logs.audit.viaLabels.mcp`). +- [ ] `MCP-B1` · **A member's agent is refused what a member is refused** — As an owner, give a + member the developer role, sign in as that member, create an API key under **Settings > API > + REST**, sign back in as the owner and set the member's role back to member; connect Claude Code + with the member's key as in `MCP-F1` and ask the agent to raise the password policy's minimum + length to 14 → the agent reports the change refused with Tale's reason, without retrying; as + the owner, **Settings > Governance > Security** still shows the earlier **Minimum length** + (`governance.passwordPolicy.minLength`), and **Settings > Governance > Logs** has no new row of + the password policy. +- [ ] `MCP-B2` · **A key pasted into a setting is refused** — With the owner's connection, ask the + agent to add `sk-test-0000000000000000000000000000` to the organization's system prompt in + **Settings > Governance > Guardrails** → the agent reports the change refused because it + carries a secret, naming the field and never repeating the key; a reload of the Guardrails page + shows the system prompt unchanged, and searching **Settings > Governance > Logs** for `sk-test` + finds nothing. + ## What the organization sees - [ ] `MCP-F13` · **Find the agent's save in the audit log** — After `MCP-F3`, sign in as an From b3bc25b0379ab7572f3b378070ea29e9e0d754d5 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 11:24:46 +0200 Subject: [PATCH 32/35] test(shared): drop a needless assertion from the schedule convergence case --- packages/shared/src/config/platform-resources.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/shared/src/config/platform-resources.test.ts b/packages/shared/src/config/platform-resources.test.ts index 39695f9868..2274790d76 100644 --- a/packages/shared/src/config/platform-resources.test.ts +++ b/packages/shared/src/config/platform-resources.test.ts @@ -335,7 +335,7 @@ describe('the embedding floor in a declaration', () => { }, }, ], - }).resources[2]!; + }).resources[2]; // The readback: the rule in the normal form the platform stores, the // zone as the declaration spells it. const stored = { From 42ebb7e00ee4fbd9240f7069970629caee3efcb3 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 11:24:50 +0200 Subject: [PATCH 33/35] refactor(platform): keep the settings kit's parse helpers private Only the kit's own config parser calls them, so knip reported them as unused exports. --- services/platform/backend/domains/mcp/settings/kit.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/platform/backend/domains/mcp/settings/kit.ts b/services/platform/backend/domains/mcp/settings/kit.ts index d215aafc53..12efdd0fab 100644 --- a/services/platform/backend/domains/mcp/settings/kit.ts +++ b/services/platform/backend/domains/mcp/settings/kit.ts @@ -70,7 +70,7 @@ interface ParseFailure { } /** The problems of a failed parse, as issues of the change. */ -export function configIssues(error: ParseFailure): SettingsIssue[] { +function configIssues(error: ParseFailure): SettingsIssue[] { return error.issues.map((issue) => ({ path: configPointer(issue.path), code: issue.code, @@ -109,7 +109,7 @@ export function droppedMembers( } /** The refusal of a change whose config its kind does not take. */ -export function invalidSettings( +function invalidSettings( what: string, issues: readonly SettingsIssue[], ): SettingsRefusalError { From bf276973c0003737966bd6c006919068092215e3 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 11:26:04 +0200 Subject: [PATCH 34/35] test(platform): name the review-context addition apart from the change helper --- .../backend/domains/tasks/settings-resource.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/platform/backend/domains/tasks/settings-resource.test.ts b/services/platform/backend/domains/tasks/settings-resource.test.ts index 4ba7e92e01..15de2b536f 100644 --- a/services/platform/backend/domains/tasks/settings-resource.test.ts +++ b/services/platform/backend/domains/tasks/settings-resource.test.ts @@ -255,7 +255,7 @@ describe("a task's review context over MCP", () => { }); it('adds one through its writer, compare-and-set on the hash read', async () => { - const change = { + const addition = { kind: 'task-review-context' as const, op: 'set' as const, config: context, @@ -263,7 +263,7 @@ describe("a task's review context over MCP", () => { const answer = await applySettings( contextOf('editor'), registry, - [change], + [addition], { 'task-review-context/p-1/t-1': configurationHash(null), }, @@ -280,7 +280,7 @@ describe("a task's review context over MCP", () => { const stale = await applySettings( contextOf('editor'), registry, - [{ ...change, config: { ...context, enabled: false } }], + [{ ...addition, config: { ...context, enabled: false } }], { 'task-review-context/p-1/t-1': configurationHash(null) }, ); expect(stale).toMatchObject({ code: 'SETTINGS_STALE', applied: [] }); From a329c67797c0bfb8135c8ffab43aa74684ff4c7e Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 10 Oct 2026 11:28:35 +0200 Subject: [PATCH 35/35] test(platform): count the settings kinds the lane expects from their descriptors --- .../platform/backend/domains/mcp/settings.integration.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/platform/backend/domains/mcp/settings.integration.ts b/services/platform/backend/domains/mcp/settings.integration.ts index 230c18046b..7f305bc8e8 100644 --- a/services/platform/backend/domains/mcp/settings.integration.ts +++ b/services/platform/backend/domains/mcp/settings.integration.ts @@ -10,6 +10,7 @@ import { randomUUID } from 'node:crypto'; +import { SETTINGS_KINDS } from '@tale/shared/schemas/settings-kinds'; import type { Sql } from 'postgres'; import { z } from 'zod'; @@ -194,12 +195,12 @@ export async function checkMcpSettingsConfig( record( 'MCP get_settings serves every kind, and says what the role may do with each (MCP-R10)', ownerKinds.success && - ownerKinds.data.length === 10 && + ownerKinds.data.length === SETTINGS_KINDS.length && ownerKinds.data.every((entry) => entry.available) && access(ownerKinds, 'governance') === '[[true,true]]' && access(memberKinds, 'governance') === '[[true,false]]' && access(memberKinds, 'branding') === '[[false,false]]', - `owner=${ownerKinds.success ? ownerKinds.data.length : 'unread'} kinds, member governance=${access(memberKinds, 'governance')}, member branding=${access(memberKinds, 'branding')}`, + `owner=${ownerKinds.success ? ownerKinds.data.length : 'unread'} of ${SETTINGS_KINDS.length} kinds, member governance=${access(memberKinds, 'governance')}, member branding=${access(memberKinds, 'branding')}`, ); // A policy: the owner's agent changes it, a member's is refused, and a