@agentage/extension 0.7.0 → 0.9.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 (62) hide show
  1. package/dist/agcid/agcid.d.ts +1 -3
  2. package/dist/agcid/agcid.js +2 -3
  3. package/dist/agcid/current.d.ts +2 -0
  4. package/dist/agcid/current.js +1 -0
  5. package/dist/agcid/fetch.d.ts +1 -0
  6. package/dist/agcid/fetch.js +11 -0
  7. package/dist/agcid/header.d.ts +3 -0
  8. package/dist/agcid/header.js +3 -0
  9. package/dist/agcid/scope.js +4 -2
  10. package/dist/api/openapi-doc.d.ts +1 -0
  11. package/dist/api/openapi-doc.js +5 -3
  12. package/dist/api/routes.js +2 -5
  13. package/dist/auth/part-auth.d.ts +1 -0
  14. package/dist/auth/part-auth.js +1 -1
  15. package/dist/auth/revoked.js +2 -1
  16. package/dist/auth/token-check.d.ts +5 -2
  17. package/dist/auth/token-check.js +10 -3
  18. package/dist/auth/verify-token.js +2 -2
  19. package/dist/command/check-cli.js +3 -2
  20. package/dist/command/cli-context.d.ts +15 -0
  21. package/dist/command/cli-context.js +37 -0
  22. package/dist/command/command.types.d.ts +13 -0
  23. package/dist/command/command.types.js +4 -0
  24. package/dist/command/run-command.d.ts +4 -1
  25. package/dist/command/run-command.js +12 -8
  26. package/dist/context/context.d.ts +2 -0
  27. package/dist/context/context.js +4 -2
  28. package/dist/context/recording-log.d.ts +7 -0
  29. package/dist/context/recording-log.js +10 -0
  30. package/dist/context/test-command-context.d.ts +36 -0
  31. package/dist/context/test-command-context.js +60 -0
  32. package/dist/context/test-context.d.ts +6 -23
  33. package/dist/context/test-context.js +10 -35
  34. package/dist/contracts/index.d.ts +6 -0
  35. package/dist/contracts/index.js +6 -0
  36. package/dist/envelope/envelope.schema.js +1 -1
  37. package/dist/index.d.ts +8 -12
  38. package/dist/index.js +7 -10
  39. package/dist/log/log.d.ts +6 -0
  40. package/dist/log/log.js +29 -8
  41. package/dist/log/span.d.ts +9 -0
  42. package/dist/log/span.js +19 -0
  43. package/dist/mcp/snapshot.js +2 -1
  44. package/dist/mcp/tools.js +5 -4
  45. package/dist/pages/pages-app.js +2 -3
  46. package/dist/runtime/build-info.d.ts +1 -0
  47. package/dist/runtime/build-info.js +2 -1
  48. package/dist/runtime/part-runners.js +7 -1
  49. package/dist/runtime/run-part.js +1 -1
  50. package/dist/server/api-routes.js +1 -1
  51. package/dist/server/app.js +3 -0
  52. package/dist/server/request-line.d.ts +4 -0
  53. package/dist/server/request-line.js +25 -0
  54. package/dist/store/migrate.js +1 -1
  55. package/dist/tool/build-info.js +4 -4
  56. package/dist/tool/index.d.ts +4 -1
  57. package/dist/tool/index.js +4 -1
  58. package/dist/worker/run-log.js +7 -3
  59. package/dist/worker/runs.d.ts +1 -0
  60. package/dist/worker/runs.js +4 -2
  61. package/dist/worker/scheduler.js +8 -1
  62. package/package.json +5 -1
@@ -1,5 +1,3 @@
1
- export declare const AGCID_HEADER = "agcid";
2
- export declare const AGCID_PATTERN: RegExp;
3
- export declare const isAgcid: (value: unknown) => value is string;
1
+ export { AGCID_HEADER, AGCID_PATTERN, isAgcid } from './header.js';
4
2
  export declare const uuidv7: (now?: number, random?: Buffer) => string;
5
3
  export declare const agcidOf: (incoming: unknown) => string;
