@agentage/extension 0.6.1 → 0.8.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.
- package/dist/agcid/current.d.ts +2 -0
- package/dist/agcid/current.js +1 -0
- package/dist/agcid/fetch.d.ts +1 -0
- package/dist/agcid/fetch.js +11 -0
- package/dist/agcid/scope.js +4 -2
- package/dist/api/openapi-doc.js +55 -19
- package/dist/api/page.d.ts +14 -0
- package/dist/api/page.js +33 -0
- package/dist/api/routes.d.ts +18 -8
- package/dist/api/routes.js +4 -2
- package/dist/api/well-known.d.ts +13 -0
- package/dist/api/well-known.js +13 -0
- package/dist/auth/revoked.js +2 -1
- package/dist/auth/token-check.d.ts +1 -1
- package/dist/auth/token-check.js +8 -4
- package/dist/auth/verify-token.d.ts +2 -1
- package/dist/auth/verify-token.js +3 -2
- package/dist/command/check-cli.js +3 -2
- package/dist/command/cli-context.d.ts +15 -0
- package/dist/command/cli-context.js +34 -0
- package/dist/command/command.types.d.ts +11 -0
- package/dist/command/command.types.js +3 -0
- package/dist/command/run-command.d.ts +4 -1
- package/dist/command/run-command.js +12 -8
- package/dist/context/context.js +1 -1
- package/dist/context/recording-log.d.ts +7 -0
- package/dist/context/recording-log.js +10 -0
- package/dist/context/test-command-context.d.ts +34 -0
- package/dist/context/test-command-context.js +51 -0
- package/dist/context/test-context.d.ts +6 -23
- package/dist/context/test-context.js +7 -35
- package/dist/envelope/envelope.d.ts +12 -0
- package/dist/envelope/envelope.js +8 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +3 -1
- package/dist/log/log.d.ts +3 -0
- package/dist/log/log.js +24 -7
- package/dist/mcp/snapshot.js +2 -1
- package/dist/mcp/tools.d.ts +1 -1
- package/dist/runtime/part-runners.js +2 -2
- package/dist/runtime/run-part.js +1 -1
- package/dist/server/api-routes.d.ts +2 -0
- package/dist/server/api-routes.js +14 -7
- package/dist/server/app.d.ts +2 -0
- package/dist/server/app.js +15 -0
- package/dist/server/request-line.d.ts +4 -0
- package/dist/server/request-line.js +25 -0
- package/dist/store/kit-migrations.d.ts +7 -0
- package/dist/store/kit-migrations.js +18 -0
- package/dist/store/migrate.js +1 -1
- package/dist/store/migrations.js +14 -6
- package/dist/testing/test-caller.d.ts +2 -0
- package/dist/testing/test-caller.js +13 -0
- package/dist/testing/test-server.d.ts +2 -0
- package/dist/testing/test-server.js +15 -4
- package/dist/tool/record-extras.js +2 -1
- package/dist/worker/runs.d.ts +1 -1
- package/dist/worker/runs.js +7 -12
- package/dist/worker/scheduler.js +8 -1
- package/package.json +1 -1
package/dist/agcid/current.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
2
|
interface RequestScope {
|
|
3
3
|
agcid: string;
|
|
4
|
+
traceparent?: string;
|
|
4
5
|
}
|
|
5
6
|
export declare const requestScope: AsyncLocalStorage<RequestScope>;
|
|
6
7
|
export declare const currentAgcid: () => string | undefined;
|
|
8
|
+
export declare const TRACEPARENT_PATTERN: RegExp;
|
|
7
9
|
export {};
|
package/dist/agcid/current.js
CHANGED
|
@@ -2,3 +2,4 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
// Apart from the middleware, so code the cli loads (logs, the build tool) never imports express.
|
|
3
3
|
export const requestScope = new AsyncLocalStorage();
|
|
4
4
|
export const currentAgcid = () => requestScope.getStore()?.agcid;
|
|
5
|
+
export const TRACEPARENT_PATTERN = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const kitFetch: (url: string, init?: RequestInit, impl?: typeof fetch) => Promise<Response>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AGCID_HEADER, uuidv7 } from './agcid.js';
|
|
2
|
+
import { requestScope } from './current.js';
|
|
3
|
+
// Every fetch the kit makes: the scope's agcid (a fresh one outside a scope) and its traceparent.
|
|
4
|
+
export const kitFetch = (url, init = {}, impl = fetch) => {
|
|
5
|
+
const scope = requestScope.getStore();
|
|
6
|
+
const headers = new Headers(init.headers);
|
|
7
|
+
headers.set(AGCID_HEADER, scope?.agcid ?? uuidv7());
|
|
8
|
+
if (scope?.traceparent)
|
|
9
|
+
headers.set('traceparent', scope.traceparent);
|
|
10
|
+
return impl(url, { ...init, headers });
|
|
11
|
+
};
|
package/dist/agcid/scope.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import {} from 'express';
|
|
2
2
|
import { AGCID_HEADER, agcidOf } from './agcid.js';
|
|
3
|
-
import { requestScope } from './current.js';
|
|
3
|
+
import { requestScope, TRACEPARENT_PATTERN } from './current.js';
|
|
4
4
|
// Keeps a valid incoming agcid, else mints one; echoed on every response and tags every log line.
|
|
5
5
|
export const agcidMiddleware = (req, res, next) => {
|
|
6
6
|
const agcid = agcidOf(req.get(AGCID_HEADER));
|
|
7
7
|
res.locals['agcid'] = agcid;
|
|
8
8
|
res.setHeader(AGCID_HEADER, agcid);
|
|
9
|
-
|
|
9
|
+
const traceparent = req.get('traceparent');
|
|
10
|
+
const valid = traceparent !== undefined && TRACEPARENT_PATTERN.test(traceparent);
|
|
11
|
+
requestScope.run(valid ? { agcid, traceparent } : { agcid }, next);
|
|
10
12
|
};
|
|
11
13
|
export const agcidOfResponse = (res) => {
|
|
12
14
|
const agcid = res.locals['agcid'];
|
package/dist/api/openapi-doc.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { scopeOf } from '../auth/token-check.js';
|
|
2
|
+
import {} from '../envelope/codes.js';
|
|
2
3
|
import { ErrorEnvelopeSchema } from '../envelope/envelope.schema.js';
|
|
3
4
|
import {} from '../manifest/manifest.schema.js';
|
|
4
5
|
import {} from './routes.js';
|
|
@@ -11,44 +12,76 @@ const bare = (zod, io) => {
|
|
|
11
12
|
};
|
|
12
13
|
const json = (schema) => ({ 'application/json': { schema } });
|
|
13
14
|
const content = (description, schema) => ({ description, content: json(schema) });
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
const STRING = { type: 'string' };
|
|
16
|
+
const okResponse = ({ output, etag }) => ({
|
|
17
|
+
...content('the envelope', {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
success: { type: 'boolean', const: true },
|
|
21
|
+
data: output ? bare(output, 'output') : {},
|
|
22
|
+
},
|
|
23
|
+
required: ['success', 'data'],
|
|
24
|
+
}),
|
|
25
|
+
...(etag && { headers: { ETag: { schema: STRING } } }),
|
|
21
26
|
});
|
|
22
|
-
const
|
|
27
|
+
const refusal = (code) => content(code, { $ref: '#/components/schemas/Error' });
|
|
23
28
|
const inQuery = ({ method }) => method === 'get' || method === 'delete';
|
|
24
|
-
const
|
|
25
|
-
|
|
29
|
+
const fields = (zod) => bare(zod, 'input');
|
|
30
|
+
const pathParameters = ({ path, spec }) => {
|
|
31
|
+
const typed = spec.params ? (fields(spec.params).properties ?? {}) : {};
|
|
32
|
+
return [...path.matchAll(/\{(\w+)\}/g)].map(([, name = '']) => ({
|
|
26
33
|
name,
|
|
27
34
|
in: 'path',
|
|
28
35
|
required: true,
|
|
29
|
-
schema:
|
|
36
|
+
schema: typed[name] ?? STRING,
|
|
30
37
|
}));
|
|
38
|
+
};
|
|
39
|
+
const queryParameters = (entry) => {
|
|
31
40
|
if (!entry.spec.input || !inQuery(entry))
|
|
32
|
-
return
|
|
33
|
-
const { properties = {}, required = [] } =
|
|
34
|
-
|
|
41
|
+
return [];
|
|
42
|
+
const { properties = {}, required = [] } = fields(entry.spec.input);
|
|
43
|
+
return Object.entries(properties).map(([name, schema]) => ({
|
|
35
44
|
name,
|
|
36
45
|
in: 'query',
|
|
37
46
|
required: required.includes(name),
|
|
38
47
|
schema,
|
|
39
48
|
}));
|
|
40
|
-
|
|
49
|
+
};
|
|
50
|
+
const IF_MATCH = { name: 'If-Match', in: 'header', required: false, schema: STRING };
|
|
51
|
+
const parameters = (entry) => [
|
|
52
|
+
...pathParameters(entry),
|
|
53
|
+
...queryParameters(entry),
|
|
54
|
+
...(entry.spec.etag ? [IF_MATCH] : []),
|
|
55
|
+
];
|
|
56
|
+
const responses = (entry) => {
|
|
57
|
+
const { input, params, scope, etag } = entry.spec;
|
|
58
|
+
return {
|
|
59
|
+
'200': okResponse(entry.spec),
|
|
60
|
+
...((input || params) && { '400': refusal('VALIDATION_ERROR') }),
|
|
61
|
+
...(scope !== 'public' && { '401': refusal('UNAUTHORIZED'), '403': refusal('FORBIDDEN') }),
|
|
62
|
+
...(entry.path.includes('{') && { '404': refusal('NOT_FOUND') }),
|
|
63
|
+
// If-Match absent on a PUT overwrites (no 428); only a stale tag is refused.
|
|
64
|
+
...(etag && { '412': refusal('PRECONDITION_FAILED') }),
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
const securityOf = (id, scope) => {
|
|
68
|
+
if (scope === 'public')
|
|
69
|
+
return [];
|
|
70
|
+
// The empty requirement lets a call through anonymous; a bearer sent must grant read.
|
|
71
|
+
if (scope === 'optional')
|
|
72
|
+
return [{}, { pat: [scopeOf(id, 'read')] }];
|
|
73
|
+
return [{ pat: [scopeOf(id, scope)] }];
|
|
41
74
|
};
|
|
42
75
|
const operation = (id, entry) => {
|
|
43
|
-
const { summary, scope, input
|
|
76
|
+
const { summary, scope, input } = entry.spec;
|
|
44
77
|
const params = parameters(entry);
|
|
45
78
|
return {
|
|
46
79
|
summary,
|
|
47
|
-
security:
|
|
80
|
+
security: securityOf(id, scope),
|
|
48
81
|
...(params.length > 0 && { parameters: params }),
|
|
49
82
|
...(input &&
|
|
50
83
|
!inQuery(entry) && { requestBody: { required: true, content: json(bare(input, 'input')) } }),
|
|
51
|
-
responses:
|
|
84
|
+
responses: responses(entry),
|
|
52
85
|
};
|
|
53
86
|
};
|
|
54
87
|
// The api's contract from its ctx.route declarations: what openapi.json must hold.
|
|
@@ -62,7 +95,10 @@ export const generatedOpenapi = (pkg, routes) => {
|
|
|
62
95
|
return {
|
|
63
96
|
openapi: '3.1.0',
|
|
64
97
|
info: { title: id, version: pkg.version },
|
|
65
|
-
components: {
|
|
98
|
+
components: {
|
|
99
|
+
securitySchemes: { pat: { type: 'http', scheme: 'bearer' } },
|
|
100
|
+
schemas: { Error: bare(ErrorEnvelopeSchema, 'input') },
|
|
101
|
+
},
|
|
66
102
|
paths,
|
|
67
103
|
};
|
|
68
104
|
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type Reply } from '../envelope/envelope.js';
|
|
3
|
+
export declare const MAX_LIMIT = 200;
|
|
4
|
+
export declare const PageQuerySchema: z.ZodObject<{
|
|
5
|
+
cursor: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
6
|
+
limit: z.ZodPipe<z.ZodDefault<z.ZodCoercedNumber<unknown>>, z.ZodTransform<number, number>>;
|
|
7
|
+
}, z.core.$strip>;
|
|
8
|
+
export interface Pagination {
|
|
9
|
+
limit: number;
|
|
10
|
+
nextCursor?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare const pageOf: <T extends {
|
|
13
|
+
id: string | number;
|
|
14
|
+
}>(rows: readonly T[], limit: number) => Reply<T[]>;
|
package/dist/api/page.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { reply } from '../envelope/envelope.js';
|
|
3
|
+
// api-standards section 3: default 50, a limit above 200 is clamped, not refused.
|
|
4
|
+
export const MAX_LIMIT = 200;
|
|
5
|
+
const encode = (id) => Buffer.from(id).toString('base64url');
|
|
6
|
+
// The cursor is the last row's id, opaque on the wire; parsed back to that id here.
|
|
7
|
+
const CursorSchema = z
|
|
8
|
+
.string()
|
|
9
|
+
.regex(/^[A-Za-z0-9_-]{1,256}$/)
|
|
10
|
+
.transform((cursor, ctx) => {
|
|
11
|
+
const id = Buffer.from(cursor, 'base64url').toString();
|
|
12
|
+
if (id && encode(id) === cursor)
|
|
13
|
+
return id;
|
|
14
|
+
ctx.issues.push({ code: 'custom', message: 'Invalid cursor', input: cursor });
|
|
15
|
+
return z.NEVER;
|
|
16
|
+
});
|
|
17
|
+
export const PageQuerySchema = z.object({
|
|
18
|
+
cursor: CursorSchema.optional(),
|
|
19
|
+
limit: z.coerce
|
|
20
|
+
.number()
|
|
21
|
+
.int()
|
|
22
|
+
.min(1)
|
|
23
|
+
.default(50)
|
|
24
|
+
.describe(`page size; a limit above ${MAX_LIMIT} is clamped to ${MAX_LIMIT}`)
|
|
25
|
+
.transform((limit) => Math.min(limit, MAX_LIMIT)),
|
|
26
|
+
});
|
|
27
|
+
// rows: up to limit + 1 read after the cursor; the extra row says a next page exists.
|
|
28
|
+
export const pageOf = (rows, limit) => {
|
|
29
|
+
const items = rows.slice(0, limit);
|
|
30
|
+
const last = rows.length > limit ? items.at(-1) : undefined;
|
|
31
|
+
const pagination = { limit, ...(last && { nextCursor: encode(String(last.id)) }) };
|
|
32
|
+
return reply(items, { meta: { pagination } });
|
|
33
|
+
};
|
package/dist/api/routes.d.ts
CHANGED
|
@@ -1,35 +1,45 @@
|
|
|
1
1
|
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
|
+
import { type Reply } from '../envelope/envelope.js';
|
|
5
|
+
import { type WellKnownRegistrar } from './well-known.js';
|
|
4
6
|
export declare const ROUTE_METHODS: readonly ["get", "post", "put", "patch", "delete"];
|
|
5
7
|
export type RouteMethod = (typeof ROUTE_METHODS)[number];
|
|
6
8
|
type ObjectSchema = z.ZodObject;
|
|
7
|
-
export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extends Access = Access> {
|
|
9
|
+
export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extends Access = Access, Q extends ObjectSchema = never> {
|
|
8
10
|
summary: string;
|
|
9
11
|
scope?: S;
|
|
10
12
|
input?: I;
|
|
11
13
|
output?: O;
|
|
14
|
+
params?: Q;
|
|
15
|
+
etag?: true;
|
|
12
16
|
}
|
|
13
17
|
export type ParamsOf<P extends string> = P extends `${string}{${infer N}}${infer R}` ? {
|
|
14
18
|
[K in N]: string;
|
|
15
19
|
} & ParamsOf<R> : Record<never, string>;
|
|
16
|
-
export interface RouteRequest<I, P extends string, S extends Access = Access> {
|
|
20
|
+
export interface RouteRequest<I, P extends string, S extends Access = Access, Q = never> {
|
|
17
21
|
input: I;
|
|
18
|
-
params: ParamsOf<P
|
|
19
|
-
caller: S extends 'public' ? Caller | null : Caller;
|
|
22
|
+
params: [Q] extends [never] ? ParamsOf<P> : Q;
|
|
23
|
+
caller: S extends 'public' | 'optional' ? Caller | null : Caller;
|
|
24
|
+
ifMatch?: string;
|
|
20
25
|
}
|
|
21
|
-
|
|
22
|
-
export type
|
|
26
|
+
type Answer<T> = T | Reply<T>;
|
|
27
|
+
export type RouteHandler<I extends ObjectSchema, O extends z.ZodType, P extends string, S extends Access = Access, Q extends ObjectSchema = never> = (request: RouteRequest<z.output<I>, P, S, [Q] extends [never] ? never : z.output<Q>>) => Answer<z.input<O>> | Promise<Answer<z.input<O>>>;
|
|
28
|
+
export type RouteRegistrar = <P extends string, I extends ObjectSchema = z.ZodObject<Record<never, z.ZodType>>, O extends z.ZodType = z.ZodUnknown, S extends Access = 'read', Q extends ObjectSchema = never>(method: RouteMethod, path: P, spec: RouteSpec<I, O, S, Q>, handler: RouteHandler<I, O, P, S, Q>) => void;
|
|
23
29
|
export interface ApiContext extends PartContext {
|
|
24
30
|
readonly route: RouteRegistrar;
|
|
31
|
+
readonly wellKnown: WellKnownRegistrar;
|
|
25
32
|
}
|
|
33
|
+
type Params = Record<string, unknown>;
|
|
26
34
|
export interface RouteEntry {
|
|
27
35
|
method: RouteMethod;
|
|
28
36
|
path: string;
|
|
29
|
-
spec: RouteSpec<ObjectSchema, z.ZodType>;
|
|
30
|
-
handler: (request: RouteRequest<Record<string, unknown>, string, 'public'>) => unknown;
|
|
37
|
+
spec: RouteSpec<ObjectSchema, z.ZodType, Access, ObjectSchema>;
|
|
38
|
+
handler: (request: RouteRequest<Record<string, unknown>, string, 'public', Params>) => unknown;
|
|
31
39
|
}
|
|
32
40
|
export declare const createRouteRegistry: () => {
|
|
41
|
+
wellKnown: WellKnownRegistrar;
|
|
42
|
+
documents: import("./well-known.js").WellKnownEntry[];
|
|
33
43
|
route: RouteRegistrar;
|
|
34
44
|
routes: RouteEntry[];
|
|
35
45
|
};
|
package/dist/api/routes.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import {} from 'zod';
|
|
2
2
|
import {} from '../auth/token-check.js';
|
|
3
3
|
import {} from '../context/context.js';
|
|
4
|
+
import {} from '../envelope/envelope.js';
|
|
5
|
+
import { createWellKnownRegistry } from './well-known.js';
|
|
4
6
|
export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
|
|
5
7
|
const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
|
|
6
|
-
const SCOPES = ['public', 'read', 'write', 'admin'];
|
|
8
|
+
const SCOPES = ['public', 'optional', 'read', 'write', 'admin'];
|
|
7
9
|
const problemOf = (routes, { method, path, spec }) => {
|
|
8
10
|
if (!ROUTE_METHODS.includes(method))
|
|
9
11
|
return `method ${String(method)}: one of get, post, put, patch, delete`;
|
|
@@ -26,5 +28,5 @@ export const createRouteRegistry = () => {
|
|
|
26
28
|
throw new Error(`route ${String(method).toUpperCase()} ${path} ${problem}`);
|
|
27
29
|
routes.push(entry);
|
|
28
30
|
};
|
|
29
|
-
return { route, routes };
|
|
31
|
+
return { route, routes, ...createWellKnownRegistry() };
|
|
30
32
|
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const WELL_KNOWN: readonly ["agentage.json", "mcp-registry-auth"];
|
|
2
|
+
export type WellKnownName = (typeof WELL_KNOWN)[number];
|
|
3
|
+
export type WellKnownDoc = Record<string, unknown> | string;
|
|
4
|
+
export type WellKnownRender = () => WellKnownDoc | Promise<WellKnownDoc>;
|
|
5
|
+
export type WellKnownRegistrar = (name: WellKnownName, render: WellKnownRender) => void;
|
|
6
|
+
export interface WellKnownEntry {
|
|
7
|
+
name: WellKnownName;
|
|
8
|
+
render: WellKnownRender;
|
|
9
|
+
}
|
|
10
|
+
export declare const createWellKnownRegistry: () => {
|
|
11
|
+
wellKnown: WellKnownRegistrar;
|
|
12
|
+
documents: WellKnownEntry[];
|
|
13
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// api-standards section 1: the closed names an api part may serve under /.well-known/.
|
|
2
|
+
export const WELL_KNOWN = ['agentage.json', 'mcp-registry-auth'];
|
|
3
|
+
export const createWellKnownRegistry = () => {
|
|
4
|
+
const documents = [];
|
|
5
|
+
const wellKnown = (name, render) => {
|
|
6
|
+
if (!WELL_KNOWN.includes(name))
|
|
7
|
+
throw new Error(`well-known ${String(name)}: one of ${WELL_KNOWN.join(', ')}`);
|
|
8
|
+
if (documents.some((entry) => entry.name === name))
|
|
9
|
+
throw new Error(`well-known ${name} is registered twice`);
|
|
10
|
+
documents.push({ name, render });
|
|
11
|
+
};
|
|
12
|
+
return { wellKnown, documents };
|
|
13
|
+
};
|
package/dist/auth/revoked.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { kitFetch } from '../agcid/fetch.js';
|
|
2
3
|
import {} from '../health/health.js';
|
|
3
4
|
import { messageOf } from '../log/log.js';
|
|
4
5
|
import { retryOnce } from './token-check.js';
|
|
@@ -9,7 +10,7 @@ const RevokedSchema = z.object({
|
|
|
9
10
|
generatedAt: z.string(),
|
|
10
11
|
});
|
|
11
12
|
const readList = async (url) => {
|
|
12
|
-
const res = await
|
|
13
|
+
const res = await kitFetch(url, { signal: AbortSignal.timeout(5000) });
|
|
13
14
|
if (!res.ok)
|
|
14
15
|
throw new Error(`the issuer answered ${res.status}`);
|
|
15
16
|
return new Set(RevokedSchema.parse(await res.json()).revoked.map((entry) => entry.jti));
|
package/dist/auth/token-check.js
CHANGED
|
@@ -2,19 +2,23 @@ import { setTimeout as sleep } from 'node:timers/promises';
|
|
|
2
2
|
const callers = new WeakMap();
|
|
3
3
|
export const setCaller = (request, caller) => void callers.set(request, caller);
|
|
4
4
|
export const callerOf = (request) => callers.get(request) ?? null;
|
|
5
|
-
export const RANK = { public: 0,
|
|
6
|
-
export const scopeOf = (id, access = 'read') => access === 'public' ? 'public' : `${id}:${access}`;
|
|
5
|
+
export const RANK = { public: 0, optional: 1, read: 2, write: 3, admin: 4 };
|
|
6
|
+
export const scopeOf = (id, access = 'read') => access === 'public' ? 'public' : `${id}:${access === 'optional' ? 'read' : access}`;
|
|
7
7
|
export const strongest = (needed) => needed.reduce((top, access) => (RANK[access] > RANK[top] ? access : top), 'public');
|
|
8
8
|
const VERB = /:(read|write|admin)$/;
|
|
9
|
-
|
|
9
|
+
const isAnonymous = (requirement) => typeof requirement === 'object' && requirement !== null && Object.keys(requirement).length === 0;
|
|
10
|
+
// OpenAPI security: [] is public, [{}, {pat}] optional, a scope names the verb; nothing declared needs read.
|
|
10
11
|
export const accessOfSecurity = (security) => {
|
|
11
12
|
if (Array.isArray(security) && security.length === 0)
|
|
12
13
|
return 'public';
|
|
13
|
-
const
|
|
14
|
+
const requirements = Array.isArray(security) ? security : [];
|
|
15
|
+
const scopes = requirements
|
|
14
16
|
.flatMap((requirement) => Object.values(requirement ?? {}))
|
|
15
17
|
.flat()
|
|
16
18
|
.filter((scope) => typeof scope === 'string');
|
|
17
19
|
const verbs = scopes.map((scope) => VERB.exec(scope)?.[1] ?? 'read');
|
|
20
|
+
if (requirements.some(isAnonymous))
|
|
21
|
+
return verbs.length === 0 ? 'public' : 'optional';
|
|
18
22
|
return verbs.length === 0 ? 'read' : strongest(verbs);
|
|
19
23
|
};
|
|
20
24
|
// security.md: a failed read of the issuer is tried once more before it counts as an outage.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type JWTVerifyGetKey } from 'jose';
|
|
2
|
-
import { type TokenCheck } from './token-check.js';
|
|
2
|
+
import { type Access, type TokenCheck } from './token-check.js';
|
|
3
3
|
export interface TokenCheckDeps {
|
|
4
4
|
issuer: string;
|
|
5
5
|
audience: string;
|
|
@@ -16,4 +16,5 @@ export declare const remoteKeys: (issuer: string) => {
|
|
|
16
16
|
read: () => Promise<void>;
|
|
17
17
|
held: () => boolean;
|
|
18
18
|
};
|
|
19
|
+
export declare const grants: (scope: string, id: string, access: Access) => boolean;
|
|
19
20
|
export declare const createTokenCheck: (deps: TokenCheckDeps) => TokenCheck;
|
|
@@ -49,12 +49,13 @@ const claimsOf = async (authorization, deps) => {
|
|
|
49
49
|
throw invalid(deps.origin);
|
|
50
50
|
return claims.data;
|
|
51
51
|
};
|
|
52
|
-
const grants = (scope, id, access) => {
|
|
52
|
+
export const grants = (scope, id, access) => {
|
|
53
53
|
const held = new Set(scope.split(' '));
|
|
54
54
|
return ['read', 'write', 'admin'].some((verb) => RANK[verb] >= RANK[access] && held.has(`${id}:${verb}`));
|
|
55
55
|
};
|
|
56
56
|
export const createTokenCheck = (deps) => async (authorization, access) => {
|
|
57
|
-
|
|
57
|
+
// optional: no bearer is anonymous, but a bearer sent is checked like read, never ignored.
|
|
58
|
+
if (access === 'public' || (access === 'optional' && !authorization))
|
|
58
59
|
return null;
|
|
59
60
|
if (!authorization)
|
|
60
61
|
throw invalid(deps.origin, 'Missing token');
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readManifest } from '../manifest/read-manifest.js';
|
|
2
2
|
import { createOut } from './out.js';
|
|
3
|
-
import {
|
|
3
|
+
import { cliContext } from './cli-context.js';
|
|
4
|
+
import { loadHandlers } from './run-command.js';
|
|
4
5
|
const quiet = () => undefined;
|
|
5
6
|
// null when the cli entry exports create and its handlers are exactly the declared commands.
|
|
6
7
|
export const checkCli = async (dir) => {
|
|
@@ -8,7 +9,7 @@ export const checkCli = async (dir) => {
|
|
|
8
9
|
const pkg = await readManifest(dir);
|
|
9
10
|
const declared = (pkg.agentage.commands ?? []).map((command) => command.name).sort();
|
|
10
11
|
const out = createOut({ json: false, stdout: quiet, stderr: quiet });
|
|
11
|
-
const handlers = Object.keys(await loadHandlers(dir, pkg,
|
|
12
|
+
const handlers = Object.keys(await loadHandlers(dir, pkg, cliContext(pkg, { command: 'check', args: {}, out, stderr: quiet }))).sort();
|
|
12
13
|
if (JSON.stringify(handlers) === JSON.stringify(declared))
|
|
13
14
|
return null;
|
|
14
15
|
return `cli handlers [${handlers.join(', ')}] differ from commands [${declared.join(', ')}]`;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type Caller } from '../auth/token-check.js';
|
|
2
|
+
import { type ExtensionPackage } from '../manifest/manifest.schema.js';
|
|
3
|
+
import { type CliClient, type CliContext } from './command.types.js';
|
|
4
|
+
import { type Out, type Write } from './out.js';
|
|
5
|
+
export interface CommandRun {
|
|
6
|
+
command: string;
|
|
7
|
+
args: CliContext['args'];
|
|
8
|
+
out: Out;
|
|
9
|
+
stderr: Write;
|
|
10
|
+
user?: Caller | null;
|
|
11
|
+
client?: CliClient;
|
|
12
|
+
dataDir?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare const NO_CLIENT: CliClient;
|
|
15
|
+
export declare const cliContext: (pkg: ExtensionPackage, run: CommandRun) => CliContext;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import {} from '../auth/token-check.js';
|
|
4
|
+
import { createLog } from '../log/log.js';
|
|
5
|
+
import {} from '../manifest/manifest.schema.js';
|
|
6
|
+
import {} from './command.types.js';
|
|
7
|
+
import {} from './out.js';
|
|
8
|
+
const unwired = () => Promise.reject(new Error('ctx.client: this host does not provide a client yet'));
|
|
9
|
+
export const NO_CLIENT = Object.freeze({ api: unwired, tool: unwired });
|
|
10
|
+
// Owner-only, made on first read, so --help and the build check never create a folder.
|
|
11
|
+
const ownDir = (dataDir, id) => () => {
|
|
12
|
+
if (dataDir === undefined)
|
|
13
|
+
throw new Error('ctx.dir: this host passes no data dir');
|
|
14
|
+
const dir = join(dataDir, id);
|
|
15
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
16
|
+
chmodSync(dir, 0o700);
|
|
17
|
+
return dir;
|
|
18
|
+
};
|
|
19
|
+
export const cliContext = (pkg, run) => {
|
|
20
|
+
const { id } = pkg.agentage;
|
|
21
|
+
const tags = { extension: id, part: 'cli', version: pkg.version, base: { command: run.command } };
|
|
22
|
+
const dir = ownDir(run.dataDir, id);
|
|
23
|
+
return Object.freeze({
|
|
24
|
+
extension: Object.freeze({ id, version: pkg.version, part: 'cli' }),
|
|
25
|
+
args: Object.freeze(run.args),
|
|
26
|
+
out: run.out,
|
|
27
|
+
log: createLog(tags, run.stderr),
|
|
28
|
+
user: run.user ?? null,
|
|
29
|
+
client: run.client ?? NO_CLIENT,
|
|
30
|
+
get dir() {
|
|
31
|
+
return dir();
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
};
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { type RouteMethod } from '../api/routes.js';
|
|
2
|
+
import { type Caller } from '../auth/token-check.js';
|
|
3
|
+
import { type Log } from '../log/log.js';
|
|
1
4
|
import { type Out } from './out.js';
|
|
2
5
|
import { type ArgValue } from './args.js';
|
|
3
6
|
export interface CommandExtension {
|
|
@@ -5,10 +8,18 @@ export interface CommandExtension {
|
|
|
5
8
|
version: string;
|
|
6
9
|
part: 'cli';
|
|
7
10
|
}
|
|
11
|
+
export interface CliClient {
|
|
12
|
+
api(method: RouteMethod, path: string, input?: unknown): Promise<unknown>;
|
|
13
|
+
tool(name: string, args?: Record<string, unknown>): Promise<unknown>;
|
|
14
|
+
}
|
|
8
15
|
export interface CliContext {
|
|
9
16
|
readonly extension: Readonly<CommandExtension>;
|
|
10
17
|
readonly args: Readonly<Record<string, ArgValue>>;
|
|
11
18
|
readonly out: Out;
|
|
19
|
+
readonly log: Log;
|
|
20
|
+
readonly user: Caller | null;
|
|
21
|
+
readonly client: CliClient;
|
|
22
|
+
readonly dir: string;
|
|
12
23
|
}
|
|
13
24
|
export type CommandHandler = () => unknown;
|
|
14
25
|
export type CliCreate = (ctx: CliContext) => Record<string, CommandHandler>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ExtensionPackage } from '../manifest/manifest.schema.js';
|
|
2
|
+
import { type CommandRun } from './cli-context.js';
|
|
2
3
|
import { type CliContext, type CommandHandler } from './command.types.js';
|
|
3
4
|
import { type Write } from './out.js';
|
|
4
5
|
export interface RunCommandOptions {
|
|
@@ -7,10 +8,12 @@ export interface RunCommandOptions {
|
|
|
7
8
|
argv: string[];
|
|
8
9
|
stdout?: Write;
|
|
9
10
|
stderr?: Write;
|
|
11
|
+
user?: CommandRun['user'];
|
|
12
|
+
client?: CommandRun['client'];
|
|
13
|
+
dataDir?: string;
|
|
10
14
|
}
|
|
11
15
|
export declare const EXIT_OK = 0;
|
|
12
16
|
export declare const EXIT_FAILED = 1;
|
|
13
17
|
export declare const EXIT_USAGE = 2;
|
|
14
18
|
export declare const loadHandlers: (dir: string, pkg: ExtensionPackage, ctx: CliContext) => Promise<Record<string, CommandHandler>>;
|
|
15
|
-
export declare const contextFor: (pkg: ExtensionPackage, args: CliContext["args"], out: CliContext["out"]) => CliContext;
|
|
16
19
|
export declare const runCommand: (o: RunCommandOptions) => Promise<number>;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { uuidv7 } from '../agcid/agcid.js';
|
|
2
|
+
import { requestScope } from '../agcid/current.js';
|
|
1
3
|
import { loadCreate } from '../manifest/entry.js';
|
|
2
4
|
import {} from '../manifest/manifest.schema.js';
|
|
3
5
|
import { readManifest } from '../manifest/read-manifest.js';
|
|
4
6
|
import { parseCommandArgs, usage, UsageError } from './args.js';
|
|
7
|
+
import { cliContext } from './cli-context.js';
|
|
5
8
|
import {} from './command.types.js';
|
|
6
9
|
import { createOut } from './out.js';
|
|
7
10
|
export const EXIT_OK = 0;
|
|
@@ -10,11 +13,6 @@ export const EXIT_USAGE = 2;
|
|
|
10
13
|
const writeOut = (text) => void process.stdout.write(text);
|
|
11
14
|
const writeErr = (text) => void process.stderr.write(text);
|
|
12
15
|
export const loadHandlers = async (dir, pkg, ctx) => (await loadCreate(dir, pkg, 'cli'))(ctx);
|
|
13
|
-
export const contextFor = (pkg, args, out) => ({
|
|
14
|
-
extension: Object.freeze({ id: pkg.agentage.id, version: pkg.version, part: 'cli' }),
|
|
15
|
-
args: Object.freeze(args),
|
|
16
|
-
out,
|
|
17
|
-
});
|
|
18
16
|
const execute = async (o, pkg, stdout, stderr) => {
|
|
19
17
|
const spec = pkg.agentage.commands?.find((command) => command.name === o.command);
|
|
20
18
|
if (!spec)
|
|
@@ -23,11 +21,17 @@ const execute = async (o, pkg, stdout, stderr) => {
|
|
|
23
21
|
if (parsed.help)
|
|
24
22
|
return (stdout(`${usage(spec)}\n`), EXIT_OK);
|
|
25
23
|
const out = createOut({ json: parsed.json, stdout, stderr });
|
|
26
|
-
const
|
|
24
|
+
const { user, client, dataDir, command } = o;
|
|
25
|
+
const ctx = cliContext(pkg, { command, args: parsed.args, out, stderr, user, client, dataDir });
|
|
26
|
+
// One agcid per command run: every log line and kit fetch of the run carries it.
|
|
27
|
+
const result = await requestScope.run({ agcid: uuidv7() }, () => handle(o, pkg, ctx));
|
|
28
|
+
return out.exitCode ?? (typeof result === 'number' ? result : EXIT_OK);
|
|
29
|
+
};
|
|
30
|
+
const handle = async (o, pkg, ctx) => {
|
|
31
|
+
const handler = (await loadHandlers(o.dir, pkg, ctx))[o.command];
|
|
27
32
|
if (typeof handler !== 'function')
|
|
28
33
|
throw new Error(`the cli entry has no handler for ${o.command}`);
|
|
29
|
-
|
|
30
|
-
return out.exitCode ?? (typeof result === 'number' ? result : EXIT_OK);
|
|
34
|
+
return handler();
|
|
31
35
|
};
|
|
32
36
|
// Exit codes: 0 ok, 2 usage, 1 failure (a throw, a missing handler, an invalid manifest).
|
|
33
37
|
export const runCommand = async (o) => {
|
package/dist/context/context.js
CHANGED
|
@@ -23,7 +23,7 @@ export const createContext = (input) => {
|
|
|
23
23
|
commit,
|
|
24
24
|
...(kind && { store: kind }),
|
|
25
25
|
});
|
|
26
|
-
const log = input.log ?? createLog({ extension: pkg.agentage.id, part });
|
|
26
|
+
const log = input.log ?? createLog({ extension: pkg.agentage.id, part, version: pkg.version });
|
|
27
27
|
const settings = Object.freeze({ ...settingDefaults(pkg), ...input.settings });
|
|
28
28
|
const auth = Object.freeze({ caller: callerOf });
|
|
29
29
|
const secrets = input.secrets ?? {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { messageOf } from '../log/log.js';
|
|
2
|
+
export const recordingLog = (logs) => ({
|
|
3
|
+
info: (message, fields = {}) => void logs.push({ level: 'info', message, fields }),
|
|
4
|
+
warn: (message, fields = {}) => void logs.push({ level: 'warn', message, fields }),
|
|
5
|
+
error: (error, fields = {}) => void logs.push({
|
|
6
|
+
level: 'error',
|
|
7
|
+
message: messageOf(error),
|
|
8
|
+
fields: { ...fields, err: error },
|
|
9
|
+
}),
|
|
10
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type ArgValue } from '../command/args.js';
|
|
2
|
+
import { type Caller } from '../auth/token-check.js';
|
|
3
|
+
import { type CliClient, type CliContext } from '../command/command.types.js';
|
|
4
|
+
import { type LogEntry } from './recording-log.js';
|
|
5
|
+
export type ClientCall = {
|
|
6
|
+
kind: 'api';
|
|
7
|
+
method: string;
|
|
8
|
+
path: string;
|
|
9
|
+
input?: unknown;
|
|
10
|
+
} | {
|
|
11
|
+
kind: 'tool';
|
|
12
|
+
name: string;
|
|
13
|
+
args?: Record<string, unknown>;
|
|
14
|
+
};
|
|
15
|
+
export interface TestCommandContext extends CliContext {
|
|
16
|
+
readonly output: {
|
|
17
|
+
stdout: string[];
|
|
18
|
+
stderr: string[];
|
|
19
|
+
};
|
|
20
|
+
readonly exitCode: number | undefined;
|
|
21
|
+
readonly logs: LogEntry[];
|
|
22
|
+
readonly calls: ClientCall[];
|
|
23
|
+
}
|
|
24
|
+
export interface TestCommandOptions {
|
|
25
|
+
args: Record<string, ArgValue>;
|
|
26
|
+
extension?: {
|
|
27
|
+
id?: string;
|
|
28
|
+
version?: string;
|
|
29
|
+
};
|
|
30
|
+
json?: boolean;
|
|
31
|
+
user?: Caller | null;
|
|
32
|
+
client?: Partial<CliClient>;
|
|
33
|
+
}
|
|
34
|
+
export declare const commandContext: (options: TestCommandOptions) => TestCommandContext;
|