@agentage/extension 0.17.0 → 0.18.1
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.
- package/dist/api/download.d.ts +14 -0
- package/dist/api/download.js +10 -0
- package/dist/api/openapi-doc.js +21 -12
- package/dist/api/routes.d.ts +4 -1
- package/dist/api/routes.js +12 -1
- package/dist/host/daemon/app-files.d.ts +13 -0
- package/dist/host/daemon/app-files.js +51 -0
- package/dist/host/daemon/app-header.d.ts +3 -0
- package/dist/host/daemon/app-header.js +12 -0
- package/dist/host/daemon/app-reload.d.ts +10 -0
- package/dist/host/daemon/app-reload.js +18 -0
- package/dist/host/daemon/child.d.ts +1 -0
- package/dist/host/daemon/child.js +1 -0
- package/dist/host/daemon/cli-user-watch.d.ts +8 -0
- package/dist/host/daemon/cli-user-watch.js +43 -0
- package/dist/host/daemon/cli-user.d.ts +2 -0
- package/dist/host/daemon/cli-user.js +42 -0
- package/dist/host/daemon/daemon.d.ts +1 -0
- package/dist/host/daemon/daemon.js +13 -1
- package/dist/host/daemon/health-routes.d.ts +2 -0
- package/dist/host/daemon/health-routes.js +16 -7
- package/dist/host/daemon/limits.d.ts +1 -0
- package/dist/host/daemon/limits.js +2 -0
- package/dist/host/daemon/routes.js +25 -9
- package/dist/host/daemon/shell-events.d.ts +9 -0
- package/dist/host/daemon/shell-events.js +36 -0
- package/dist/host/daemon/shell-routes.d.ts +28 -0
- package/dist/host/daemon/shell-routes.js +63 -0
- package/dist/host/daemon/supervisor.d.ts +2 -0
- package/dist/host/daemon/supervisor.js +2 -1
- package/dist/host/data-lock.js +5 -5
- package/dist/host/host-env.js +14 -2
- package/dist/host/host-extension.js +3 -5
- package/dist/host/host-migrations.d.ts +1 -1
- package/dist/host/host-migrations.js +2 -2
- package/dist/host/host-url-store.d.ts +2 -1
- package/dist/host/host-url-store.js +17 -14
- package/dist/host/open-store.d.ts +6 -0
- package/dist/host/open-store.js +6 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/manifest/manifest.schema.d.ts +13 -0
- package/dist/manifest/manifest.schema.js +16 -2
- package/dist/manifest/parts.d.ts +7 -0
- package/dist/manifest/parts.js +5 -0
- package/dist/manifest/primitives.schema.js +2 -2
- package/dist/mcp/mcp-app.d.ts +1 -0
- package/dist/mcp/mcp-app.js +1 -1
- package/dist/mcp/server.js +19 -5
- package/dist/mcp/tools.d.ts +19 -1
- package/dist/mcp/tools.js +12 -0
- package/dist/runtime/run-part.js +22 -6
- package/dist/server/api-routes.js +33 -8
- package/dist/server/send-download.d.ts +3 -0
- package/dist/server/send-download.js +29 -0
- package/dist/shell/dist/index.html +46 -0
- package/dist/shell/dist/shell.css +2 -0
- package/dist/shell/dist/shell.js +68 -0
- package/dist/shell/dist/vendor/app.js +1 -0
- package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +14 -0
- package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +14 -0
- package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +14 -0
- package/dist/shell/dist/vendor/chunk-SQE76S5B.js +1 -0
- package/dist/shell/dist/vendor/jsx-runtime.js +1 -0
- package/dist/shell/dist/vendor/react-dom-client.js +33 -0
- package/dist/shell/dist/vendor/react-dom.js +1 -0
- package/dist/shell/dist/vendor/react.js +1 -0
- package/dist/shell/package.json +5 -0
- package/dist/tool/app-build.d.ts +13 -0
- package/dist/tool/app-build.js +126 -0
- package/dist/tool/app-load.d.ts +4 -0
- package/dist/tool/app-load.js +34 -0
- package/dist/tool/build.js +5 -2
- package/dist/tool/check.js +4 -2
- package/dist/tool/container-recipe.d.ts +4 -0
- package/dist/tool/container-recipe.js +10 -6
- package/dist/tool/index.d.ts +1 -0
- package/dist/tool/index.js +1 -0
- package/dist/tool/main.d.ts +2 -0
- package/dist/tool/main.js +8 -1
- package/dist/tool/recipe.d.ts +1 -1
- package/dist/tool/recipe.js +16 -6
- package/dist/tool/rules/folders.js +1 -1
- package/dist/tool/rules/sealing.js +4 -0
- package/dist/tool/stage.js +2 -2
- package/dist/tool/up/compose.d.ts +4 -0
- package/dist/tool/up/compose.js +41 -3
- package/dist/tool/up/gateway.js +16 -3
- package/dist/tool/up/secrets.d.ts +1 -0
- package/dist/tool/up/secrets.js +13 -1
- package/dist/tool/up/up.js +8 -5
- package/dist/vendor/app/api.d.ts +9 -0
- package/dist/vendor/app/api.js +63 -0
- package/dist/vendor/app/app.types.d.ts +65 -0
- package/dist/vendor/app/app.types.js +1 -0
- package/dist/vendor/app/boundary.d.ts +15 -0
- package/dist/vendor/app/boundary.js +17 -0
- package/dist/vendor/app/context.d.ts +5 -0
- package/dist/vendor/app/context.js +22 -0
- package/dist/vendor/app/index.d.ts +7 -0
- package/dist/vendor/app/index.js +6 -0
- package/dist/vendor/app/region.d.ts +6 -0
- package/dist/vendor/app/region.js +14 -0
- package/dist/vendor/app/split.d.ts +20 -0
- package/dist/vendor/app/split.js +38 -0
- package/dist/vendor/app/state-store.d.ts +3 -0
- package/dist/vendor/app/state-store.js +35 -0
- package/dist/vendor/app/test-host.d.ts +29 -0
- package/dist/vendor/app/test-host.js +66 -0
- package/dist/vendor/app/theme.css +32 -0
- package/package.json +35 -2
- package/schemas/extension-discovery.schema.json +1 -1
- package/schemas/extension-package.schema.json +28 -1
- package/schemas/extension-record.schema.json +1 -1
- package/schemas/health.schema.json +1 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Readable } from 'node:stream';
|
|
2
|
+
declare const FILE: unique symbol;
|
|
3
|
+
export type DownloadBody = string | Uint8Array | Readable | ReadableStream<Uint8Array>;
|
|
4
|
+
export interface DownloadOptions {
|
|
5
|
+
filename?: string;
|
|
6
|
+
contentType?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface DownloadAnswer extends DownloadOptions {
|
|
9
|
+
readonly [FILE]: true;
|
|
10
|
+
body: DownloadBody;
|
|
11
|
+
}
|
|
12
|
+
export declare const download: (body: DownloadBody, options?: DownloadOptions) => DownloadAnswer;
|
|
13
|
+
export declare const isDownload: (value: unknown) => value is DownloadAnswer;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {} from 'node:stream';
|
|
2
|
+
// A registry symbol, so a file made by a second copy of the kit is still recognised.
|
|
3
|
+
const FILE = Symbol.for('agentage.extension.download');
|
|
4
|
+
// What a route that declares produces returns: bytes or a stream sent as they are, not the envelope.
|
|
5
|
+
export const download = (body, options = {}) => ({
|
|
6
|
+
[FILE]: true,
|
|
7
|
+
body,
|
|
8
|
+
...options,
|
|
9
|
+
});
|
|
10
|
+
export const isDownload = (value) => typeof value === 'object' && value !== null && value[FILE] === true;
|
package/dist/api/openapi-doc.js
CHANGED
|
@@ -14,16 +14,21 @@ const bare = (zod, io) => {
|
|
|
14
14
|
const json = (schema) => ({ 'application/json': { schema } });
|
|
15
15
|
const content = (description, schema) => ({ description, content: json(schema) });
|
|
16
16
|
const STRING = { type: 'string' };
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
17
|
+
const BINARY = { type: 'string', format: 'binary' };
|
|
18
|
+
const okResponse = (spec) => {
|
|
19
|
+
if (spec.produces)
|
|
20
|
+
return { description: 'the file', content: { [spec.produces]: { schema: BINARY } } };
|
|
21
|
+
return spec.status === 204 ? { description: 'no content' } : okBody(spec);
|
|
22
|
+
};
|
|
23
|
+
const envelopeOf = (data) => ({
|
|
24
|
+
type: 'object',
|
|
25
|
+
properties: { success: { type: 'boolean', const: true }, data },
|
|
26
|
+
required: ['success', 'data'],
|
|
27
|
+
});
|
|
28
|
+
const okBody = ({ output, etag, bare: asIs }) => ({
|
|
29
|
+
...(asIs
|
|
30
|
+
? content('the body', output ? bare(output, 'output') : {})
|
|
31
|
+
: content('the envelope', envelopeOf(output ? bare(output, 'output') : {}))),
|
|
27
32
|
...(etag && { headers: { ETag: { schema: STRING } } }),
|
|
28
33
|
});
|
|
29
34
|
const refusal = (code) => content(code, { $ref: '#/components/schemas/Error' });
|
|
@@ -52,10 +57,13 @@ const queryParameters = ({ method, spec }) => [
|
|
|
52
57
|
...(spec.query ? queryOf(spec.query) : []),
|
|
53
58
|
];
|
|
54
59
|
const IF_MATCH = { name: 'If-Match', in: 'header', required: false, schema: STRING };
|
|
60
|
+
const IF_NONE_MATCH = { ...IF_MATCH, name: 'If-None-Match' };
|
|
61
|
+
// A bare GET with an ETag is a conditional GET: If-None-Match and 304, not If-Match and 412.
|
|
62
|
+
const conditionalGet = ({ method, spec }) => method === 'get' && spec.bare === true && spec.etag === true;
|
|
55
63
|
const parameters = (entry) => [
|
|
56
64
|
...pathParameters(entry),
|
|
57
65
|
...queryParameters(entry),
|
|
58
|
-
...(entry.spec.etag ? [IF_MATCH] : []),
|
|
66
|
+
...(entry.spec.etag ? [conditionalGet(entry) ? IF_NONE_MATCH : IF_MATCH] : []),
|
|
59
67
|
];
|
|
60
68
|
const responses = (entry) => {
|
|
61
69
|
const { input, params, scope, etag } = entry.spec;
|
|
@@ -64,8 +72,9 @@ const responses = (entry) => {
|
|
|
64
72
|
...((input || params) && { '400': refusal('VALIDATION_ERROR') }),
|
|
65
73
|
...(scope !== 'public' && { '401': refusal('UNAUTHORIZED'), '403': refusal('FORBIDDEN') }),
|
|
66
74
|
...(entry.path.includes('{') && { '404': refusal('NOT_FOUND') }),
|
|
75
|
+
...(conditionalGet(entry) && { '304': { description: 'not modified' } }),
|
|
67
76
|
// If-Match absent on a PUT overwrites (no 428); only a stale tag is refused.
|
|
68
|
-
...(etag && { '412': refusal('PRECONDITION_FAILED') }),
|
|
77
|
+
...(etag && !conditionalGet(entry) && { '412': refusal('PRECONDITION_FAILED') }),
|
|
69
78
|
};
|
|
70
79
|
};
|
|
71
80
|
const securityOf = (id, scope) => {
|
package/dist/api/routes.d.ts
CHANGED
|
@@ -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 DownloadAnswer } from './download.js';
|
|
5
6
|
import { type FilesRegistrar } from './files-registry.js';
|
|
6
7
|
import { type WellKnownRegistrar } from './well-known.js';
|
|
7
8
|
export declare const ROUTE_METHODS: readonly ["get", "post", "put", "patch", "delete"];
|
|
@@ -16,6 +17,8 @@ export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extend
|
|
|
16
17
|
query?: Y;
|
|
17
18
|
etag?: true;
|
|
18
19
|
status?: 200 | 201 | 204;
|
|
20
|
+
bare?: true;
|
|
21
|
+
produces?: string;
|
|
19
22
|
}
|
|
20
23
|
export type ParamsOf<P extends string> = P extends `${string}{${infer N}}${infer R}` ? {
|
|
21
24
|
[K in N]: string;
|
|
@@ -29,7 +32,7 @@ export interface RouteRequest<I, P extends string, S extends Access = Access, Q
|
|
|
29
32
|
ifMatch?: string;
|
|
30
33
|
header: (name: string) => string | undefined;
|
|
31
34
|
}
|
|
32
|
-
type Answer<T> = T | Reply<T
|
|
35
|
+
type Answer<T> = T | Reply<T> | DownloadAnswer;
|
|
33
36
|
export type RouteHandler<I extends ObjectSchema, O extends z.ZodType, P extends string, S extends Access = Access, Q extends ObjectSchema = never, Y extends ObjectSchema = never> = (request: RouteRequest<z.output<I>, P, S, [
|
|
34
37
|
Q
|
|
35
38
|
] extends [never] ? never : z.output<Q>, [
|
package/dist/api/routes.js
CHANGED
|
@@ -2,10 +2,19 @@ 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 {} from './download.js';
|
|
5
6
|
import { createFilesRegistry } from './files-registry.js';
|
|
6
7
|
import { createWellKnownRegistry } from './well-known.js';
|
|
7
8
|
export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
|
|
8
9
|
const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
|
|
10
|
+
const MEDIA_TYPE = /^[a-z0-9][\w.+-]*\/[a-z0-9][\w.+-]*$/i;
|
|
11
|
+
const producesProblem = ({ produces = '', output, status, etag }) => {
|
|
12
|
+
if (!MEDIA_TYPE.test(produces))
|
|
13
|
+
return `produces ${produces}: a media type, as application/zip`;
|
|
14
|
+
if (output || etag || (status ?? 200) !== 200)
|
|
15
|
+
return 'produces a file: no output, etag or status';
|
|
16
|
+
return null;
|
|
17
|
+
};
|
|
9
18
|
const problemOf = (routes, { method, path, spec }) => {
|
|
10
19
|
if (!ROUTE_METHODS.includes(method))
|
|
11
20
|
return `method ${String(method)}: one of get, post, put, patch, delete`;
|
|
@@ -15,7 +24,9 @@ const problemOf = (routes, { method, path, spec }) => {
|
|
|
15
24
|
return 'is registered twice';
|
|
16
25
|
if (!spec.summary)
|
|
17
26
|
return 'needs a summary: it documents the route';
|
|
18
|
-
|
|
27
|
+
if (spec.bare && spec.produces)
|
|
28
|
+
return 'bare answers JSON, produces a download: pick one';
|
|
29
|
+
return (spec.produces !== undefined && producesProblem(spec)) || badScope(spec.scope);
|
|
19
30
|
};
|
|
20
31
|
export const createRouteRegistry = () => {
|
|
21
32
|
const routes = [];
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Express } from 'express';
|
|
2
|
+
import { type Entries } from './entries.js';
|
|
3
|
+
import { type Entry } from './supervisor.js';
|
|
4
|
+
export interface AppRow {
|
|
5
|
+
title: string;
|
|
6
|
+
icon?: string;
|
|
7
|
+
order?: number;
|
|
8
|
+
entry: string;
|
|
9
|
+
css: string;
|
|
10
|
+
}
|
|
11
|
+
export declare const appRowOf: (entry: Entry) => Promise<AppRow | undefined>;
|
|
12
|
+
export declare const hasApp: (entries: Entries, id: string) => Promise<boolean>;
|
|
13
|
+
export declare const appRoutes: (app: Express, entries: Entries) => void;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import express, {} from 'express';
|
|
4
|
+
import { fail } from '../../envelope/envelope.js';
|
|
5
|
+
import { APP_DIR, APP_META_FILE, appOf } from '../../manifest/parts.js';
|
|
6
|
+
import { readManifest } from '../../manifest/read-manifest.js';
|
|
7
|
+
import {} from './entries.js';
|
|
8
|
+
import {} from './supervisor.js';
|
|
9
|
+
const HASHED = /^app-[0-9a-f]+\.(?:js|css)$/;
|
|
10
|
+
const builtFiles = async (dir) => {
|
|
11
|
+
const text = await readFile(join(dir, APP_DIR, APP_META_FILE), 'utf8');
|
|
12
|
+
const files = JSON.parse(text);
|
|
13
|
+
const ok = [files.entry, files.css].every((f) => typeof f === 'string' && HASHED.test(f));
|
|
14
|
+
return ok ? files : undefined;
|
|
15
|
+
};
|
|
16
|
+
// The nav row of an enabled entry whose package has the app part, built; else none.
|
|
17
|
+
export const appRowOf = async (entry) => {
|
|
18
|
+
if (!entry.dir || entry.install.enabled === false)
|
|
19
|
+
return undefined;
|
|
20
|
+
const meta = await readManifest(entry.dir).then(appOf, () => undefined);
|
|
21
|
+
const files = meta && (await builtFiles(entry.dir).catch(() => undefined));
|
|
22
|
+
if (!meta || !files)
|
|
23
|
+
return undefined;
|
|
24
|
+
const at = `/app/${entry.id}/`;
|
|
25
|
+
return { ...meta, entry: `${at}${files.entry}`, css: `${at}${files.css}` };
|
|
26
|
+
};
|
|
27
|
+
// The app id of a page path, when the id is installed and has an app row.
|
|
28
|
+
export const hasApp = async (entries, id) => {
|
|
29
|
+
const entry = entries.get(id);
|
|
30
|
+
return entry !== undefined && (await appRowOf(entry)) !== undefined;
|
|
31
|
+
};
|
|
32
|
+
// K5: hashed files never change; index.js and app.json name the newest build.
|
|
33
|
+
const cacheOf = (path) => HASHED.test(path.split('/').pop() ?? '') ? 'immutable' : 'no-cache';
|
|
34
|
+
const setHeaders = (res, path) => {
|
|
35
|
+
const cache = cacheOf(path);
|
|
36
|
+
res.set('Cache-Control', cache === 'immutable' ? 'public, max-age=31536000, immutable' : cache);
|
|
37
|
+
};
|
|
38
|
+
const appDirOf = async (entries, id) => {
|
|
39
|
+
const entry = entries.get(id);
|
|
40
|
+
if (!entry || !(await appRowOf(entry)))
|
|
41
|
+
throw fail('NOT_FOUND', `${id} has no app`);
|
|
42
|
+
return join(entry.dir ?? '', APP_DIR);
|
|
43
|
+
};
|
|
44
|
+
// GET /app/{id}/*: static from the package folder (not the child), so it answers while the child is down.
|
|
45
|
+
const serveApp = (entries) => async (req, res, next) => {
|
|
46
|
+
const root = await appDirOf(entries, String(req.params['id']));
|
|
47
|
+
express.static(root, { fallthrough: false, index: false, dotfiles: 'deny', setHeaders })(req, res, (err) => next(err && fail('NOT_FOUND', `${String(req.params['id'])} has no such app file`)));
|
|
48
|
+
};
|
|
49
|
+
export const appRoutes = (app, entries) => {
|
|
50
|
+
app.use('/app/:id', serveApp(entries));
|
|
51
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import {} from 'express';
|
|
2
|
+
import { fail } from '../../envelope/envelope.js';
|
|
3
|
+
// What useAppHost().api sends: the app that made the call.
|
|
4
|
+
export const APP_HEADER = 'x-agentage-app';
|
|
5
|
+
// K10: an app calls only its own extension; a raw fetch with no header is not stopped (stated limit).
|
|
6
|
+
export const ownAppOnly = (req, _res, next) => {
|
|
7
|
+
const from = req.get(APP_HEADER);
|
|
8
|
+
const id = String(req.params['id']);
|
|
9
|
+
if (from !== undefined && from !== id)
|
|
10
|
+
throw fail('FORBIDDEN', `the app ${from} may not call the extension ${id}`);
|
|
11
|
+
next();
|
|
12
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Entries } from './entries.js';
|
|
2
|
+
import { type ShellEvents } from './shell-events.js';
|
|
3
|
+
export declare const isAppReload: (body: unknown) => boolean;
|
|
4
|
+
export declare const reloadApp: (entries: Entries, id: string, events: ShellEvents) => Promise<{
|
|
5
|
+
id: string;
|
|
6
|
+
version: string;
|
|
7
|
+
state: import("./supervisor.js").State;
|
|
8
|
+
reloaded: boolean;
|
|
9
|
+
part: string;
|
|
10
|
+
}>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { fail } from '../../envelope/envelope.js';
|
|
2
|
+
import { appRowOf } from './app-files.js';
|
|
3
|
+
import { entryOf } from './entries.js';
|
|
4
|
+
import {} from './shell-events.js';
|
|
5
|
+
// The body of a reload that names the app part: the child keeps running.
|
|
6
|
+
export const isAppReload = (body) => typeof body === 'object' &&
|
|
7
|
+
body !== null &&
|
|
8
|
+
Object.keys(body).length === 1 &&
|
|
9
|
+
body.part === 'app';
|
|
10
|
+
// K8: the new build is in dist/app already; the shell re-imports the entry the event names.
|
|
11
|
+
export const reloadApp = async (entries, id, events) => {
|
|
12
|
+
const entry = entryOf(entries, id);
|
|
13
|
+
const row = await appRowOf(entry);
|
|
14
|
+
if (!row)
|
|
15
|
+
throw fail('VALIDATION_ERROR', `${id} has no built app: run the app build first`);
|
|
16
|
+
events.send('app', { id, entry: row.entry, css: row.css });
|
|
17
|
+
return { id, version: entry.version, state: entry.state, reloaded: true, part: 'app' };
|
|
18
|
+
};
|
|
@@ -21,6 +21,7 @@ export const childEnv = (spec, secretsDir, runDir) => ({
|
|
|
21
21
|
AGENTAGE_ORIGIN: spec.origin,
|
|
22
22
|
...(runDir && { AGENTAGE_RUN_DIR: runDir }),
|
|
23
23
|
...(spec.storeOpenMs && { AGENTAGE_STORE_OPEN_MS: String(spec.storeOpenMs) }),
|
|
24
|
+
...(spec.userSub && { AGENTAGE_USER_SUB: spec.userSub }),
|
|
24
25
|
});
|
|
25
26
|
const passedEnv = () => Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
|
|
26
27
|
const captured = (child, secrets) => {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Entries } from './entries.js';
|
|
2
|
+
import { type SupervisorDeps } from './supervisor.js';
|
|
3
|
+
export interface CliUser {
|
|
4
|
+
text?: string;
|
|
5
|
+
sub?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const syncCliUser: (deps: SupervisorDeps, entries: Entries, polls?: number) => Promise<boolean>;
|
|
8
|
+
export declare const watchCliUser: (deps: SupervisorDeps, entries: Entries) => (() => void);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {} from './entries.js';
|
|
2
|
+
import { cliUserOf, readCliAuth } from './cli-user.js';
|
|
3
|
+
import { halt, hold } from './gate.js';
|
|
4
|
+
import { startEntry } from './supervisor.js';
|
|
5
|
+
// A failed session check (offline) is tried again this many polls later, with the same file.
|
|
6
|
+
const RETRY_POLLS = 30;
|
|
7
|
+
const restart = async (deps, entry) => {
|
|
8
|
+
const release = hold(entry);
|
|
9
|
+
try {
|
|
10
|
+
await halt(entry, deps.drainMs);
|
|
11
|
+
await startEntry(deps, entry);
|
|
12
|
+
}
|
|
13
|
+
finally {
|
|
14
|
+
release();
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
// Read the file; a new user (sign-in, sign-out, another account) restarts every running child.
|
|
18
|
+
export const syncCliUser = async (deps, entries, polls = 0) => {
|
|
19
|
+
const text = await readCliAuth(deps.configDir);
|
|
20
|
+
const retry = text !== '' && deps.user.sub === undefined && polls % RETRY_POLLS === 0;
|
|
21
|
+
if (text === deps.user.text && !retry)
|
|
22
|
+
return false;
|
|
23
|
+
const sub = await cliUserOf(text);
|
|
24
|
+
const changed = sub !== deps.user.sub;
|
|
25
|
+
Object.assign(deps.user, { text, sub });
|
|
26
|
+
if (!changed)
|
|
27
|
+
return false;
|
|
28
|
+
deps.log.info('cli user changed: running extensions restart', { signedIn: sub !== undefined });
|
|
29
|
+
for (const entry of entries.values())
|
|
30
|
+
if (entry.lane)
|
|
31
|
+
await restart(deps, entry);
|
|
32
|
+
return true;
|
|
33
|
+
};
|
|
34
|
+
// Polled in the change queue, so a restart never runs inside an install, update or reload.
|
|
35
|
+
export const watchCliUser = (deps, entries) => {
|
|
36
|
+
let polls = 0;
|
|
37
|
+
const tick = () => void deps
|
|
38
|
+
.queue(() => syncCliUser(deps, entries, ++polls))
|
|
39
|
+
.catch((err) => deps.log.warn('cli user not read', { reason: err.message }));
|
|
40
|
+
const timer = setInterval(tick, deps.userPollMs);
|
|
41
|
+
timer.unref();
|
|
42
|
+
return () => clearInterval(timer);
|
|
43
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
// A segment the extension may use as a folder name (memory: <root>/<sub>/<vault>.git).
|
|
4
|
+
const SUB = /^[A-Za-z0-9_-]{1,128}$/;
|
|
5
|
+
const SESSION_MS = 3_000;
|
|
6
|
+
const objectOf = (value) => typeof value === 'object' && value !== null ? value : {};
|
|
7
|
+
const subOf = (value) => typeof value === 'string' && SUB.test(value) ? value : undefined;
|
|
8
|
+
const parsed = (text) => {
|
|
9
|
+
try {
|
|
10
|
+
return objectOf(JSON.parse(text));
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return {};
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
// The platform token of the issuer (aga_<jwt>) names the sub, no network.
|
|
17
|
+
const tokenSub = (auth, issuer) => {
|
|
18
|
+
const token = String(objectOf(objectOf(auth['platformPats'])[issuer])['token'] ?? '');
|
|
19
|
+
return subOf(parsed(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString())['sub']);
|
|
20
|
+
};
|
|
21
|
+
// The session as the cli checks it (get-session with its bearer); any failure is no user.
|
|
22
|
+
const sessionSub = async (issuer, bearer) => {
|
|
23
|
+
if (typeof bearer !== 'string' || !bearer)
|
|
24
|
+
return undefined;
|
|
25
|
+
const url = `${issuer}/api/auth/mcp/get-session`;
|
|
26
|
+
const headers = { authorization: `Bearer ${bearer}` };
|
|
27
|
+
const signal = AbortSignal.timeout(SESSION_MS);
|
|
28
|
+
const res = await fetch(url, { headers, signal, redirect: 'error' }).catch(() => undefined);
|
|
29
|
+
if (!res?.ok)
|
|
30
|
+
return void (await res?.body?.cancel());
|
|
31
|
+
return subOf(objectOf(await res.json().catch(() => null))['userId']);
|
|
32
|
+
};
|
|
33
|
+
const isOrigin = (value) => typeof value === 'string' && URL.canParse(value) && new URL(value).origin === value;
|
|
34
|
+
// The user of an auth.json text: only of its own issuer; no issuer (a session before cli 0.50.1) is none.
|
|
35
|
+
export const cliUserOf = async (text) => {
|
|
36
|
+
const auth = parsed(text);
|
|
37
|
+
const issuer = auth['issuer'];
|
|
38
|
+
if (!isOrigin(issuer))
|
|
39
|
+
return undefined;
|
|
40
|
+
return tokenSub(auth, issuer) ?? sessionSub(issuer, objectOf(auth['tokens'])['accessToken']);
|
|
41
|
+
};
|
|
42
|
+
export const readCliAuth = (configDir) => readFile(join(configDir, 'auth.json'), 'utf8').catch(() => '');
|
|
@@ -4,6 +4,7 @@ import {} from 'node:net';
|
|
|
4
4
|
import { createLog } from '../../log/log.js';
|
|
5
5
|
import { closeNow, listen } from '../../server/serve.js';
|
|
6
6
|
import { forkLaunch } from './child.js';
|
|
7
|
+
import { syncCliUser, watchCliUser } from './cli-user-watch.js';
|
|
7
8
|
import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-files.js';
|
|
8
9
|
import { assertNoOtherDaemon } from './daemon-owner.js';
|
|
9
10
|
import { bootInstallation, updateInstallation } from './installation.js';
|
|
@@ -15,6 +16,7 @@ import { pendingChanges } from './pending.js';
|
|
|
15
16
|
import { serialQueue } from './queue.js';
|
|
16
17
|
import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
|
|
17
18
|
import { daemonApp } from './routes.js';
|
|
19
|
+
import { kitShellDir, readShell } from './shell-routes.js';
|
|
18
20
|
import { runInstaller } from './installer-call.js';
|
|
19
21
|
import { repairReload } from './reload-marker.js';
|
|
20
22
|
import { halt } from './gate.js';
|
|
@@ -90,6 +92,12 @@ const depsOf = (opts, launch, origin, stopping) => ({
|
|
|
90
92
|
queue: serialQueue(),
|
|
91
93
|
pending: pendingChanges(),
|
|
92
94
|
unsynced: new Set(),
|
|
95
|
+
user: {},
|
|
96
|
+
});
|
|
97
|
+
// A broken shell install costs the page, never the extensions.
|
|
98
|
+
const shellOf = (deps, dir) => readShell(dir).catch((err) => {
|
|
99
|
+
deps.log.warn('the shell package is not readable: no page at /', { reason: err.message });
|
|
100
|
+
return undefined;
|
|
93
101
|
});
|
|
94
102
|
// No other daemon, read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
|
|
95
103
|
export const startDaemon = async (opts, launch) => {
|
|
@@ -101,7 +109,9 @@ export const startDaemon = async (opts, launch) => {
|
|
|
101
109
|
const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
|
|
102
110
|
const { entries, ...file } = await loadEntries(deps);
|
|
103
111
|
const self = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL };
|
|
104
|
-
const
|
|
112
|
+
const shellDir = opts.shellDir ?? kitShellDir();
|
|
113
|
+
const shell = shellDir ? { shell: await shellOf(deps, shellDir) } : {};
|
|
114
|
+
const info = { ...launchMarks(launch), ...self, ...file, ...shell };
|
|
105
115
|
const hostToken = newHostToken();
|
|
106
116
|
const app = daemonApp(deps, entries, () => port, info, hostToken);
|
|
107
117
|
const server = await listen(app, port, '127.0.0.1');
|
|
@@ -109,7 +119,9 @@ export const startDaemon = async (opts, launch) => {
|
|
|
109
119
|
const stop = stopper(server, entries, deps, life);
|
|
110
120
|
try {
|
|
111
121
|
await announce(opts, port, hostToken);
|
|
122
|
+
await deps.queue(() => syncCliUser(deps, entries));
|
|
112
123
|
await deps.queue(() => boot(deps, entries));
|
|
124
|
+
life.signal.addEventListener('abort', watchCliUser(deps, entries));
|
|
113
125
|
}
|
|
114
126
|
catch (err) {
|
|
115
127
|
await stop();
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type Express } from 'express';
|
|
2
2
|
import { type Entries } from './entries.js';
|
|
3
3
|
import { type Seal } from './seal.js';
|
|
4
|
+
import { type Shell } from './shell-routes.js';
|
|
4
5
|
import { type SupervisorDeps } from './supervisor.js';
|
|
5
6
|
export interface DaemonInfo {
|
|
6
7
|
version: string;
|
|
@@ -12,5 +13,6 @@ export interface DaemonInfo {
|
|
|
12
13
|
clockRate?: number;
|
|
13
14
|
seal?: Seal;
|
|
14
15
|
sealError?: string;
|
|
16
|
+
shell?: Shell;
|
|
15
17
|
}
|
|
16
18
|
export declare const healthRoutes: (app: Express, deps: SupervisorDeps, entries: Entries, info: DaemonInfo) => void;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import {} from 'express';
|
|
2
2
|
import { hostParts } from '../../manifest/parts.js';
|
|
3
3
|
import { readManifest } from '../../manifest/read-manifest.js';
|
|
4
|
+
import { appRowOf } from './app-files.js';
|
|
4
5
|
import { summary } from './entries.js';
|
|
5
6
|
import { restartsOf } from './restart.js';
|
|
6
7
|
import { sealOfEntry } from './seal.js';
|
|
8
|
+
import {} from './shell-routes.js';
|
|
7
9
|
import {} from './supervisor.js';
|
|
8
10
|
// What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
|
|
9
11
|
const DAEMON_SERVICE = 'agentage-daemon';
|
|
@@ -45,15 +47,22 @@ const healthOf = async (deps, entries, info) => {
|
|
|
45
47
|
const status = statusOf(deps, entries, info);
|
|
46
48
|
return { status, version: info.version, ...self, extensions, ...marks };
|
|
47
49
|
};
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
const listed = running.map(async (e) => ({
|
|
50
|
+
const rowOf = async (e) => {
|
|
51
|
+
const app = await appRowOf(e);
|
|
52
|
+
return {
|
|
52
53
|
id: e.id,
|
|
53
54
|
version: e.version,
|
|
55
|
+
state: e.state,
|
|
54
56
|
parts: await partsOf(e),
|
|
55
|
-
|
|
56
|
-
|
|
57
|
+
...(app && { app }),
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
// C10 (D10): each running extension and each enabled one with an app (a crashed child keeps its nav row), its state; the shell.
|
|
61
|
+
const discoveryOf = async (entries, { shell }) => {
|
|
62
|
+
const rows = await Promise.all([...entries.values()].map(rowOf));
|
|
63
|
+
const extensions = rows.filter((row) => row.state === 'running' || row.app);
|
|
64
|
+
const served = shell && { shell: { package: shell.package, version: shell.version } };
|
|
65
|
+
return { host: 'local', ...served, extensions };
|
|
57
66
|
};
|
|
58
67
|
const HOST_DISCOVERY_PATH = '/.well-known/agentage-host.json';
|
|
59
68
|
export const healthRoutes = (app, deps, entries, info) => {
|
|
@@ -61,6 +70,6 @@ export const healthRoutes = (app, deps, entries, info) => {
|
|
|
61
70
|
res.set('Cache-Control', 'no-store').json(await healthOf(deps, entries, info));
|
|
62
71
|
});
|
|
63
72
|
app.get(HOST_DISCOVERY_PATH, async (_req, res) => {
|
|
64
|
-
res.set('Cache-Control', 'no-store').json(await discoveryOf(entries));
|
|
73
|
+
res.set('Cache-Control', 'no-store').json(await discoveryOf(entries, info));
|
|
65
74
|
});
|
|
66
75
|
};
|
|
@@ -22,6 +22,8 @@ export const LIMITS = {
|
|
|
22
22
|
crashWindowMs: 600_000,
|
|
23
23
|
// A child healthy this long has its restart count and exits reset.
|
|
24
24
|
healthyResetMs: 600_000,
|
|
25
|
+
// How often auth.json is read: a sign-in or sign-out restarts the running children.
|
|
26
|
+
userPollMs: 2_000,
|
|
25
27
|
};
|
|
26
28
|
export const limitsOf = (given) => {
|
|
27
29
|
const keys = Object.keys(LIMITS);
|
|
@@ -4,6 +4,9 @@ import { ok } from '../../envelope/envelope.js';
|
|
|
4
4
|
import { BODY_LIMIT } from '../../server/app.js';
|
|
5
5
|
import { errorHandler, notFound } from '../../server/errors.js';
|
|
6
6
|
import { localOnly } from './guard.js';
|
|
7
|
+
import { ownAppOnly } from './app-header.js';
|
|
8
|
+
import { appRoutes } from './app-files.js';
|
|
9
|
+
import { isAppReload, reloadApp } from './app-reload.js';
|
|
7
10
|
import { addExtension } from './add.js';
|
|
8
11
|
import { listed } from './entries.js';
|
|
9
12
|
import { healthRoutes } from './health-routes.js';
|
|
@@ -14,6 +17,8 @@ import {} from './pending.js';
|
|
|
14
17
|
import { waitAtMost } from './queue.js';
|
|
15
18
|
import { proxyTo } from './proxy.js';
|
|
16
19
|
import { reloadExtension } from './reload.js';
|
|
20
|
+
import { shellEvents } from './shell-events.js';
|
|
21
|
+
import { shellRoutes } from './shell-routes.js';
|
|
17
22
|
import { stopsNow } from './stopping.js';
|
|
18
23
|
import {} from './supervisor.js';
|
|
19
24
|
const reasonOf = (err) => err.details?.reason;
|
|
@@ -37,8 +42,14 @@ const runner = (deps, info, p) => (what, fn) => p.track(what, () => waitAtMost(d
|
|
|
37
42
|
return fn();
|
|
38
43
|
}));
|
|
39
44
|
const purge = (q) => q['purge'] === 'true';
|
|
40
|
-
|
|
41
|
-
|
|
45
|
+
// Each change that went through tells the open shell pages to read discovery again (K7).
|
|
46
|
+
const changes = (deps, entries, info, events) => {
|
|
47
|
+
const queued = runner(deps, info, deps.pending);
|
|
48
|
+
const run = async (what, fn) => {
|
|
49
|
+
const done = await queued(what, fn);
|
|
50
|
+
events.send('extensions', { op: what.op, ...(what.id && { id: what.id }) });
|
|
51
|
+
return done;
|
|
52
|
+
};
|
|
42
53
|
const id = (params) => String(params['id']);
|
|
43
54
|
const add = async (req, res) => {
|
|
44
55
|
const what = { op: 'install', ...named(req.body) };
|
|
@@ -54,32 +65,37 @@ const changes = (deps, entries, info, p) => {
|
|
|
54
65
|
};
|
|
55
66
|
const reload = async ({ params, body }, res) => {
|
|
56
67
|
const what = { op: 'reload', id: id(params) };
|
|
68
|
+
if (isAppReload(body))
|
|
69
|
+
return void res.json(ok(await queued(what, () => reloadApp(entries, what.id, events))));
|
|
57
70
|
res.json(ok(await run(what, () => reloadExtension(deps, entries, what.id, body))));
|
|
58
71
|
};
|
|
59
72
|
return { add, change, remove, reload };
|
|
60
73
|
};
|
|
61
|
-
const hostRoutes = (app, deps, entries, info,
|
|
74
|
+
const hostRoutes = (app, deps, entries, info, events) => {
|
|
62
75
|
app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
|
|
63
76
|
const json = express.json({ limit: BODY_LIMIT });
|
|
64
|
-
const { add, change, remove, reload } = changes(deps, entries, info,
|
|
77
|
+
const { add, change, remove, reload } = changes(deps, entries, info, events);
|
|
65
78
|
app.post('/host/extensions', json, add);
|
|
66
79
|
app.patch('/host/extensions/:id', json, change);
|
|
67
80
|
app.delete('/host/extensions/:id', remove);
|
|
68
81
|
app.post('/host/extensions/:id/reload', json, reload);
|
|
69
82
|
};
|
|
70
|
-
// C5 and C1: /health, discovery, /host/* (host token); /api, /mcp, /connector, /files of {id} to the child.
|
|
83
|
+
// C5 and C1: /health, discovery, /host/* (host token); /api, /mcp, /connector, /files of {id} to the child; S1.2 the shell and /app.
|
|
71
84
|
export const daemonApp = (deps, entries, port, info, hostToken) => {
|
|
72
85
|
const app = express();
|
|
73
86
|
const proxy = proxyTo(entries, deps, hostToken);
|
|
74
87
|
app.disable('x-powered-by');
|
|
75
88
|
app.use(agcidMiddleware, localOnly(port));
|
|
76
|
-
app.use('/api/:id', proxy);
|
|
89
|
+
app.use('/api/:id', ownAppOnly, proxy);
|
|
77
90
|
app.use('/mcp/:id', proxy);
|
|
78
|
-
app.use('/connector/:id', proxy);
|
|
79
|
-
app.use('/files/:id', proxy);
|
|
91
|
+
app.use('/connector/:id', ownAppOnly, proxy);
|
|
92
|
+
app.use('/files/:id', ownAppOnly, proxy);
|
|
80
93
|
healthRoutes(app, deps, entries, info);
|
|
81
94
|
app.use('/host', requireHostToken(hostToken));
|
|
82
|
-
|
|
95
|
+
const events = shellEvents();
|
|
96
|
+
hostRoutes(app, deps, entries, info, events);
|
|
97
|
+
appRoutes(app, entries);
|
|
98
|
+
shellRoutes(app, { shell: info.shell, entries, events, user: deps.user });
|
|
83
99
|
app.use(notFound);
|
|
84
100
|
app.use(errorHandler(deps.log));
|
|
85
101
|
return app;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type RequestHandler } from 'express';
|
|
2
|
+
export type ShellEvent = 'extensions' | 'app';
|
|
3
|
+
export interface ShellEvents {
|
|
4
|
+
send(event: ShellEvent, data: unknown): void;
|
|
5
|
+
stream: RequestHandler;
|
|
6
|
+
}
|
|
7
|
+
export declare const HEARTBEAT_MS = 25000;
|
|
8
|
+
export declare const STALLED_WRITES = 32;
|
|
9
|
+
export declare const shellEvents: (heartbeatMs?: number) => ShellEvents;
|