@agentage/extension 0.15.2 → 0.17.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.
Files changed (66) hide show
  1. package/dist/api/files-registry.d.ts +17 -0
  2. package/dist/api/files-registry.js +10 -0
  3. package/dist/api/files.d.ts +8 -0
  4. package/dist/api/files.js +82 -0
  5. package/dist/api/routes.d.ts +6 -0
  6. package/dist/api/routes.js +3 -1
  7. package/dist/auth/token-check.d.ts +1 -1
  8. package/dist/auth/verify-token.js +9 -9
  9. package/dist/context/test-context.d.ts +5 -1
  10. package/dist/context/test-context.js +2 -1
  11. package/dist/host/daemon/child.js +6 -4
  12. package/dist/host/daemon/health-routes.js +13 -8
  13. package/dist/host/daemon/routes.js +3 -1
  14. package/dist/host/daemon/seal.d.ts +6 -2
  15. package/dist/host/daemon/seal.js +9 -2
  16. package/dist/host/host-env.d.ts +1 -0
  17. package/dist/host/host-env.js +2 -0
  18. package/dist/host/host-extension.d.ts +1 -0
  19. package/dist/host/host-extension.js +7 -3
  20. package/dist/host/host-git-store.d.ts +10 -0
  21. package/dist/host/host-git-store.js +36 -0
  22. package/dist/host/host-migrations.d.ts +8 -0
  23. package/dist/host/host-migrations.js +62 -0
  24. package/dist/host/host-parts.d.ts +2 -2
  25. package/dist/host/host-parts.js +1 -1
  26. package/dist/host/host-url-store.d.ts +22 -0
  27. package/dist/host/host-url-store.js +62 -0
  28. package/dist/host/main.js +9 -3
  29. package/dist/host/serve-host.js +3 -2
  30. package/dist/index.d.ts +2 -0
  31. package/dist/index.js +2 -0
  32. package/dist/manifest/primitives.schema.js +1 -1
  33. package/dist/mcp/connector.d.ts +4 -0
  34. package/dist/mcp/connector.js +11 -0
  35. package/dist/mcp/mcp-app.d.ts +3 -1
  36. package/dist/mcp/mcp-app.js +27 -17
  37. package/dist/mcp/server.d.ts +6 -3
  38. package/dist/mcp/server.js +52 -14
  39. package/dist/mcp/tools.d.ts +22 -4
  40. package/dist/mcp/tools.js +22 -12
  41. package/dist/runtime/part-mounts.js +12 -6
  42. package/dist/server/api-routes.d.ts +5 -2
  43. package/dist/server/api-routes.js +8 -6
  44. package/dist/server/app.d.ts +3 -0
  45. package/dist/server/app.js +11 -1
  46. package/dist/store/clickhouse-http.d.ts +20 -0
  47. package/dist/store/clickhouse-http.js +90 -0
  48. package/dist/store/clickhouse-store.d.ts +22 -0
  49. package/dist/store/clickhouse-store.js +87 -0
  50. package/dist/store/git-env.d.ts +11 -0
  51. package/dist/store/git-env.js +44 -0
  52. package/dist/store/migrate.js +1 -3
  53. package/dist/store/store-url.d.ts +4 -0
  54. package/dist/store/store-url.js +30 -0
  55. package/dist/store/store.d.ts +1 -0
  56. package/dist/store/store.js +2 -0
  57. package/dist/store/store.types.d.ts +3 -0
  58. package/dist/store/store.types.js +1 -1
  59. package/dist/testing/test-server.js +11 -12
  60. package/dist/tool/container-recipe.d.ts +5 -2
  61. package/dist/tool/container-recipe.js +6 -5
  62. package/dist/tool/container-stage.js +1 -1
  63. package/dist/tool/record-extras.js +4 -3
  64. package/dist/tool/rules/store.js +0 -3
  65. package/dist/tool/rules/surface.js +4 -1
  66. package/package.json +1 -1
