Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .changeset/37102-knowledge-capability-token.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@objectstack/spec': minor
'@objectstack/core': minor
'@objectstack/cli': minor
'@objectstack/verify': minor
'@objectstack/service-knowledge': minor
'@objectstack/knowledge-turso': minor
'@objectstack/service-settings': patch
---

feat(core): `requires: ['knowledge']` mounts the knowledge service and one vector store

Clause-②: yes
Metadata-protocol: added
Skills-docs: follow-up #37310

ADR-0161, #37102.

- **New capability token `knowledge`** (`PLATFORM_CAPABILITY_TOKENS`, provider `@objectstack/service-knowledge`, edition `open`). `os serve` and `@objectstack/verify` mount `KnowledgeServicePlugin` plus exactly one store, picked from the primary database: PostgreSQL gets `KnowledgePgvectorPlugin` (adapter `pgvector`, on the same database URL); any other database gets `KnowledgeTursoPlugin` (adapter `turso`) on a local libSQL file, `knowledge.db` in the directory of the default database: `.objectstack/data/`, or `<OS_HOME>/data/` when `OS_HOME` is set (`os start --home` sets it). An in-memory database gets an in-memory turso store. The in-memory adapter (`knowledge-memory`) is never mounted by the token.
- No token: no knowledge service and no knowledge settings page, as before. A host that mounts `KnowledgeServicePlugin` itself keeps its own and gets no store from the runtime; a host that mounts only the store the token would choose keeps that store and gets the service.
- New core exports: `resolveCapabilityExtras`, `resolveKnowledgeStore`, `KNOWLEDGE_STORE_PROVIDERS` and the `CapabilityDatabase` / `CapabilityExtra` / `KnowledgeStoreSpec` types. `constructServedProviders` (`@objectstack/verify`) takes an optional `database` (default: in-memory SQLite).
- `os serve` now warns when a capability's extra plugin cannot be imported or constructed, instead of skipping it silently.
- **A source whose adapter is not mounted** no longer fails silently. The service still mounts and boot does not fail; after boot the service logs one `error` per such source naming the mounted adapters, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same message. A search across several sources names the refused one beside the hits of the others. Before, indexing threw an uncoded error and search skipped the source with a warning.
- **The turso store reads its URL from settings under the token.** `KnowledgeTursoPlugin` gains `urlFromSettings`: with no `url` option it reads the saved `knowledge.turso_url` / `turso_auth_token`. It reads them when the boot completes (`kernel:bootstrapped`), the first moment the settings service answers a saved value; the adapter is mounted from `start()` and answers `SERVICE_UNAVAILABLE` until the store has opened. A saved `file:` URL must resolve, after symlinks, inside that data directory; a URL that leaves it, names the platform database, or carries a NUL byte or another control character, written out or percent-encoded (`%00`, `%0a`), is refused before the libSQL client sees it (the client decodes the path, and a NUL byte in it kills the process inside the native library). New option `stateDir` (the token passes `OS_HOME`); new exports: `resolveSettingsStoreUrl`, `dataDirectoryOf`. `resolveStoreUrl` refuses control characters too, in both spellings. An auth token carrying a control character (a pasted line break, a NUL byte), saved or given as the `authToken` option, is refused the same way, read as written: the store answers `SERVICE_UNAVAILABLE` with a reason that never quotes the token.
- **`@objectstack/knowledge-turso` is an optional dependency of `@objectstack/cli` and `@objectstack/verify`**, not a hard one: its libSQL client is a native module with an `os` / `cpu` list, and a hard dependency would refuse the whole install outside that list. Where it is absent `os serve` warns that the store was not mounted and boots on, `@objectstack/verify` does the same, and a source naming `turso` answers `SERVICE_UNAVAILABLE`. `KNOWLEDGE_STORE_PROVIDERS.turso` and the extra `resolveCapabilityExtras` answers for it carry `optional: true`.
- The `turso_url` setting's example path now reads `file:./.objectstack/data/knowledge.db` in every locale.
32 changes: 30 additions & 2 deletions content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,35 @@ ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable bac
**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-pgvector`, `@objectstack/knowledge-turso`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge).
</Callout>

## Wiring
## Turning it on: `requires: ['knowledge']`

Add `knowledge` to your app's `requires`, and `os dev`, `os serve` and `os start` mount the knowledge service and one vector store for you — and in an app's tests, `bootStack` from `@objectstack/verify` mounts the same:

```ts
export default defineStack({
// …
requires: ['knowledge'],
});
```

Which store is mounted depends on the platform database:

| Platform database | Store | Adapter id | Where the vectors live |
|:--|:--|:--|:--|
| PostgreSQL | `@objectstack/knowledge-pgvector` | `pgvector` | the platform database, schema `os_knowledge` ([below](#self-hosted-vector-store-postgresql--pgvector)) |
| anything else (SQLite under `os dev`, libSQL, MySQL, MongoDB) | `@objectstack/knowledge-turso` | `turso` | `knowledge.db` in the directory of the default database and never its file: `.objectstack/data/`, or `<OS_HOME>/data/` when `OS_HOME` is set ([below](#local-vector-store-a-libsql-file)) |

- **Sources are still written in code**: register them on the `knowledge` service from your own plugin, and name the adapter of the store your database gets (`adapter: 'turso'` or `adapter: 'pgvector'`).
- **A source naming a store that is not mounted** does not stop the boot: the server logs one error naming the source and the stores that are mounted, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same choices; `search_knowledge` lists it in `refused`.
- **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)).
- **Another libSQL store** for the `turso` case: save its URL as `turso_url` (and `turso_auth_token` for a managed `libsql://` database) in Settings → Knowledge, then restart. A `file:` URL saved there must name a file inside that same data directory, and a URL carrying a NUL byte or another control character, written out or percent-encoded (`%00`), is refused, as is a token carrying one (a pasted line break counts); either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on.
- **Where the file is**: `os start --home` and `OS_HOME` move it with the default database, so on a container put `OS_HOME` on a volume and the index survives a redeploy. A database named by URL (`OS_DATABASE_URL`) does not move it.
- **More than one replica** on MySQL, MongoDB or a remote libSQL database: each replica keeps its own local `knowledge.db` and indexes only the record writes that replica itself handles, so replicas answer from indexes that differ. Give them one store: save a shared `libsql://` URL in `turso_url`, or run on PostgreSQL, where the vectors live in the one database.
- **An install without the libSQL client**: `@objectstack/knowledge-turso` is an optional dependency of the CLI, because its client is a native module. Where it could not be installed the server warns at boot that the store was not mounted, and sources naming `turso` answer `SERVICE_UNAVAILABLE`.
- **Without the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you.
- **Mounting it yourself** still works: an app whose `plugins` already hold `KnowledgeServicePlugin` keeps its own, and the runtime adds neither a second service nor a store.