@@ -1,7 +1,6 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- export const AGCID_HEADER = 'agcid';
3
- export const AGCID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
4
- export const isAgcid = (value) => typeof value === 'string' && AGCID_PATTERN.test(value);
2
+ import { isAgcid } from './header.js';
3
+ export { AGCID_HEADER, AGCID_PATTERN, isAgcid } from './header.js';
5
4
  const hyphenate = (hex) => [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
6
5
  // RFC 9562 UUIDv7: 48-bit unix ms, version 7, variant 10, the rest random.
7
6
  export const uuidv7 = (now = Date.now(), random = randomBytes(10)) => {
@@ -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 {};
@@ -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
+ };
@@ -0,0 +1,3 @@
1
+ export declare const AGCID_HEADER = "agcid";
2
+ export declare const AGCID_PATTERN: RegExp;
3
+ export declare const isAgcid: (value: unknown) => value is string;
@@ -0,0 +1,3 @@
1
+ export const AGCID_HEADER = 'agcid';
2
+ export const AGCID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
3
+ export const isAgcid = (value) => typeof value === 'string' && AGCID_PATTERN.test(value);
@@ -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
- requestScope.run({ agcid }, next);
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'];
@@ -2,5 +2,6 @@ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
2
2
  import { type RouteEntry } from './routes.js';
3
3
  type Json = Record<string, unknown>;
4
4
  export declare const schemaOf: (zod: object, io: "input" | "output") => Json;
5
+ export declare const inQuery: (method: string) => boolean;
5
6
  export declare const generatedOpenapi: (pkg: ExtensionPackage, routes: RouteEntry[]) => Json;
6
7
  export {};
@@ -25,7 +25,7 @@ const okResponse = ({ output, etag }) => ({
25
25
  ...(etag && { headers: { ETag: { schema: STRING } } }),
26
26
  });
27
27
  const refusal = (code) => content(code, { $ref: '#/components/schemas/Error' });
28
- const inQuery = ({ method }) => method === 'get' || method === 'delete';
28
+ export const inQuery = (method) => method === 'get' || method === 'delete';
29
29
  const fields = (zod) => bare(zod, 'input');
30
30
  const pathParameters = ({ path, spec }) => {
31
31
  const typed = spec.params ? (fields(spec.params).properties ?? {}) : {};
@@ -37,7 +37,7 @@ const pathParameters = ({ path, spec }) => {
37
37
  }));
38
38
  };