@@ -0,0 +1,17 @@
1
+ import { type Caller } from '../auth/token-check.js';
2
+ export type FilesHandler = (...args: never[]) => unknown;
3
+ export interface FilesOptions {
4
+ owner?: (req: never, caller: Caller | null) => boolean | Promise<boolean>;
5
+ maxPushBytes?: number;
6
+ }
7
+ export interface FilesEntry {
8
+ handler: FilesHandler;
9
+ options: FilesOptions;
10
+ }
11
+ export type FilesRegistrar = (handler: FilesHandler, options?: FilesOptions) => void;
12
+ export declare const createFilesRegistry: () => {
13
+ files: FilesRegistrar;
14
+ served: {
15
+ files?: FilesEntry;
16
+ };
17
+ };
@@ -0,0 +1,10 @@
1
+ import {} from '../auth/token-check.js';
2
+ export const createFilesRegistry = () => {
3
+ const served = {};
4
+ const files = (handler, options = {}) => {
5
+ if (served.files)
6
+ throw new Error('files are registered twice');
7
+ served.files = { handler, options };
8
+ };
9
+ return { files, served };
10
+ };
@@ -0,0 +1,8 @@
1
+ import { type Express, type Request } from 'express';
2
+ import { type Access, type TokenCheck } from '../auth/token-check.js';
3
+ import { type FilesEntry } from './files-registry.js';
4
+ export declare const filesPathOf: (id: string) => string;
5
+ export declare const filesAccess: (req: Request) => Access;
6
+ export declare const hasDotSegment: (path: string) => boolean;
7
+ export declare const bearerOf: (authorization: string | undefined) => string | undefined;
8
+ export declare const mountFiles: (app: Express, id: string, entry: FilesEntry, check?: TokenCheck) => undefined;
@@ -0,0 +1,82 @@
1
+ import {} from 'express';
2
+ import { setCaller } from '../auth/token-check.js';
3
+ import { fail, isFailure } from '../envelope/envelope.js';
4
+ import {} from './files-registry.js';
5
+ export const filesPathOf = (id) => `/files/${id}`;
6
+ const UPLOAD = 'git-upload-pack';
7
+ // The raw query is exactly one service=git-upload-pack: no second or encoded key, no other text.
8
+ const onlyUploadService = (req) => {
9
+ const at = req.originalUrl.indexOf('?');
10
+ return at >= 0 && req.originalUrl.slice(at + 1) === `service=${UPLOAD}`;
11
+ };
12
+ // Default deny: only a clone or fetch reads; anything else (a push, any odd form) needs write.
13
+ export const filesAccess = (req) => {
14
+ if (req.method === 'GET' && req.path.endsWith('/info/refs') && onlyUploadService(req))
15
+ return 'read';
16
+ if (req.method === 'POST' && req.path.endsWith(`/${UPLOAD}`) && !req.originalUrl.includes('?'))
17
+ return 'read';
18
+ return 'write';
19
+ };
20
+ const decoded = (segment) => {
21
+ try {
22
+ return decodeURIComponent(segment);
23
+ }
24
+ catch {
25
+ return '..';
26
+ }
27
+ };
28
+ // A dot segment, raw or encoded (also one hidden behind an encoded slash), never reaches the handler.
29
+ export const hasDotSegment = (path) => path
30
+ .split('/')
31
+ .flatMap((segment) => decoded(segment).split(/[/\\]/))
32
+ .some((segment) => segment === '..' || segment === '.');
33
+ // git sends the token as the Basic password; a Bearer header passes as it is.
34
+ export const bearerOf = (authorization) => {
35
+ const [scheme = '', credential = ''] = (authorization ?? '').split(' ');
36
+ if (scheme.toLowerCase() !== 'basic')
37
+ return authorization;
38
+ const decodedBasic = Buffer.from(credential, 'base64').toString('utf8');
39
+ return `Bearer ${decodedBasic.slice(decodedBasic.indexOf(':') + 1)}`;
40
+ };
41
+ // git asks for credentials only after a 401 that names Basic.
42
+ const BASIC = { 'WWW-Authenticate': 'Basic realm="agentage"' };
43
+ const callerFor = async (req, access, check) => {
44
+ if (!check)
45
+ return null;
46
+ return check(bearerOf(req.get('authorization')), access).catch((err) => {
47
+ if (isFailure(err) && err.status === 401)
48
+ throw fail('UNAUTHORIZED', err.message, { headers: BASIC });
49
+ throw err;
50
+ });
51
+ };
52
+ const tooLarge = () => fail('PAYLOAD_TOO_LARGE', 'The push is too large');
53
+ // Counts the bytes as the socket delivers them, so a chunked push stops at the cap too.
54
+ const capBody = (req, max) => {
55
+ if (Number(req.get('content-length') ?? 0) > max)
56
+ throw tooLarge();
57
+ let bytes = 0;
58
+ const push = req.push.bind(req);
59
+ req.push = (chunk, encoding) => {
60
+ bytes += chunk ? chunk.length : 0;
61
+ if (bytes <= max)
62
+ return push(chunk, encoding);
63
+ req.destroy(tooLarge());
64
+ return false;
65
+ };
66
+ };
67
+ const filesGuard = (options, check) => async (req, res, next) => {
68
+ if (hasDotSegment(req.path))
69
+ throw fail('VALIDATION_ERROR', 'A path may not hold a dot segment');
70
+ const access = filesAccess(req);
71
+ const caller = await callerFor(req, access, check);
72
+ if (caller)
73
+ res.setHeader('Cache-Control', 'no-store');
74
+ setCaller(req, caller);
75
+ if (options.owner && !(await options.owner(req, caller)))
76
+ throw fail('FORBIDDEN', 'Not the owner of this path');
77
+ if (access === 'write' && options.maxPushBytes !== undefined)
78
+ capBody(req, options.maxPushBytes);
79
+ next();
80
+ };
81
+ // No token check (a daemon child): anonymous, but the dot, owner and size checks still run.
82
+ export const mountFiles = (app, id, entry, check) => void app.use(filesPathOf(id), filesGuard(entry.options, check), entry.handler);
@@ -2,6 +2,7 @@ import { type z } from 'zod';
2
2
  import { type Access, type Caller } from '../auth/token-check.js';