## Wiring by hand

```ts
import { ObjectKernel } from '@objectstack/core';
Expand Down Expand Up @@ -275,7 +303,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds —

## Local vector store: a libSQL file

`@objectstack/knowledge-turso` keeps passages and vectors in a libSQL file of its own — by default `knowledge.db` under the project's `.objectstack/data/`, never the platform database's file — so a deployment on SQLite gets semantic search, Chinese text included, with no database server to run. Until `os dev` mounts it for you, add the package and register `KnowledgeTursoPlugin` beside the knowledge service yourself. Point a source at it with `adapter: 'turso'`:
`@objectstack/knowledge-turso` keeps passages and vectors in a libSQL file of its own — by default `knowledge.db` under the project's `.objectstack/data/`, never the platform database's file — so a deployment on SQLite gets semantic search, Chinese text included, with no database server to run. `requires: ['knowledge']` mounts it on any database but PostgreSQL; to wire it by hand, register `KnowledgeTursoPlugin` beside the knowledge service. Point a source at it with `adapter: 'turso'`:

```ts
new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
"@objectstack/driver-sql": "workspace:*",
"@objectstack/driver-sqlite-wasm": "workspace:*",
"@objectstack/formula": "workspace:*",
"@objectstack/knowledge-pgvector": "workspace:*",
"@objectstack/lint": "workspace:*",
"@objectstack/mcp": "workspace:*",
"@objectstack/metadata": "workspace:*",
Expand All @@ -146,6 +147,7 @@
"@objectstack/service-cache": "workspace:*",
"@objectstack/service-datasource": "workspace:*",
"@objectstack/service-job": "workspace:*",
"@objectstack/service-knowledge": "workspace:*",
"@objectstack/service-mailbox": "workspace:*",
"@objectstack/service-messaging": "workspace:*",
"@objectstack/service-package": "workspace:*",
Expand Down Expand Up @@ -184,6 +186,7 @@
}
},
"optionalDependencies": {
"@objectstack/knowledge-turso": "workspace:*",
"better-sqlite3": "^13.0.3"
},
"devDependencies": {
Expand Down
64 changes: 50 additions & 14 deletions packages/cli/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ import {
providesCapability,
resolveServedCapabilities,
resolveCapabilityArgument,
resolveCapabilityExtras,
type CapabilityDatabase,
materializeStackPlugin,
STACK_TIER_PRESETS,
CAPABILITY_TO_TIER as SHARED_CAPABILITY_TO_TIER,
Expand Down Expand Up @@ -2765,6 +2767,10 @@ export default class Serve extends Command {
// multi-replica local-database refusal before step 2 reads the runtime's
// own resolution of it. Unset on the legacy route.
let standaloneDatabaseInput: StandaloneStackConfig | undefined;
// The platform database this command's own `OS_DATABASE_URL` fallback
// declared (step 2), for the `knowledge` store choice in the capability
// resolver (`resolveCapabilityExtras`). Unset on every other route.
let fallbackPrimaryDatabase: CapabilityDatabase | undefined;

// Resolve the kernel logger level up front. It decides more than the
// logger's own threshold: it decides whether the boot-quiet window below
Expand Down Expand Up @@ -3600,6 +3606,7 @@ export default class Serve extends Command {
resolvedDriverLabel = resolution.label;
resolvedDatabaseUrl = resolution.displayUrl;
servedSqliteFilePath = resolution.sqliteFilePath;
fallbackPrimaryDatabase = { driver: resolution.driverId, url: databaseUrl };

// ADR-0057 §3.6 (#2834 ②): the dedicated `telemetry` datasource
// next to an explicit SQLite primary (`sqliteFilePath`, unset for
Expand Down Expand Up @@ -5474,6 +5481,22 @@ export default class Serve extends Command {
// token's own required/best-effort semantics — under the next.
const resolverMounted: unknown[] = [];

// The platform database, as the token rows whose providers depend on it
// read it (today the `knowledge` store: pgvector on PostgreSQL, else a
// libSQL file of its own). The one each route resolved for itself: this
// command's fallback (step 2), else the standalone stack's own
// resolution over the input it was composed from. Neither ⇒ a host
// whose own plugin provides the driver, and the rule reads the
// environment (`resolveKnowledgeStore`).
let capabilityDatabase: CapabilityDatabase | undefined = fallbackPrimaryDatabase;
if (!capabilityDatabase && standaloneDatabaseInput !== undefined) {
try {
const { resolveStandaloneDatabase } = await import('@objectstack/runtime');
const primary = resolveStandaloneDatabase(standaloneDatabaseInput);
capabilityDatabase = { driver: primary.driver, url: primary.url };
} catch { /* the stack's own boot reports a database it cannot resolve */ }
}

// Exact identity comparison, NOT substring containment — a consumer named
// after the capability it consumes must never be mistaken for its
// provider (#7652). See Serve.providesCapability.
Expand Down Expand Up @@ -5601,21 +5624,34 @@ export default class Serve extends Command {
resolverMounted.push(provider);
trackPlugin(spec.export);

if (spec.extras) {
for (const ex of spec.extras) {
if (hasPluginMatching(ex.identities)) continue;
try {
const exMod: any = await import(/* webpackIgnore: true */ ex.pkg);
const ExCtor = exMod[ex.export];
if (ExCtor) {
const extra = new ExCtor();
await kernel.use(extra);
resolverMounted.push(extra);
trackPlugin(ex.export);
}
} catch {
// optional extra — silently skip
// A row's extras, or for `knowledge` the one store the platform
// database chooses, each with its own argument — the rule the
// handle reads too (`resolveCapabilityExtras`, `@objectstack/core`).
const extras = resolveCapabilityExtras(cap, {
stack: config,
packageRoot: path.dirname(absolutePath),
env: process.env,
database: capabilityDatabase,
});
for (const ex of extras) {
if (hasPluginMatching(ex.identities)) continue;
try {
const exMod: any = await import(/* webpackIgnore: true */ ex.pkg);
const ExCtor = exMod[ex.export];
if (ExCtor) {
const extra = ex.argument !== undefined ? new ExCtor(ex.argument) : new ExCtor();
await kernel.use(extra);
resolverMounted.push(extra);
trackPlugin(ex.export);
} else {
console.warn(chalk.yellow(` ⚠ Capability "${cap}": ${ex.pkg} did not export ${ex.export}; it was not mounted`));
}
} catch (exErr: unknown) {
// The main provider is mounted; an extra that cannot load is
// said once, never skipped in silence (a `knowledge` source
// naming the store then answers why at its first use).
const exMsg = exErr instanceof Error ? exErr.message : String(exErr);
console.warn(chalk.yellow(` ⚠ Capability "${cap}": ${ex.export} (${ex.pkg}) was not mounted: ${exMsg}`));
}
}
} catch (err: unknown) {
Expand Down
15 changes: 15 additions & 0 deletions packages/cli/src/utils/boot-preparation-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ import {
} from './stack-collections.js';
import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from './telemetry-datasource.js';

// Paid at collection, not inside a clocked case: what the step modules imported
// above reach through dynamic `import()`s (`check:test-source-alias`).
import '@objectstack/service-datasource';
import '@objectstack/driver-turso';
import '@objectstack/driver-sql';
import '@objectstack/platform-objects/plugin';
import '@objectstack/plugin-security';
import '@objectstack/rest';

/** …/packages/cli/src/utils */
const HERE = dirname(fileURLToPath(import.meta.url));
/** …/packages/cli/src — this package's own source tree. */
Expand Down Expand Up @@ -178,6 +187,12 @@ const SERVE_ONLY: Record<string, string> = {
+ 'the storage root; [#22301], shared with @objectstack/verify\'s bootStack): the declaration boot constructs '
+ 'each provider for its declarations only, with a measured posture per token '
+ '(DECLARATION_PROVIDER_POSTURES), and runs no start() that would read a configuration',
resolveCapabilityExtras:
'which further providers serve mounts after a token\'s main one, and what each is built with — a row\'s '
+ 'extras, and for knowledge the one vector store the platform database chooses (shared with '
+ '@objectstack/verify\'s bootStack): the declaration boot reads a row\'s extras itself (composeServedPlatform) '
+ 'and composes no knowledge store, whose init() declares nothing — its tables are its own, in a libSQL file '
+ 'or a PostgreSQL schema of its own, made in the start() this boot does not run',
findSqlDriverForKernel:
'the artifact boot migration gate, a kernel:ready hook over a booted kernel — a serving-boot policy that '
+ 'runs after preparation, not a step that shapes what is prepared',
Expand Down
16 changes: 14 additions & 2 deletions packages/cli/test/serve-capability-identity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { CAPABILITY_PROVIDERS, providesCapability } from '@objectstack/core';
import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS, providesCapability } from '@objectstack/core';
import Serve from '../src/commands/serve.js';

// Pay the first transform of these dist-resolved workspace deps at MODULE LOAD:
Expand Down Expand Up @@ -148,6 +148,7 @@ const EXPECTED_PROVIDER_NAME: Record<string, string> = {
settings: 'com.objectstack.service.settings',
webhooks: 'com.objectstack.plugin-webhook-outbox',
'record-context': 'com.objectstack.service.record-context',
knowledge: 'com.objectstack.service.knowledge',
};

describe('#7652: every registered provider is still recognised (the other direction)', () => {
Expand Down Expand Up @@ -222,7 +223,12 @@ describe('#7652: declared identities match what the provider packages register',
const entries = Object.entries(CAPABILITY_PROVIDERS).flatMap(([cap, spec]) => [
{ cap, pkg: spec.pkg, export: spec.export, identities: spec.identities },
...(spec.extras ?? []).map((ex) => ({ cap: `${cap}:${ex.export}`, pkg: ex.pkg, export: ex.export, identities: ex.identities })),
]);
]).concat(
// The stores the `knowledge` token chooses between (`resolveCapabilityExtras`).
Object.values(KNOWLEDGE_STORE_PROVIDERS).map((store) => ({
cap: `knowledge:${store.export}`, pkg: store.pkg, export: store.export, identities: store.identities,
})),
);

/**
* The consumer side of the pin. `@objectstack/connector-mcp` is not a
Expand Down Expand Up @@ -341,6 +347,12 @@ const IDENTITY_SOURCES: IdentitySource[] = [
identities: ex.identities,
})),
]),
...Object.entries(KNOWLEDGE_STORE_PROVIDERS).map(([id, store]) => ({
label: `KNOWLEDGE_STORE_PROVIDERS.${id}`,
pkg: store.pkg,
export: store.export,
identities: store.identities,
})),
...Object.entries(IDENTITY_LISTS).map(([name, entry]) => ({
label: `Serve.${name}`,
pkg: entry.pkg,
Expand Down
Loading
Loading