39
39
  const queryParameters = (entry) => {
40
- if (!entry.spec.input || !inQuery(entry))
40
+ if (!entry.spec.input || !inQuery(entry.method))
41
41
  return [];
42
42
  const { properties = {}, required = [] } = fields(entry.spec.input);
43
43
  return Object.entries(properties).map(([name, schema]) => ({
@@ -80,7 +80,9 @@ const operation = (id, entry) => {
80
80
  security: securityOf(id, scope),
81
81
  ...(params.length > 0 && { parameters: params }),
82
82
  ...(input &&
83
- !inQuery(entry) && { requestBody: { required: true, content: json(bare(input, 'input')) } }),
83
+ !inQuery(entry.method) && {
84
+ requestBody: { required: true, content: json(bare(input, 'input')) },
85
+ }),
84
86
  responses: responses(entry),
85
87
  };
86
88
  };
@@ -1,11 +1,10 @@
1
1
  import {} from 'zod';
2
- import {} from '../auth/token-check.js';
2
+ import { badScope } from '../auth/token-check.js';
3
3
  import {} from '../context/context.js';
4
4
  import {} from '../envelope/envelope.js';
5
5
  import { createWellKnownRegistry } from './well-known.js';
6
6
  export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
7
7
  const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
8
- const SCOPES = ['public', 'optional', 'read', 'write', 'admin'];
9
8
  const problemOf = (routes, { method, path, spec }) => {
10
9
  if (!ROUTE_METHODS.includes(method))
11
10
  return `method ${String(method)}: one of get, post, put, patch, delete`;
@@ -15,9 +14,7 @@ const problemOf = (routes, { method, path, spec }) => {
15
14
  return 'is registered twice';
16
15
  if (!spec.summary)
17
16
  return 'needs a summary: it documents the route';
18
- if (spec.scope !== undefined && !SCOPES.includes(spec.scope))
19
- return `scope ${String(spec.scope)}: one of ${SCOPES.join(', ')}`;
20
- return null;
17
+ return badScope(spec.scope);
21
18
  };
22
19
  export const createRouteRegistry = () => {
23
20
  const routes = [];
@@ -1,5 +1,6 @@
1
1
  import { type Log } from '../log/log.js';
2
2
  import { type Env } from '../runtime/build-info.js';
3
+ export declare const isAudience: (audience: string) => boolean;
3
4
  export declare const covers: (audience: string, host: string) => boolean;
4
5
  export declare const partAuth: (env: Env, id: string, log: Log, scopes: string[]) => Promise<{
5
6
  tokenCheck: import("./token-check.js").TokenCheck;
@@ -7,7 +7,7 @@ import { createRevokedList, REVOKED_POLL_MS } from './revoked.js';
7
7
  import { accessOfSecurity, scopeOf } from './token-check.js';
8
8
  import { createTokenCheck, remoteKeys } from './verify-token.js';
9
9
  // *.{a domain of two labels or more}, or one host, as a deployment's origin may name it.
10
- const isAudience = (audience) => {
10
+ export const isAudience = (audience) => {
11
11
  const host = audience.startsWith('*.') ? audience.slice(2) : audience;
12
12
  return ['https', 'http'].some((scheme) => OriginSchema.safeParse(`${scheme}://${host}`).success);
13
13
  };
@@ -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 fetch(url, { signal: AbortSignal.timeout(5000) });
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));
@@ -1,4 +1,7 @@
1
- export type Access = 'public' | 'optional' | 'read' | 'write' | 'admin';
1
+ export declare const ACCESS: readonly ["public", "optional", "read", "write", "admin"];
2
+ export type Access = (typeof ACCESS)[number];
3
+ export declare const VERBS: readonly ["read", "write", "admin"];
4
+ export declare const badScope: (scope: unknown, allowed?: readonly Access[]) => string | null;
2
5
  export interface Caller {
3
6
  sub: string;
4
7
  scopes: readonly string[];
@@ -6,7 +9,7 @@ export interface Caller {
6
9
  export type TokenCheck = (authorization: string | undefined, access: Access) => Promise<Caller | null>;
7
10
  export declare const setCaller: (request: object, caller: Caller | null) => void;
8
11
  export declare const callerOf: (request: object) => Caller | null;
9
- export declare const RANK: Record<Access, number>;
12
+ export declare const rank: (access: Access) => number;
10
13
  export declare const scopeOf: (id: string, access?: Access) => string;
11
14
  export declare const strongest: (needed: readonly Access[]) => Access;
12
15
  export declare const accessOfSecurity: (security: unknown) => Access;
@@ -1,11 +1,18 @@
1
1
  import { setTimeout as sleep } from 'node:timers/promises';
2
+ // What a route or tool declares (api-standards section 5): public, optional (anonymous or a read bearer), or a verb.
3
+ export const ACCESS = ['public', 'optional', 'read', 'write', 'admin'];
4
+ export const VERBS = ['read', 'write', 'admin'];
5
+ // Where a route or a tool may declare its scope: tools have no optional.
6
+ export const badScope = (scope, allowed = ACCESS) => scope === undefined || allowed.includes(scope)
7
+ ? null
8
+ : `scope ${String(scope)}: one of ${allowed.join(', ')}`;
2
9
  const callers = new WeakMap();
3
10
  export const setCaller = (request, caller) => void callers.set(request, caller);
4
11
  export const callerOf = (request) => callers.get(request) ?? null;
5
- export const RANK = { public: 0, optional: 1, read: 2, write: 3, admin: 4 };
12
+ export const rank = (access) => ACCESS.indexOf(access);
6
13
  export const scopeOf = (id, access = 'read') => access === 'public' ? 'public' : `${id}:${access === 'optional' ? 'read' : access}`;
7
- export const strongest = (needed) => needed.reduce((top, access) => (RANK[access] > RANK[top] ? access : top), 'public');
8
- const VERB = /:(read|write|admin)$/;
14
+ export const strongest = (needed) => needed.reduce((top, access) => (rank(access) > rank(top) ? access : top), 'public');
15
+ const VERB = new RegExp(`:(${VERBS.join('|')})$`);
9
16
  const isAnonymous = (requirement) => typeof requirement === 'object' && requirement !== null && Object.keys(requirement).length === 0;
10
17
  // OpenAPI security: [] is public, [{}, {pat}] optional, a scope names the verb; nothing declared needs read.
11
18
  export const accessOfSecurity = (security) => {
@@ -1,7 +1,7 @@
1
1
  import { createRemoteJWKSet, errors, jwtVerify } from 'jose';
2
2
  import { z } from 'zod';
3
3
  import { fail, isFailure } from '../envelope/envelope.js';
4
- import { RANK, retryOnce, scopeOf } from './token-check.js';
4
+ import { rank, retryOnce, scopeOf, VERBS } from './token-check.js';
5
5
  const VERIFY = { algorithms: ['EdDSA'], requiredClaims: ['exp'] };
6
6
  const ClaimsSchema = z.object({
7
7
  sub: z.string().min(1),
@@ -51,7 +51,7 @@ const claimsOf = async (authorization, deps) => {
51
51
  };
52
52
  export const grants = (scope, id, access) => {
53
53
  const held = new Set(scope.split(' '));
54
- return ['read', 'write', 'admin'].some((verb) => RANK[verb] >= RANK[access] && held.has(`${id}:${verb}`));
54
+ return VERBS.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.
@@ -1,6 +1,7 @@
1
1
  import { readManifest } from '../manifest/read-manifest.js';
2
2
  import { createOut } from './out.js';
3
- import { contextFor, loadHandlers } from './run-command.js';
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, contextFor(pkg, {}, out))).sort();
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,37 @@
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 { createSpan } from '../log/span.js';
6
+ import {} from '../manifest/manifest.schema.js';
7
+ import {} from './command.types.js';
8
+ import {} from './out.js';
9
+ const unwired = () => Promise.reject(new Error('ctx.client: this host does not provide a client yet'));
10
+ export const NO_CLIENT = Object.freeze({ api: unwired, tool: unwired });
11
+ // Owner-only, made on first read, so --help and the build check never create a folder.
12
+ const ownDir = (dataDir, id) => () => {
13
+ if (dataDir === undefined)
14
+ throw new Error('ctx.dir: this host passes no data dir');
15
+ const dir = join(dataDir, id);
16
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
17
+ chmodSync(dir, 0o700);
18
+ return dir;
19
+ };
20
+ export const cliContext = (pkg, run) => {
21
+ const { id } = pkg.agentage;
22
+ const tags = { extension: id, part: 'cli', version: pkg.version, base: { command: run.command } };
23
+ const dir = ownDir(run.dataDir, id);
24
+ const log = createLog(tags, run.stderr);
25
+ return Object.freeze({
26
+ extension: Object.freeze({ id, version: pkg.version, part: 'cli' }),
27
+ args: Object.freeze(run.args),
28
+ out: run.out,
29
+ log,
30
+ span: createSpan(log),
31
+ user: run.user ?? null,
32
+ client: run.client ?? NO_CLIENT,
33
+ get dir() {
34
+ return dir();
35
+ },
36
+ });
37
+ };
@@ -1,3 +1,7 @@
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';
4
+ import { type Span } from '../log/span.js';
1
5
  import { type Out } from './out.js';
2
6
  import { type ArgValue } from './args.js';
3
7
  export interface CommandExtension {
@@ -5,10 +9,19 @@ export interface CommandExtension {
5
9
  version: string;
6
10
  part: 'cli';
7
11
  }
12
+ export interface CliClient {
13
+ api(method: RouteMethod, path: string, input?: unknown): Promise<unknown>;
14
+ tool(name: string, args?: Record<string, unknown>): Promise<unknown>;
15
+ }
8
16
  export interface CliContext {
9
17
  readonly extension: Readonly<CommandExtension>;
10
18
  readonly args: Readonly<Record<string, ArgValue>>;
11
19
  readonly out: Out;
20
+ readonly log: Log;
21
+ readonly span: Span;
22
+ readonly user: Caller | null;
23
+ readonly client: CliClient;
24
+ readonly dir: string;
12
25
  }
13
26
  export type CommandHandler = () => unknown;
14
27
  export type CliCreate = (ctx: CliContext) => Record<string, CommandHandler>;
@@ -1,2 +1,6 @@
1
+ import {} from '../api/routes.js';
2
+ import {} from '../auth/token-check.js';
3
+ import {} from '../log/log.js';
4
+ import {} from '../log/span.js';
1
5
  import {} from './out.js';
2
6
  import {} from './args.js';
@@ -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 handler = (await loadHandlers(o.dir, pkg, contextFor(pkg, parsed.args, out)))[o.command];
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
- const result = await handler();
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) => {
@@ -2,6 +2,7 @@ import { type Caller } from '../auth/token-check.js';
2
2
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
3
  import { type StoreKind } from '../manifest/primitives.schema.js';
4
4
  import { type Log } from '../log/log.js';
5
+ import { type Span } from '../log/span.js';
5
6
  import { type Store } from '../store/store.types.js';
6
7
  import { type Secrets } from './secrets.js';
7
8
  export type ServerPartKind = 'pages' | 'api' | 'mcp' | 'worker';
@@ -20,6 +21,7 @@ export interface PartContext {
20
21
  caller(request: object): Caller | null;
21
22
  };
22
23
  readonly log: Log;
24
+ readonly span: Span;
23
25
  readonly settings: Readonly<Record<string, SettingValue>>;
24
26
  readonly store: Store;
25
27
  readonly secrets: Secrets;
@@ -3,6 +3,7 @@ import {} from '../manifest/manifest.schema.js';
3
3
  import { storeOf } from '../manifest/parts.js';
4
4
  import {} from '../manifest/primitives.schema.js';
5
5
  import { createLog } from '../log/log.js';
6
+ import { createSpan } from '../log/span.js';
6
7
  import {} from '../store/store.types.js';
7
8
  import {} from './secrets.js';
8
9
  // ctx.store is always there; without a store part in the manifest it says so on first use.
@@ -23,9 +24,10 @@ export const createContext = (input) => {
23
24
  commit,
24
25
  ...(kind && { store: kind }),
25
26
  });
26
- const log = input.log ?? createLog({ extension: pkg.agentage.id, part });
27
+ const log = input.log ?? createLog({ extension: pkg.agentage.id, part, version: pkg.version });
27
28
  const settings = Object.freeze({ ...settingDefaults(pkg), ...input.settings });
28
29
  const auth = Object.freeze({ caller: callerOf });
29
30
  const secrets = input.secrets ?? {};
30
- return Object.freeze({ extension, auth, log, settings, store: store ?? NO_STORE, secrets });
31
+ const span = createSpan(log);
32
+ return Object.freeze({ extension, auth, log, span, settings, store: store ?? NO_STORE, secrets });
31
33
  };
@@ -0,0 +1,7 @@
1
+ import { type Log, type LogFields, type LogLevel } from '../log/log.js';
2
+ export interface LogEntry {
3
+ level: LogLevel;
4
+ message: string;
5
+ fields: LogFields;
6
+ }
7
+ export declare const recordingLog: (logs: LogEntry[]) => Log;
@@ -0,0 +1,10 @@
1
+ import { messageOf, withLineAt } from '../log/log.js';
2
+ export const recordingLog = (logs) => withLineAt({
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
+ }, (level, message, fields) => void logs.push({ level, message, fields }));
@@ -0,0 +1,36 @@
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 SpanRecord } from '../log/span.js';
5
+ import { type LogEntry } from './recording-log.js';
6
+ export type ClientCall = {
7
+ kind: 'api';
8
+ method: string;
9
+ path: string;
10
+ input?: unknown;
11
+ } | {
12
+ kind: 'tool';
13
+ name: string;
14
+ args?: Record<string, unknown>;
15
+ };
16
+ export interface TestCommandContext extends CliContext {
17
+ readonly output: {
18
+ stdout: string[];
19
+ stderr: string[];
20
+ };
21
+ readonly exitCode: number | undefined;
22
+ readonly logs: LogEntry[];
23
+ readonly spans: SpanRecord[];
24
+ readonly calls: ClientCall[];
25
+ }
26
+ export interface TestCommandOptions {
27
+ args: Record<string, ArgValue>;
28
+ extension?: {
29
+ id?: string;
30
+ version?: string;
31
+ };
32
+ json?: boolean;
33
+ user?: Caller | null;
34
+ client?: Partial<CliClient>;
35
+ }
36
+ export declare const commandContext: (options: TestCommandOptions) => TestCommandContext;
@@ -0,0 +1,60 @@
1
+ import { mkdtempSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import {} from '../command/args.js';
5
+ import {} from '../auth/token-check.js';
6
+ import {} from '../command/command.types.js';
7
+ import { createOut } from '../command/out.js';
8
+ import { createSpan } from '../log/span.js';
9
+ import { packageExtension } from './package-extension.js';
10
+ import { recordingLog } from './recording-log.js';
11
+ // One recorded line per line written, the trailing newline dropped.
12
+ const lines = (into) => (text) => void into.push(...text.replace(/\n$/, '').split('\n'));
13
+ const recordingClient = (calls, answers = {}) => ({
14
+ api: async (method, path, input) => {
15
+ calls.push({ kind: 'api', method, path, ...(input === undefined ? {} : { input }) });
16
+ return answers.api?.(method, path, input);
17
+ },
18
+ tool: async (name, args) => {
19
+ calls.push({ kind: 'tool', name, ...(args === undefined ? {} : { args }) });
20
+ return answers.tool?.(name, args);
21
+ },
22
+ });
23
+ // A throwaway owner-only folder, made on first read like the real one.
24
+ const lazyDir = () => {
25
+ let dir;
26
+ return () => (dir ??= mkdtempSync(join(tmpdir(), 'agentage-cli-')));
27
+ };
28
+ const recorded = (options) => {
29
+ const output = { stdout: [], stderr: [] };
30
+ const json = options.json ?? false;
31
+ const out = createOut({ json, stdout: lines(output.stdout), stderr: lines(output.stderr) });
32
+ return {
33
+ out,
34
+ output,
35
+ logs: [],
36
+ spans: [],
37
+ calls: [],
38
+ };
39
+ };
40
+ export const commandContext = (options) => {
41
+ const { out, output, logs, spans, calls } = recorded(options);
42
+ const { id = 'test', version = '0.0.0' } = packageExtension();
43
+ const extension = { id, version, ...options.extension, part: 'cli' };
44
+ const fixedUser = { sub: 'usr_test', scopes: [`${extension.id}:read`] };
45
+ const dir = lazyDir();
46
+ const log = recordingLog(logs);
47
+ return {
48
+ ...{ extension, args: { ...options.args }, out, output, logs, spans, calls },
49
+ log,
50
+ span: createSpan(log, spans),
51
+ user: options.user === undefined ? fixedUser : options.user,
52
+ client: recordingClient(calls, options.client),
53
+ get dir() {
54
+ return dir();
55
+ },
56
+ get exitCode() {
57
+ return out.exitCode;
58
+ },
59
+ };
60
+ };
@@ -1,18 +1,15 @@
1
1
  import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
2
2
  import { type WellKnownRegistrar } from '../api/well-known.js';
3
- import { type CliContext } from '../command/command.types.js';
4
- import { type LogFields, type LogLevel } from '../log/log.js';
3
+ import { type SpanRecord } from '../log/span.js';
5
4
  import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
6
5
  import { type JobOptions } from '../worker/job-options.js';
7
6
  import { type JobRun } from '../worker/runs.js';
8
7
  import { type Schedule } from '../worker/scheduler.js';
9
8
  import { type ExtensionInfo, type PartContext, type SettingValue } from './context.js';
10
- import { type ArgValue } from '../command/args.js';
11
- export interface LogEntry {
12
- level: LogLevel;
13
- message: string;
14
- fields: LogFields;
15
- }
9
+ import { type LogEntry } from './recording-log.js';
10
+ import { type TestCommandContext, type TestCommandOptions } from './test-command-context.js';
11
+ export { type LogEntry } from './recording-log.js';
12
+ export { type ClientCall, type TestCommandContext, type TestCommandOptions, } from './test-command-context.js';
16
13
  export interface TestContext extends PartContext {
17
14
  readonly logs: LogEntry[];
18
15
  close(): Promise<void>;
@@ -23,6 +20,7 @@ export interface TestContext extends PartContext {
23
20
  readonly routes: RouteEntry[];
24
21
  readonly wellKnown: WellKnownRegistrar;
25
22
  readonly jobs: ScheduledJob[];
23
+ readonly spans: SpanRecord[];
26
24
  runJob(name: string): Promise<JobRun | undefined>;
27
25
  }
28
26
  export interface ScheduledJob {
@@ -30,13 +28,6 @@ export interface ScheduledJob {
30
28
  cron: string;
31
29
  options?: JobOptions;
32
30
  }
33
- export interface TestCommandContext extends CliContext {
34
- readonly output: {
35
- stdout: string[];
36
- stderr: string[];
37
- };
38
- readonly exitCode: number | undefined;
39
- }
40
31
  export interface TestContextOptions {
41
32
  extension?: Partial<ExtensionInfo>;
42
33
  settings?: Record<string, SettingValue>;
@@ -45,13 +36,5 @@ export interface TestContextOptions {
45
36
  dir: string;
46
37
  };
47
38
  }
48
- export interface TestCommandOptions {
49
- args: Record<string, ArgValue>;
50
- extension?: {
51
- id?: string;
52
- version?: string;
53
- };
54
- json?: boolean;
55
- }
56
39
  export declare function createTestContext(options: TestCommandOptions): TestCommandContext;
57
40
  export declare function createTestContext(options?: TestContextOptions): TestContext;