3
3
  import { type PartContext } from '../context/context.js';
4
4
  import { type Reply } from '../envelope/envelope.js';
5
+ import { type FilesRegistrar } from './files-registry.js';
5
6
  import { type WellKnownRegistrar } from './well-known.js';
6
7
  export declare const ROUTE_METHODS: readonly ["get", "post", "put", "patch", "delete"];
7
8
  export type RouteMethod = (typeof ROUTE_METHODS)[number];
@@ -38,6 +39,7 @@ export type RouteRegistrar = <P extends string, I extends ObjectSchema = z.ZodOb
38
39
  export interface ApiContext extends PartContext {
39
40
  readonly route: RouteRegistrar;
40
41
  readonly wellKnown: WellKnownRegistrar;
42
+ readonly files: FilesRegistrar;
41
43
  }
42
44
  type Params = Record<string, unknown>;
43
45
  export interface RouteEntry {
@@ -51,5 +53,9 @@ export declare const createRouteRegistry: () => {
51
53
  documents: import("./well-known.js").WellKnownEntry[];
52
54
  route: RouteRegistrar;
53
55
  routes: RouteEntry[];
56
+ files: FilesRegistrar;
57
+ filesServed: {
58
+ files?: import("./files-registry.js").FilesEntry;
59
+ };
54
60
  };
55
61
  export {};
@@ -2,6 +2,7 @@ import {} from 'zod';
2
2
  import { badScope } from '../auth/token-check.js';
3
3
  import {} from '../context/context.js';
4
4
  import {} from '../envelope/envelope.js';
5
+ import { createFilesRegistry } from './files-registry.js';
5
6
  import { createWellKnownRegistry } from './well-known.js';
6
7
  export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
7
8
  const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
@@ -25,5 +26,6 @@ export const createRouteRegistry = () => {
25
26
  throw new Error(`route ${String(method).toUpperCase()} ${path} ${problem}`);
26
27
  routes.push(entry);
27
28
  };
28
- return { route, routes, ...createWellKnownRegistry() };
29
+ const { files, served } = createFilesRegistry();
30
+ return { route, routes, files, filesServed: served, ...createWellKnownRegistry() };
29
31
  };
