@agentage/extension 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,7 @@ export declare const hostEnvOf: (env: Env) => {
12
12
  origin: string;
13
13
  drainMs: number;
14
14
  storeOpenMs: number;
15
+ storeUrlFile: string | undefined;
15
16
  };
16
17
  export declare const guardOf: (env: Env, { bind, dir }: {
17
18
  bind: string;
@@ -28,6 +28,8 @@ export const hostEnvOf = (env) => {
28
28
  origin: env['AGENTAGE_ORIGIN'] || `http://127.0.0.1${port ? `:${port}` : ''}`,
29
29
  drainMs: msOf(env['AGENTAGE_DRAIN_MS'], GRACE_MS),
30
30
  storeOpenMs: msOf(env['AGENTAGE_STORE_OPEN_MS'], STORE_OPEN_MS),
31
+ // G1, G2: the estate's postgres or clickhouse; unset keeps PGlite in dataDir.
32
+ storeUrlFile: env['AGENTAGE_STORE_URL_FILE'] || undefined,
31
33
  };
32
34
  };
33
35
  // Loopback: no token check. Every address: the cloud part's check, or an explicit AGENTAGE_HOST_AUTH=off.
@@ -16,6 +16,7 @@ export interface HostOptions {
16
16
  localOnly?: boolean;
17
17
  localPorts?: number[];
18
18
  storeOpenMs?: number;
19
+ storeUrlFile?: string;
19
20
  }
20
21
  export interface HostedExtension {
21
22
  id: string;
@@ -12,11 +12,11 @@ import {} from '../manifest/parts.js';
12
12
  import { readManifest } from '../manifest/read-manifest.js';
13
13
  import { buildInfoFromEnv } from '../runtime/build-info.js';
14
14
  import {} from '../server/app.js';
15
- import { storeCheck } from '../store/store.js';
16
15
  import { hostClockRate } from '../worker/clock.js';
17
16
  import { localOnly } from './daemon/guard.js';
18
17
  import { hostPartsOf } from './host-parts.js';
19
18
  import { openHostStore, STORE_OPEN_MS } from './host-store.js';
19
+ import { hostStoreChecks, openUrlStore } from './host-url-store.js';
20
20
  const once = (fn) => {
21
21
  let done = false;
22
22
  return () => {
@@ -28,7 +28,7 @@ const once = (fn) => {
28
28
  };
29
29
  const baseOf = async (h) => {
30
30
  const guard = (await h.extras.guard?.(h.pkg, h.log)) ?? {};
31
- const checks = { ...(h.store && { store: storeCheck(h.store) }), ...guard.checks };
31
+ const checks = { ...hostStoreChecks(h.store), ...guard.checks };
32
32
  const resolved = { instance: randomBytes(4).toString('hex'), startedAt: Date.now() };
33
33
  const clockRate = hostClockRate();
34
34
  const guards = h.opts.localOnly ? [localOnly(undefined, h.opts.localPorts)] : undefined;
@@ -61,7 +61,8 @@ export const hostWith = async (dir, opts, extras) => {
61
61
  const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
62
62
  const openMs = opts.storeOpenMs ?? STORE_OPEN_MS;
63
63
  const at = { dir, dataDir: opts.dataDir, runDir: opts.runDir, openMs };
64
- const store = await openHostStore(pkg, at, log);
64
+ const url = { dir, file: opts.storeUrlFile, openMs };
65
+ const store = (await openUrlStore(pkg, url, log)) ?? (await openHostStore(pkg, at, log));
65
66
  const onExit = once(opts.onExit ?? (() => undefined));
66
67
  const build = extras.build ?? (await hostBuildInfo({}, dir));
67
68
  const h = { dir, pkg, log, opts, extras, store, onExit, build };
@@ -0,0 +1,8 @@
1
+ import { type HealthCheck } from '../health/health.js';
2
+ import { type Log } from '../log/log.js';
3
+ import { type Env } from '../runtime/build-info.js';
4
+ import { type MigrateResult } from '../store/migrations.js';
5
+ import { type Store } from '../store/store.types.js';
6
+ export declare const pendingMigrations: (store: Store, dir: string) => Promise<string[]>;
7
+ export declare const migrationsCheck: (store: Store, dir: string, log: Log) => HealthCheck;
8
+ export declare const migrateHost: (env: Env, write?: (line: string) => undefined) => Promise<MigrateResult | undefined>;
@@ -0,0 +1,62 @@
1
+ import { join } from 'node:path';
2
+ import {} from '../health/health.js';
3
+ import { createLog } from '../log/log.js';
4
+ import { storeOf } from '../manifest/parts.js';
5
+ import { readManifest } from '../manifest/read-manifest.js';
6
+ import {} from '../runtime/build-info.js';
7
+ import { KIT_MIGRATIONS } from '../store/kit-migrations.js';
8
+ import { migrate, sqlFiles } from '../store/migrations.js';
9
+ import { createStore, MIGRATE_TIMEOUTS } from '../store/store.js';
10
+ import { readStoreUrl, STORE_URL_FILE_ENV } from '../store/store-url.js';
11
+ import {} from '../store/store.types.js';
12
+ const UNDEFINED_TABLE = '42P01';
13
+ // The kit's and the package's migration names the ledger does not hold yet.
14
+ export const pendingMigrations = async (store, dir) => {
15
+ const want = [...KIT_MIGRATIONS.map((m) => m.name), ...(await sqlFiles(join(dir, 'migrations')))];
16
+ try {
17
+ const { rows } = await store.query('select name from _migrations');
18
+ const done = new Set(rows.map((row) => row.name));
19
+ return want.filter((name) => !done.has(name));
20
+ }
21
+ catch (err) {
22
+ if (err.code === UNDEFINED_TABLE)
23
+ return want;
24
+ throw err;
25
+ }
26
+ };
27
+ // checks["store:migrations"]: the serving host never migrates; ok once, it stays ok (one image, one set).
28
+ export const migrationsCheck = (store, dir, log) => {
29
+ let applied = false;
30
+ let warned = false;
31
+ return async () => {
32
+ if (applied)
33
+ return 'ok';
34
+ const pending = await pendingMigrations(store, dir);
35
+ applied = pending.length === 0;
36
+ if (!applied && !warned)
37
+ log.warn('migrations not applied: run the migrate job', { pending: pending.join(', ') });
38
+ warned ||= !applied;
39
+ return applied ? 'ok' : 'unavailable';
40
+ };
41
+ };
42
+ // `main.js migrate`: the one container as a one-shot job; the URL is never printed.
43
+ export const migrateHost = async (env, write = (line) => void process.stdout.write(line)) => {
44
+ const dir = env['AGENTAGE_EXTENSION_DIR'] || process.cwd();
45
+ const pkg = await readManifest(dir);
46
+ const log = createLog({ extension: pkg.agentage.id, part: 'migrate', version: pkg.version });
47
+ const file = env[STORE_URL_FILE_ENV];
48
+ if (!file)
49
+ throw new Error(`migrate needs ${STORE_URL_FILE_ENV}`);
50
+ if (storeOf(pkg) !== 'postgres')
51
+ return void log.info('no postgres store: nothing to migrate');
52
+ const url = await readStoreUrl(file, 'postgres');
53
+ const store = createStore({ AGENTAGE_STORE_URL: url }, log, MIGRATE_TIMEOUTS);
54
+ try {
55
+ const result = await migrate(store, dir, log);
56
+ write(`${JSON.stringify(result)}\n`);
57
+ return result;
58
+ }
59
+ finally {
60
+ await store.end();
61
+ }
62
+ };
@@ -0,0 +1,21 @@
1
+ import { type HealthCheck } from '../health/health.js';
2
+ import { type Log } from '../log/log.js';
3
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
4
+ import { type PoolStore } from '../store/store.js';
5
+ import { type UrlStoreKind } from '../store/store-url.js';
6
+ import { type Store } from '../store/store.types.js';
7
+ export interface HostStore extends Store {
8
+ close(): Promise<void>;
9
+ readonly kind?: UrlStoreKind;
10
+ readonly checks?: Record<string, HealthCheck>;
11
+ }
12
+ export interface UrlStoreAt {
13
+ dir: string;
14
+ file?: string;
15
+ openMs: number;
16
+ }
17
+ type Pool = (url: string, log: Log) => PoolStore;
18
+ export declare const postgresStore: (url: string, dir: string, log: Log, pool?: Pool) => HostStore;
19
+ export declare const openUrlStore: (pkg: ExtensionPackage, at: UrlStoreAt, log: Log) => Promise<HostStore | undefined>;
20
+ export declare const hostStoreChecks: (store: HostStore | undefined) => Record<string, HealthCheck>;
21
+ export {};
@@ -0,0 +1,62 @@
1
+ import {} from '../health/health.js';
2
+ import { messageOf } from '../log/log.js';
3
+ import {} from '../manifest/manifest.schema.js';
4
+ import { storeOf } from '../manifest/parts.js';
5
+ import { createClickhouseStore } from '../store/clickhouse-store.js';
6
+ import { createStore, storeCheck } from '../store/store.js';
7
+ import { isUrlStoreKind, readStoreUrl, STORE_URL_FILE_ENV, } from '../store/store-url.js';
8
+ import {} from '../store/store.types.js';
9
+ import { migrationsCheck } from './host-migrations.js';
10
+ const poolOf = (url, log) => createStore({ AGENTAGE_STORE_URL: url }, log);
11
+ // The serving host never migrates (the migrate job does): /health is 503 until the ledger is current.
12
+ export const postgresStore = (url, dir, log, pool = poolOf) => {
13
+ const parts = pool(url, log);
14
+ return {
15
+ kind: 'postgres',
16
+ query: parts.query,
17
+ close: () => parts.end(),
18
+ checks: { 'store:migrations': migrationsCheck(parts, dir, log) },
19
+ };
20
+ };
21
+ const within = (work, ms) => Promise.race([work, new Promise((ok) => setTimeout(() => ok('late'), ms).unref())]);
22
+ // The start waits up to openMs for the store; one that is down still starts, /health says 503.
23
+ const firstUse = async (store, kind, openMs, log) => {
24
+ const opened = store.query('select 1').then(() => 'ok', (err) => err);
25
+ const result = await within(opened, openMs);
26
+ if (result === 'ok')
27
+ return log.info('store opened', { kind, from: STORE_URL_FILE_ENV });
28
+ const reason = result === 'late' ? `not in ${openMs} ms` : messageOf(result);
29
+ log.warn('the store did not open: /health says unavailable until it does', { kind, reason });
30
+ };
31
+ const kindOf = (pkg, log) => {
32
+ const kind = storeOf(pkg);
33
+ if (isUrlStoreKind(kind))
34
+ return kind;
35
+ log.warn(`${STORE_URL_FILE_ENV} is set, the package has no postgres or clickhouse store: unused`);
36
+ return undefined;
37
+ };
38
+ // G1, G2: the estate's store from AGENTAGE_STORE_URL_FILE; unset, the host keeps PGlite (undefined).
39
+ export const openUrlStore = async (pkg, at, log) => {
40
+ if (!at.file)
41
+ return undefined;
42
+ const kind = kindOf(pkg, log);
43
+ if (!kind)
44
+ return undefined;
45
+ const url = await readStoreUrl(at.file, kind);
46
+ const store = kind === 'postgres' ? postgresStore(url, at.dir, log) : createClickhouseStore(url, log);
47
+ await firstUse(store, kind, at.openMs, log);
48
+ return store;
49
+ };
50
+ // Calls that overlap share one run: /health asks checks.store and store:<kind> in one probe.
51
+ const shared = (check) => {
52
+ let running;
53
+ return () => (running ??= check().finally(() => (running = undefined)));
54
+ };
55
+ // checks.store as before; a URL store adds store:<kind> (the same probe) and its own checks.
56
+ export const hostStoreChecks = (store) => {
57
+ if (!store)
58
+ return {};
59
+ const check = shared(storeCheck(store));
60
+ const named = store.kind ? { [`store:${store.kind}`]: check } : {};
61
+ return { store: check, ...named, ...store.checks };
62
+ };
package/dist/host/main.js CHANGED
@@ -1,12 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { createLog } from '../log/log.js';
3
3
  import { startHostClock } from './clock-rate.js';
4
+ import { migrateHost } from './host-migrations.js';
4
5
  import { serveHost } from './serve-host.js';
5
- // The daemon's child and the one container: `node .../dist/host/main.js`, settings from env.
6
+ // The daemon's child and the one container, settings from env; `main.js migrate`: the estate's job.
6
7
  const crash = (err) => {
7
8
  createLog({ extension: 'unknown', part: 'api' }).error(err);
8
9
  process.exit(1);
9
10
  };
10
11
  process.on('uncaughtException', crash);
11
- startHostClock(process.env);
12
- await serveHost(process.env).catch(crash);
12
+ if (process.argv[2] === 'migrate') {
13
+ await migrateHost(process.env).then(() => process.exit(0), crash);
14
+ }
15
+ else {
16
+ startHostClock(process.env);
17
+ await serveHost(process.env).catch(crash);
18
+ }
@@ -52,10 +52,11 @@ export const serveHost = async (env, deps = {}) => {
52
52
  const at = hostEnvOf(env);
53
53
  const guard = guardOf(env, at);
54
54
  const hook = exitHook();
55
- const { dataDir, runDir, settings, origin, secretsDir, storeOpenMs } = at;
55
+ const { dataDir, runDir, settings, origin, secretsDir, storeOpenMs, storeUrlFile } = at;
56
56
  // C2: on loopback the child checks Host and Origin itself, for its own port and the daemon's.
57
57
  const local = { localOnly: at.bind === '127.0.0.1', localPorts: loopbackPorts(origin) };
58
- const opts = { dataDir, runDir, settings, origin, storeOpenMs, onExit: hook.onExit, ...local };
58
+ const store = { storeOpenMs, storeUrlFile };
59
+ const opts = { dataDir, runDir, settings, origin, ...store, onExit: hook.onExit, ...local };
59
60
  const build = await hostBuildInfo(env, at.dir);
60
61
  const host = await hostWith(at.dir, opts, { secretsDir, guard, build });
61
62
  const server = await listen(host.app, at.port, at.bind);
package/dist/index.d.ts CHANGED
@@ -21,6 +21,7 @@ export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, }
21
21
  export { versionPage, type PagesContext, type PagesEntry, type PagesSite } from './pages/pages.js';
22
22
  export { siteFromDir, type SiteFromDirOptions } from './pages/site-from-dir.js';
23
23
  export { type ApiCreate, type ApiHandler, type ApiPart } from './server/part.types.js';
24
+ export { clickhouseOf, createClickhouseStore, isClickhouseOutage, type ClickhouseOptions, type ClickhouseStore, } from './store/clickhouse-store.js';
24
25
  export { type QueryResult, type Row, type Store } from './store/store.types.js';
25
26
  export { startTestMcp, startTestServer, type TestMcp, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
26
27
  export { type JobOptions } from './worker/job-options.js';
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ export {} from './mcp/tools.js';
22
22
  export { versionPage } from './pages/pages.js';
23
23
  export { siteFromDir } from './pages/site-from-dir.js';
24
24
  export {} from './server/part.types.js';
25
+ export { clickhouseOf, createClickhouseStore, isClickhouseOutage, } from './store/clickhouse-store.js';
25
26
  export {} from './store/store.types.js';
26
27
  export { startTestMcp, startTestServer, } from './testing/test-server.js';
27
28
  export {} from './worker/job-options.js';
@@ -0,0 +1,20 @@
1
+ export interface ClickhouseConnection {
2
+ origin: string;
3
+ username: string;
4
+ password: string;
5
+ database: string;
6
+ }
7
+ export type ClickhouseParams = Record<string, unknown>;
8
+ export type ClickhouseSettings = Record<string, string | number>;
9
+ export interface ClickhouseCall {
10
+ sql: string;
11
+ params?: ClickhouseParams;
12
+ settings?: ClickhouseSettings;
13
+ body?: string;
14
+ signal?: AbortSignal;
15
+ timeoutMs: number;
16
+ }
17
+ export declare const connectionOf: (text: string) => ClickhouseConnection;
18
+ export declare const value: (v: unknown) => string;
19
+ export declare const request: (c: ClickhouseConnection, call: ClickhouseCall) => Promise<string>;
20
+ export declare const rowsOf: <R>(text: string) => R[];
@@ -0,0 +1,90 @@
1
+ // The estate's form, http://logs:{pw}@logs_store:8123/logs; the URL was checked by readStoreUrl.
2
+ export const connectionOf = (text) => {
3
+ const url = new URL(text);
4
+ return {
5
+ origin: url.origin,
6
+ username: decodeURIComponent(url.username) || 'default',
7
+ password: decodeURIComponent(url.password),
8
+ database: decodeURIComponent(url.pathname.slice(1)) || 'default',
9
+ };
10
+ };
11
+ const ESCAPES = { '\\': '\\\\', '\t': '\\t', '\n': '\\n', "'": "\\'" };
12
+ const escaped = (s) => s.replace(/[\\\t\n']/g, (c) => ESCAPES[c] ?? c);
13
+ // Whole seconds fit DateTime and DateTime64; a Date with milliseconds needs DateTime64(3).
14
+ const epoch = (d) => {
15
+ const ms = d.getTime();
16
+ return ms % 1000 === 0 ? String(ms / 1000) : (ms / 1000).toFixed(3);
17
+ };
18
+ const inner = (v) => {
19
+ if (v === null || v === undefined)
20
+ return 'NULL';
21
+ if (typeof v === 'string')
22
+ return `'${escaped(v)}'`;
23
+ if (v instanceof Date)
24
+ return epoch(v);
25
+ return Array.isArray(v) ? `[${v.map(inner).join(',')}]` : value(v);
26
+ };
27
+ // A {name:Type} parameter in the escaped text form ClickHouse reads from param_<name>.
28
+ export const value = (v) => {
29
+ if (v === null || v === undefined)
30
+ return '\\N';
31
+ if (typeof v === 'string')
32
+ return escaped(v);
33
+ if (Array.isArray(v))
34
+ return `[${v.map(inner).join(',')}]`;
35
+ if (v instanceof Date)
36
+ return epoch(v);
37
+ if (typeof v === 'object')
38
+ return JSON.stringify(v);
39
+ return String(v);
40
+ };
41
+ const urlOf = (c, call) => {
42
+ const url = new URL('/', c.origin);
43
+ url.searchParams.set('database', c.database);
44
+ for (const [k, v] of Object.entries(call.settings ?? {}))
45
+ url.searchParams.set(k, String(v));
46
+ for (const [k, v] of Object.entries(call.params ?? {}))
47
+ url.searchParams.set(`param_${k}`, value(v));
48
+ if (call.body !== undefined)
49
+ url.searchParams.set('query', call.sql);
50
+ return url;
51
+ };
52
+ // ClickHouse's own code (159, 243, ...) on err.code, as @clickhouse/client gives it.
53
+ const failure = async (res) => {
54
+ const text = (await res.text()).trim();
55
+ const code = res.headers.get('x-clickhouse-exception-code') ?? /Code: (\d+)/.exec(text)?.[1];
56
+ // No ClickHouse code: a proxy or the edge answered, never the server itself.
57
+ return Object.assign(new Error(text || `clickhouse answered ${res.status}`), {
58
+ code: code ?? `HTTP_${res.status}`,
59
+ });
60
+ };
61
+ const signalOf = (call) => {
62
+ const timeout = AbortSignal.timeout(call.timeoutMs);
63
+ return call.signal ? AbortSignal.any([call.signal, timeout]) : timeout;
64
+ };
65
+ // One POST; the answer's text, or an Error carrying ClickHouse's code.
66
+ export const request = async (c, call) => {
67
+ const res = await fetch(urlOf(c, call), {
68
+ method: 'POST',
69
+ headers: { 'X-ClickHouse-User': c.username, 'X-ClickHouse-Key': c.password },
70
+ body: call.body ?? call.sql,
71
+ signal: signalOf(call),
72
+ });
73
+ if (!res.ok)
74
+ throw await failure(res);
75
+ return res.text();
76
+ };
77
+ // An error after the first rows comes in the body of a 200: never read it as a row.
78
+ const rowOf = (line) => {
79
+ try {
80
+ return JSON.parse(line);
81
+ }
82
+ catch {
83
+ const code = /Code: (\d+)/.exec(line)?.[1] ?? 'BAD_ROW';
84
+ throw Object.assign(new Error(line.slice(0, 500)), { code });
85
+ }
86
+ };
87
+ export const rowsOf = (text) => text
88
+ .split('\n')
89
+ .filter((line) => line.trim())
90
+ .map((line) => rowOf(line));
@@ -0,0 +1,22 @@
1
+ import { type Log } from '../log/log.js';
2
+ import { type ClickhouseParams, type ClickhouseSettings } from './clickhouse-http.js';
3
+ import { type QueryResult, type Row } from './store.types.js';
4
+ export interface ClickhouseOptions {
5
+ settings?: ClickhouseSettings;
6
+ signal?: AbortSignal;
7
+ }
8
+ export interface ClickhouseStore {
9
+ readonly kind: 'clickhouse';
10
+ query<R extends Row = Row>(sql: string, params?: ClickhouseParams | unknown[], options?: ClickhouseOptions): Promise<QueryResult<R>>;
11
+ command(sql: string, options?: ClickhouseOptions): Promise<void>;
12
+ insert(table: string, rows: object[], options?: ClickhouseOptions): Promise<void>;
13
+ ping(): Promise<boolean>;
14
+ close(): Promise<void>;
15
+ }
16
+ export declare const isClickhouseOutage: (err: unknown) => boolean;
17
+ export declare const createClickhouseStore: (url: string, log: Log, timeoutMs?: number) => ClickhouseStore;
18
+ export declare const isClickhouseStore: (store: unknown) => store is ClickhouseStore;
19
+ export declare const NO_CLICKHOUSE_STORE: ClickhouseStore;
20
+ export declare const clickhouseOf: (ctx: {
21
+ readonly store: unknown;
22
+ }) => ClickhouseStore;
@@ -0,0 +1,87 @@
1
+ import { fail } from '../envelope/envelope.js';
2
+ import { messageOf } from '../log/log.js';
3
+ import { connectionOf, request, rowsOf, } from './clickhouse-http.js';
4
+ import {} from './store.types.js';
5
+ // Counts as JSON numbers; the whole answer before the status, so a late error is a 500, not a 200.
6
+ const READS = {
7
+ output_format_json_quote_64bit_integers: 0,
8
+ wait_end_of_query: 1,
9
+ };
10
+ const TABLE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
11
+ const PING_MS = 900;
12
+ const OUTAGE = /^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|EPIPE)$/;
13
+ // 159 timeout, 202 too many queries; a proxy's 502-504 with no ClickHouse code.
14
+ const BUSY = /^(159|202|HTTP_50[234])$/;
15
+ const codeOf = (err) => {
16
+ const own = err?.code;
17
+ const cause = err?.cause?.code;
18
+ return String(own ?? cause ?? '');
19
+ };
20
+ // undici: "fetch failed" before the answer, "terminated" when the socket closes mid-body.
21
+ const NETWORK = (err) => err instanceof TypeError && /^(fetch failed|terminated)$/.test(err.message);
22
+ // A store that cannot answer now is UNAVAILABLE, as in store.ts; a caller's abort and a query error pass through.
23
+ export const isClickhouseOutage = (err) => OUTAGE.test(codeOf(err)) ||
24
+ BUSY.test(codeOf(err)) ||
25
+ NETWORK(err) ||
26
+ err?.name === 'TimeoutError';
27
+ const guarded = (log) => async (work) => {
28
+ try {
29
+ return await work();
30
+ }
31
+ catch (err) {
32
+ if (!isClickhouseOutage(err))
33
+ throw err;
34
+ log.warn('store unavailable', { reason: messageOf(err) });
35
+ throw fail('UNAVAILABLE', 'The store is unavailable');
36
+ }
37
+ };
38
+ const named = (params) => {
39
+ if (!Array.isArray(params))
40
+ return params;
41
+ if (params.length === 0)
42
+ return undefined;
43
+ throw new Error('a clickhouse query takes named parameters: {name:Type} and an object');
44
+ };
45
+ const ndjson = (rows) => rows.map((row) => JSON.stringify(row)).join('\n');
46
+ const queryOf = (call) => async (sql, params, o = {}) => {
47
+ const { settings, signal } = o;
48
+ const all = { default_format: 'JSONEachRow', ...READS, ...settings };
49
+ return { rows: rowsOf(await call({ sql, params: named(params), settings: all, signal })) };
50
+ };
51
+ const insertOf = (call) => async (table, rows, o = {}) => {
52
+ if (!TABLE.test(table))
53
+ throw new Error(`not a table name: ${table}`);
54
+ await call({ sql: `INSERT INTO ${table} FORMAT JSONEachRow`, body: ndjson(rows), ...o });
55
+ };
56
+ // A store client over the HTTP interface; nothing connects until the first call.
57
+ export const createClickhouseStore = (url, log, timeoutMs = 10_000) => {
58
+ const at = connectionOf(url);
59
+ const run = guarded(log);
60
+ const call = (c) => run(() => request(at, { ...c, timeoutMs }));
61
+ const ping = () => request(at, { sql: 'SELECT 1', timeoutMs: PING_MS });
62
+ const store = {
63
+ kind: 'clickhouse',
64
+ query: queryOf(call),
65
+ command: async (sql, o = {}) => void (await call({ sql, ...o })),
66
+ insert: insertOf(call),
67
+ ping: () => ping().then(() => true, () => false),
68
+ close: async () => undefined,
69
+ };
70
+ return store;
71
+ };
72
+ export const isClickhouseStore = (store) => store?.kind === 'clickhouse';
73
+ const NO_CLICKHOUSE = 'no clickhouse store: declare parts.store "clickhouse" and set AGENTAGE_STORE_URL_FILE';
74
+ const missing = async () => {
75
+ throw new Error(NO_CLICKHOUSE);
76
+ };
77
+ // Says so on first use, as ctx.store does: the check and test contexts run create() with no store.
78
+ export const NO_CLICKHOUSE_STORE = Object.freeze({
79
+ kind: 'clickhouse',
80
+ query: missing,
81
+ command: missing,
82
+ insert: missing,
83
+ ping: async () => false,
84
+ close: async () => undefined,
85
+ });
86
+ // ctx.store as the clickhouse face; the PartContext type stays as it is.
87
+ export const clickhouseOf = (ctx) => isClickhouseStore(ctx.store) ? ctx.store : NO_CLICKHOUSE_STORE;
@@ -2,9 +2,7 @@
2
2
  import { createLog } from '../log/log.js';
3
3
  import { readManifest } from '../manifest/read-manifest.js';
4
4
  import { migrate } from './migrations.js';
5
- import { createStore } from './store.js';
6
- // A migration may rewrite a table: minutes, not a request's seconds; the job itself has no retry.
7
- const MIGRATE_TIMEOUTS = { connectMs: 10_000, statementMs: 300_000 };
5
+ import { createStore, MIGRATE_TIMEOUTS } from './store.js';
8
6
  // The api image's migrate job (`node dist/store/migrate.js`); lines before the manifest read 'unknown'.
9
7
  let log = createLog({ extension: 'unknown', part: 'migrate' });
10
8
  try {
@@ -0,0 +1,4 @@
1
+ export declare const STORE_URL_FILE_ENV = "AGENTAGE_STORE_URL_FILE";
2
+ export type UrlStoreKind = 'postgres' | 'clickhouse';
3
+ export declare const isUrlStoreKind: (kind: string | undefined) => kind is UrlStoreKind;
4
+ export declare const readStoreUrl: (file: string, kind: UrlStoreKind, read?: (at: string) => Promise<string>) => Promise<string>;
@@ -0,0 +1,28 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { messageOf } from '../log/log.js';
3
+ export const STORE_URL_FILE_ENV = 'AGENTAGE_STORE_URL_FILE';
4
+ const SCHEMES = {
5
+ postgres: { protocol: /^postgres(ql)?:$/, form: 'postgres://' },
6
+ clickhouse: { protocol: /^https?:$/, form: 'http:// or https://' },
7
+ };
8
+ export const isUrlStoreKind = (kind) => kind === 'postgres' || kind === 'clickhouse';
9
+ const refused = (file, why) => new Error(`${STORE_URL_FILE_ENV} ${file}: ${why}`);
10
+ const readText = async (file, read) => {
11
+ try {
12
+ return (await read(file)).trim();
13
+ }
14
+ catch (err) {
15
+ throw refused(file, `cannot read it (${err.code ?? messageOf(err)})`);
16
+ }
17
+ };
18
+ // Every error names the variable and the file, never the URL: it holds a credential.
19
+ export const readStoreUrl = async (file, kind, read = (at) => readFile(at, 'utf8')) => {
20
+ const text = await readText(file, read);
21
+ if (!text)
22
+ throw refused(file, 'the file is empty');
23
+ const { protocol, form } = SCHEMES[kind];
24
+ const url = URL.parse(text);
25
+ if (!url || !protocol.test(url.protocol) || !url.hostname)
26
+ throw refused(file, `holds no ${form} URL for the ${kind} store`);
27
+ return text;
28
+ };
@@ -10,6 +10,7 @@ export interface StoreTimeouts {
10
10
  statementMs: number;
11
11
  }
12
12
  export declare const PART_TIMEOUTS: StoreTimeouts;
13
+ export declare const MIGRATE_TIMEOUTS: StoreTimeouts;
13
14
  export declare const storeUrl: (env: Env, read?: (file: string) => string) => string | undefined;
14
15
  export declare const isOutage: (err: unknown) => boolean;
15
16
  export declare const createStore: (env: Env, log: Log, timeouts?: StoreTimeouts) => PoolStore;
@@ -7,6 +7,8 @@ import {} from '../runtime/build-info.js';
7
7
  import {} from './store.types.js';
8
8
  // A part's query is bounded by the server and, if the network itself hangs, by the client too.
9
9
  export const PART_TIMEOUTS = { connectMs: 5_000, statementMs: 10_000 };
10
+ // A migration may rewrite a table: minutes, not a request's seconds.
11
+ export const MIGRATE_TIMEOUTS = { connectMs: 10_000, statementMs: 300_000 };
10
12
  const CLIENT_SLACK_MS = 2_000;
11
13
  // The host sets the connection: AGENTAGE_STORE_URL, a secret file named by _FILE, else libpq PG* env.
12
14
  export const storeUrl = (env, read = (file) => readFileSync(file, 'utf8')) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.15.2",
3
+ "version": "0.16.0",
4
4
  "description": "The agentage extension kit: create(ctx) per part (pages, ui, api, mcp, worker, cli), the store, /health, discovery, the envelope, and the build tool with up and token",
5
5
  "type": "module",
6
6
  "license": "MIT",