@@ -7,7 +7,7 @@ export interface Caller {
7
7
  scopes: readonly string[];
8
8
  }
9
9
  export declare const withJti: (caller: Caller, jti: string | undefined) => Caller;
10
- export type TokenCheck = (authorization: string | undefined, access: Access) => Promise<Caller | null>;
10
+ export type TokenCheck = (authorization: string | undefined, access: Access, at?: string) => Promise<Caller | null>;
11
11
  export declare const setCaller: (request: object, caller: Caller | null) => void;
12
12
  export declare const callerOf: (request: object) => Caller | null;
13
13
  export declare const rank: (access: Access) => number;
@@ -10,9 +10,9 @@ const ClaimsSchema = z.object({
10
10
  jti: z.string().optional(),
11
11
  });
12
12
  const unavailable = (message) => fail('UNAVAILABLE', message, { retryAfter: 5 });
13
- const invalid = (origin, message = 'Invalid token') => fail('UNAUTHORIZED', message, {
13
+ const invalid = (origin, message = 'Invalid token', at = '') => fail('UNAUTHORIZED', message, {
14
14
  headers: {
15
- 'WWW-Authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource"`,
15
+ 'WWW-Authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource${at}"`,
16
16
  },
17
17
  });
18
18
  const forbidden = (scope) => fail('FORBIDDEN', `Needs ${scope}`, {
@@ -36,34 +36,34 @@ export const remoteKeys = (issuer) => {
36
36
  const held = () => set.jwks() !== undefined;
37
37
  return { keys: keysOrOutage(set), read: () => retryOnce(set.reload), held };
38
38
  };
39
- const claimsOf = async (authorization, deps) => {
39
+ const claimsOf = async (authorization, deps, at) => {
40
40
  const [scheme = '', credential = '', ...rest] = authorization.split(' ');
41
41
  const bearer = scheme.toLowerCase() === 'bearer' && rest.length === 0;
42
42
  const jwt = bearer && credential.startsWith('aga_') ? credential : '';
43
43
  const options = { ...VERIFY, issuer: deps.issuer, audience: deps.audience };
44
44
  const verified = await jwtVerify(jwt.slice(4), deps.keys, options).catch((err) => {
45
- throw isFailure(err) ? err : invalid(deps.origin);
45
+ throw isFailure(err) ? err : invalid(deps.origin, undefined, at);
46
46
  });
47
47
  const claims = ClaimsSchema.safeParse(verified.payload);
48
48
  if (!claims.success || verified.protectedHeader.typ !== 'at+jwt')
49
- throw invalid(deps.origin);
49
+ throw invalid(deps.origin, undefined, at);
50
50
  return claims.data;
51
51
  };
52
52
  export const grants = (scope, id, access) => {
53
53
  const held = new Set(scope.split(' '));
54
54
  return VERBS.some((verb) => rank(verb) >= rank(access) && held.has(`${id}:${verb}`));
55
55
  };
56
- export const createTokenCheck = (deps) => async (authorization, access) => {
56
+ export const createTokenCheck = (deps) => async (authorization, access, at) => {
57
57
  // optional: no bearer is anonymous, but a bearer sent is checked like read, never ignored.
58
58
  if (access === 'public' || (access === 'optional' && !authorization))
59
59
  return null;
60
60
  if (!authorization)
61
- throw invalid(deps.origin, 'Missing token');
62
- const { sub, scope, jti } = await claimsOf(authorization, deps);
61
+ throw invalid(deps.origin, 'Missing token', at);
62
+ const { sub, scope, jti } = await claimsOf(authorization, deps, at);
63
63
  if (jti !== undefined && !deps.revoked.loaded())
64
64
  throw unavailable('Revoked list unavailable');
65
65
  if (jti !== undefined && deps.revoked.has(jti))
66
- throw invalid(deps.origin, 'Token revoked');
66
+ throw invalid(deps.origin, 'Token revoked', at);
67
67
  if (!grants(scope, deps.id, access))
68
68
  throw forbidden(scopeOf(deps.id, access));
69
69
  return withJti({ sub, scopes: scope.split(' ') }, jti);
@@ -1,8 +1,9 @@
1
+ import { type FilesRegistrar } from '../api/files-registry.js';
1
2
  import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
2
3
  import { type WellKnownRegistrar } from '../api/well-known.js';
3
4
  import type { HealthCheck } from '../health/health.js';
4
5
  import { type SpanRecord } from '../log/span.js';
5
- import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
6
+ import { type McpContext, type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
6
7
  import { type JobOptions } from '../worker/job-options.js';
7
8
  import { type JobRun } from '../worker/runs.js';
8
9
  import { type Schedule } from '../worker/scheduler.js';
@@ -16,10 +17,13 @@ export interface TestContext extends PartContext {
16
17
  close(): Promise<void>;
17
18
  readonly schedule: Schedule;
18
19
  readonly tool: ToolRegistrar;
20
+ readonly instructions: McpContext['instructions'];
21
+ readonly connector: ToolRegistrar;
19
22
  readonly tools: ToolEntry[];
20
23
  readonly route: RouteRegistrar;
21
24
  readonly routes: RouteEntry[];
22
25
  readonly wellKnown: WellKnownRegistrar;
26
+ readonly files: FilesRegistrar;
23
27
  readonly jobs: ScheduledJob[];
24
28
  readonly spans: SpanRecord[];
25
29
  readonly exits: number[];
@@ -1,8 +1,9 @@
1
+ import {} from '../api/files-registry.js';
1
2
  import { createRouteRegistry } from '../api/routes.js';
2
3
  import {} from '../api/well-known.js';
3
4
  import {} from '../log/log.js';
4
5
  import { createSpan } from '../log/span.js';
5
- import { createToolRegistry } from '../mcp/tools.js';
6
+ import { createToolRegistry, } from '../mcp/tools.js';
6
7
  import { migrate } from '../store/migrations.js';
7
8
  import { createTestStore } from '../store/test-store.js';
8
9
  import {} from '../worker/job-options.js';
@@ -6,7 +6,8 @@ import { configDirOf, fillRun, makeRun, undoRun } from './child-files.js';
6
6
  import { lastWords } from './last-words.js';
7
7
  import { LIMITS } from './limits.js';
8
8
  import { pipeRedacted } from './redact-stream.js';
9
- import { permissionFlag, sealFlags, sealOf } from './seal.js';
9
+ import { readManifest } from '../../manifest/read-manifest.js';
10
+ import { permissionFlag, sealFlags, sealOf, spawnsGit } from './seal.js';
10
11
  const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
11
12
  const STOP_MS = 5_000;
12
13
  const PASSED = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'NODE_EXTRA_CA_CERTS'];
@@ -73,12 +74,13 @@ const stopOf = (child, exited) => async () => {
73
74
  clearTimeout(kill);
74
75
  };
75
76
  // The daemon's own node flags (a loader, --input-type) are never the child's; C2 where Node has --permission.
76
- const execArgvOf = (node, main, spec, run) => {
77
+ const execArgvOf = async (node, main, spec, run) => {
77
78
  if (!permissionFlag(node))
78
79
  return [];
79
80
  const configDir = configDirOf(spec.dataDir);
80
81
  const { id, dir, dataDir } = spec;
81
- return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir });
82
+ const childProcess = spawnsGit(await readManifest(dir));
83
+ return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir, childProcess });
82
84
  };
83
85
  // The listed env of the daemon, then the child's own: TMPDIR in run/{id}, the test clock when not 1.
84
86
  const envOf = (spec, run, clockRate) => ({
@@ -88,7 +90,7 @@ const envOf = (spec, run, clockRate) => ({
88
90
  ...(clockRate === 1 ? {} : { [CLOCK_RATE_ENV]: String(clockRate) }),
89
91
  });
90
92
  const started = async (at, spec, run) => {
91
- const execArgv = execArgvOf(at.node, at.main, spec, run);
93
+ const execArgv = await execArgvOf(at.node, at.main, spec, run);
92
94
  await fillRun(run, spec);
93
95
  const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
94
96
  const child = fork(at.main, [], {
@@ -3,18 +3,23 @@ import { hostParts } from '../../manifest/parts.js';
3
3
  import { readManifest } from '../../manifest/read-manifest.js';
4
4
  import { summary } from './entries.js';
5
5
  import { restartsOf } from './restart.js';
6
- import {} from './seal.js';
6
+ import { sealOfEntry } from './seal.js';
7
7
  import {} from './supervisor.js';
8
8
  // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
9
9
  const DAEMON_SERVICE = 'agentage-daemon';
10
10
  // Read at each call: a reload can change the package in its folder.
11
- const partsOf = async ({ dir }) => dir ? readManifest(dir).then(hostParts, () => []) : [];
12
- const reported = async (entry, info) => ({
13
- ...summary(entry),
14
- parts: await partsOf(entry),
15
- seal: info.seal ?? 'off',
16
- restarts: restartsOf(entry),
17
- });
11
+ const pkgOf = async ({ dir }) => dir ? readManifest(dir).catch(() => undefined) : undefined;
12
+ const partsOf = async (entry) => {
13
+ const pkg = await pkgOf(entry);
14
+ return pkg ? hostParts(pkg) : [];
15
+ };
16
+ // PD2: a git store's child is on with a child-process grant: partial; the daemon's status stays ok.
17
+ const reported = async (entry, info) => {
18
+ const pkg = await pkgOf(entry);
19
+ const seal = sealOfEntry(info.seal ?? 'off', pkg);
20
+ const parts = pkg ? hostParts(pkg) : [];
21
+ return { ...summary(entry), parts, seal, restarts: restartsOf(entry) };
22
+ };
18
23
  const installationOf = ({ invalid, unreadable, notJson }) => {
19
24
  if (unreadable)
20
25
  return { installation: 'unreadable', installationError: unreadable };
@@ -67,7 +67,7 @@ const hostRoutes = (app, deps, entries, info, p) => {
67
67
  app.delete('/host/extensions/:id', remove);
68
68
  app.post('/host/extensions/:id/reload', json, reload);
69
69
  };
70
- // C5 and C1: /health, discovery, /host/* (host token), /api/{id}/* and /mcp/{id} to the child; Host and Origin first.
70
+ // C5 and C1: /health, discovery, /host/* (host token); /api, /mcp, /connector, /files of {id} to the child.
71
71
  export const daemonApp = (deps, entries, port, info, hostToken) => {
72
72
  const app = express();
73
73
  const proxy = proxyTo(entries, deps, hostToken);
@@ -75,6 +75,8 @@ export const daemonApp = (deps, entries, port, info, hostToken) => {
75
75
  app.use(agcidMiddleware, localOnly(port));
76
76
  app.use('/api/:id', proxy);
77
77
  app.use('/mcp/:id', proxy);
78
+ app.use('/connector/:id', proxy);
79
+ app.use('/files/:id', proxy);
78
80
  healthRoutes(app, deps, entries, info);
79
81
  app.use('/host', requireHostToken(hostToken));
80
82
  hostRoutes(app, deps, entries, info, deps.pending);
@@ -1,4 +1,7 @@
1
- export type Seal = 'on' | 'off';
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ export type Seal = 'on' | 'off' | 'partial';
3
+ export declare const spawnsGit: (pkg: ExtensionPackage) => boolean;
4
+ export declare const sealOfEntry: (seal: Seal, pkg: ExtensionPackage | undefined) => Seal;
2
5
  export declare const sealOf: (version: string) => Seal;
3
6
  export declare const permissionFlag: (version: string) => boolean;
4
7
  export declare const sealOffReason: (version: string) => string;
@@ -11,6 +14,7 @@ interface SealAt {
11
14
  configDir: string;
12
15
  runDir: string;
13
16
  dataDir: string;
17
+ childProcess?: boolean;
14
18
  }
15
- export declare const sealFlags: ({ id, main, dir, configDir, runDir, dataDir }: SealAt) => string[];
19
+ export declare const sealFlags: (at: SealAt) => string[];
16
20
  export {};
@@ -1,7 +1,12 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join, parse, sep } from 'node:path';
4
+ import {} from '../../manifest/manifest.schema.js';
5
+ import { hasStore } from '../../manifest/parts.js';
4
6
  import { assertReach, real } from './seal-reach.js';
7
+ // G6 (PD2): a git store spawns git for each operation; no other package gets a child process.
8
+ export const spawnsGit = (pkg) => hasStore(pkg, 'git');
9
+ export const sealOfEntry = (seal, pkg) => seal === 'on' && pkg && spawnsGit(pkg) ? 'partial' : seal;
5
10
  // C2: the permission model with the bypass fixes of D2; the same rule as e2e sealFloorMet.
6
11
  const SEAL_FLOOR = 'Node 22.22.2 or 24.14.1';
7
12
  const versionOf = (version) => version.split('.').map(Number);
@@ -55,8 +60,9 @@ export const kitReadDirs = (main) => {
55
60
  const root = packageRoot(main);
56
61
  return [...new Set([root, upward(root).find(hasWorkspaces) ?? root])];
57
62
  };
58
- // C2: read kit, tree, run/{id}, data/{id}; write the last two; no child process, worker, addon, WASI, sqlite.
59
- export const sealFlags = ({ id, main, dir, configDir, runDir, dataDir }) => {
63
+ // C2: read kit, tree, run/{id}, data/{id}; write the last two; no worker, addon, WASI, sqlite; a child process for git only.
64
+ export const sealFlags = (at) => {
65
+ const { id, main, dir, configDir, runDir, dataDir } = at;
60
66
  const both = (paths) => [...new Set(paths.flatMap((path) => [path, real(path)]))];
61
67
  const writes = both([runDir, dataDir]);
62
68
  const kit = both([...kitReadDirs(main), treeOf(dir)]);
@@ -65,6 +71,7 @@ export const sealFlags = ({ id, main, dir, configDir, runDir, dataDir }) => {
65
71
  return [
66
72
  '--permission',
67
73
  '--no-experimental-sqlite',
74
+ ...(at.childProcess ? ['--allow-child-process'] : []),
68
75
  ...reads.map((path) => `--allow-fs-read=${path}`),
69
76
  ...writes.map((path) => `--allow-fs-write=${path}`),
70
77
  ];
@@ -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,12 @@ 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';
17
+ import { openGitStore } from './host-git-store.js';
18
18
  import { hostPartsOf } from './host-parts.js';
19
19
  import { openHostStore, STORE_OPEN_MS } from './host-store.js';
20
+ import { hostStoreChecks, openUrlStore } from './host-url-store.js';
20
21
  const once = (fn) => {
21
22
  let done = false;
22
23
  return () => {
@@ -28,7 +29,7 @@ const once = (fn) => {
28
29
  };
29
30
  const baseOf = async (h) => {
30
31
  const guard = (await h.extras.guard?.(h.pkg, h.log)) ?? {};
31
- const checks = { ...(h.store && { store: storeCheck(h.store) }), ...guard.checks };
32
+ const checks = { ...hostStoreChecks(h.store), ...guard.checks };
32
33
  const resolved = { instance: randomBytes(4).toString('hex'), startedAt: Date.now() };
33
34
  const clockRate = hostClockRate();
34
35
  const guards = h.opts.localOnly ? [localOnly(undefined, h.opts.localPorts)] : undefined;
@@ -61,7 +62,10 @@ export const hostWith = async (dir, opts, extras) => {
61
62
  const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
62
63
  const openMs = opts.storeOpenMs ?? STORE_OPEN_MS;
63
64
  const at = { dir, dataDir: opts.dataDir, runDir: opts.runDir, openMs };
64
- const store = await openHostStore(pkg, at, log);
65
+ const url = { dir, file: opts.storeUrlFile, openMs };
66
+ const store = (await openGitStore(pkg, { ...at, file: opts.storeUrlFile }, log)) ??
67
+ (await openUrlStore(pkg, url, log)) ??
68
+ (await openHostStore(pkg, at, log));
65
69
  const onExit = once(opts.onExit ?? (() => undefined));
66
70
  const build = extras.build ?? (await hostBuildInfo({}, dir));
67
71
  const h = { dir, pkg, log, opts, extras, store, onExit, build };
@@ -0,0 +1,10 @@
1
+ import { type Log } from '../log/log.js';
2
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
+ import { type HostStore } from './host-url-store.js';
4
+ export interface GitStoreAt {
5
+ dataDir: string;
6
+ runDir?: string;
7
+ openMs: number;
8
+ file?: string;
9
+ }
10
+ export declare const openGitStore: (pkg: ExtensionPackage, at: GitStoreAt, log: Log) => Promise<HostStore | undefined>;
@@ -0,0 +1,36 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, mkdir, mkdtemp } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import {} from '../log/log.js';
6
+ import {} from '../manifest/manifest.schema.js';
7
+ import { hasStore } from '../manifest/parts.js';
8
+ import { gitAccessOf } from '../store/git-env.js';
9
+ import { readStoreUrl } from '../store/store-url.js';
10
+ import { lockOf, lockWithin } from './host-store.js';
11
+ import {} from './host-url-store.js';
12
+ const NO_QUERY = async () => {
13
+ throw new Error('a git store has no query: use ctx.store.gitRoot');
14
+ };
15
+ const writable = (root) => async () => {
16
+ await access(root, constants.W_OK);
17
+ return 'ok';
18
+ };
19
+ const rootOf = async (dataDir, log) => {
20
+ if (dataDir)
21
+ return dataDir;
22
+ log.warn('no data folder: the git store is in a temp folder and lost on exit');
23
+ return mkdtemp(join(tmpdir(), 'agentage-git-'));
24
+ };
25
+ // G5: a git store is a folder (data/{id}) under the data lock: this process is its single writer.
26
+ export const openGitStore = async (pkg, at, log) => {
27
+ if (!hasStore(pkg, 'git'))
28
+ return undefined;
29
+ const url = at.file ? await readStoreUrl(at.file, 'git') : undefined;
30
+ const gitRoot = await rootOf(at.dataDir, log);
31
+ await mkdir(gitRoot, { recursive: true });
32
+ const close = await lockWithin(gitRoot, at.openMs, lockOf({ dataDir: gitRoot, runDir: at.runDir }));
33
+ log.info('git store opened', { remote: url ? 'set' : 'none' });
34
+ const git = gitAccessOf(gitRoot, url);
35
+ return { kind: 'git', query: NO_QUERY, gitRoot, git, close, probe: writable(gitRoot) };
36
+ };
@@ -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
+ };
@@ -4,15 +4,15 @@ import { type Log } from '../log/log.js';
4
4
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
5
5
  import { type HostPartKind } from '../manifest/parts.js';
6
6
  import { type PartAppBase } from '../server/app.js';
7
- import { type PgliteStore } from '../store/pglite-store.js';
8
7
  import { type HostExtras, type HostOptions } from './host-extension.js';
8
+ import { type HostStore } from './host-url-store.js';
9
9
  export interface Hosting {
10
10
  dir: string;
11
11
  pkg: ExtensionPackage;
12
12
  log: Log;
13
13
  opts: HostOptions;
14
14
  extras: HostExtras;
15
- store: PgliteStore | undefined;
15
+ store: HostStore | undefined;
16
16
  onExit: () => void;
17
17
  build: BuildInfo;
18
18
  }
@@ -11,9 +11,9 @@ import { hostParts } from '../manifest/parts.js';
11
11
  import { mcpPathOf } from '../mcp/mcp-app.js';
12
12
  import { MOUNTS } from '../runtime/part-mounts.js';
13
13
  import { createPartApp } from '../server/app.js';
14
- import {} from '../store/pglite-store.js';
15
14
  import {} from '../health/health.js';
16
15
  import {} from './host-extension.js';
16
+ import {} from './host-url-store.js';
17
17
  import { partChecks } from './part-checks.js';
18
18
  const secretsOf = ({ pkg, opts, extras }, part) => extras.secretsDir
19
19
  ? readSecrets(pkg, part, extras.secretsDir)