@agentage/extension 0.11.1 → 0.12.2

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 (71) hide show
  1. package/README.md +2 -0
  2. package/dist/agcid/agcid.d.ts +3 -2
  3. package/dist/agcid/agcid.js +17 -11
  4. package/dist/agcid/current.d.ts +4 -1
  5. package/dist/agcid/current.js +9 -0
  6. package/dist/agcid/fetch.d.ts +1 -0
  7. package/dist/agcid/fetch.js +4 -2
  8. package/dist/agcid/header.js +2 -1
  9. package/dist/agcid/scope.js +5 -3
  10. package/dist/auth/token-check.d.ts +1 -0
  11. package/dist/auth/token-check.js +17 -1
  12. package/dist/auth/verify-token.js +2 -2
  13. package/dist/context/context.d.ts +5 -0
  14. package/dist/context/context.js +17 -0
  15. package/dist/context/recording-log.d.ts +3 -2
  16. package/dist/context/recording-log.js +12 -10
  17. package/dist/context/test-context.d.ts +3 -0
  18. package/dist/context/test-context.js +8 -2
  19. package/dist/discovery/discovery.d.ts +1 -1
  20. package/dist/discovery/discovery.schema.d.ts +2 -0
  21. package/dist/health/health.d.ts +2 -0
  22. package/dist/health/health.js +20 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/log/log.d.ts +4 -19
  26. package/dist/log/log.js +12 -42
  27. package/dist/log/span.js +6 -10
  28. package/dist/log/who.d.ts +13 -0
  29. package/dist/log/who.js +48 -0
  30. package/dist/logs/index.d.ts +1 -0
  31. package/dist/logs/index.js +2 -0
  32. package/dist/manifest/manifest.schema.d.ts +4 -0
  33. package/dist/manifest/primitives.schema.d.ts +4 -0
  34. package/dist/manifest/primitives.schema.js +2 -1
  35. package/dist/mcp/mcp-app.js +23 -2
  36. package/dist/mcp/server.js +11 -5
  37. package/dist/pages/pages-app.js +6 -3
  38. package/dist/runtime/main.js +7 -2
  39. package/dist/runtime/part-runners.js +2 -1
  40. package/dist/runtime/run-part.d.ts +2 -0
  41. package/dist/runtime/run-part.js +20 -6
  42. package/dist/server/app.js +5 -4
  43. package/dist/server/errors.js +24 -3
  44. package/dist/server/request-line.d.ts +2 -2
  45. package/dist/server/request-line.js +31 -12
  46. package/dist/server/serve.js +19 -7
  47. package/dist/tool/up/local-record.d.ts +1 -1
  48. package/dist/vendor/logs/event.schema.d.ts +45 -0
  49. package/dist/vendor/logs/event.schema.js +24 -0
  50. package/dist/vendor/logs/events-client.d.ts +22 -0
  51. package/dist/vendor/logs/events-client.js +88 -0
  52. package/dist/vendor/logs/index.d.ts +6 -0
  53. package/dist/vendor/logs/index.js +6 -0
  54. package/dist/vendor/logs/logger.d.ts +33 -0
  55. package/dist/vendor/logs/logger.js +83 -0
  56. package/dist/vendor/logs/parse-line.d.ts +6 -0
  57. package/dist/vendor/logs/parse-line.js +30 -0
  58. package/dist/vendor/logs/redact.d.ts +7 -0
  59. package/dist/vendor/logs/redact.js +63 -0
  60. package/dist/vendor/logs/rows.d.ts +34 -0
  61. package/dist/vendor/logs/rows.js +68 -0
  62. package/dist/vendor/logs/uuidv7.d.ts +1 -0
  63. package/dist/vendor/logs/uuidv7.js +10 -0
  64. package/dist/worker/run-log.d.ts +1 -1
  65. package/dist/worker/run-log.js +16 -18
  66. package/dist/worker/scheduler.js +11 -4
  67. package/package.json +10 -3
  68. package/schemas/error-envelope.schema.json +1 -1
  69. package/schemas/extension-discovery.schema.json +2 -1
  70. package/schemas/extension-package.schema.json +4 -2
  71. package/schemas/extension-record.schema.json +2 -1
package/README.md CHANGED
@@ -4,6 +4,8 @@ The agentage extension kit. Each part module (pages, api, mcp, worker, cli) expo
4
4
  `create(ctx)`; the kit owns the server, port, `/health`, the discovery document, the `agcid`
5
5
  correlation id, the response envelope, the store pool, the scheduler and argument parsing.
6
6
  `@agentage/extension/tool` is the tool behind `agentage extension build | up | down | token`.
7
+ `@agentage/extension/logs` is the event line (`EventSchema`, `parseLine`, `createLogger`,
8
+ `createEventsClient`, `KINDS`, `LEVELS`, `USER_TYPES`), built into the kit's own tarball.
7
9
 
8
10
  ```bash
9
11
  npm install @agentage/extension express zod
@@ -1,3 +1,4 @@
1
+ import { uuidv7 } from '../vendor/logs/index.js';
1
2
  export { AGCID_HEADER, AGCID_PATTERN, isAgcid } from './header.js';
2
- export declare const uuidv7: (now?: number, random?: Buffer) => string;
3
- export declare const agcidOf: (incoming: unknown) => string;
3
+ export { uuidv7 };
4
+ export declare const agcidOf: (incoming: unknown, traceparent?: unknown) => string;
@@ -1,14 +1,20 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { uuidv7 } from '../vendor/logs/index.js';
2
+ import { TRACEPARENT_PATTERN } from './current.js';
2
3
  import { isAgcid } from './header.js';
3
4
  export { AGCID_HEADER, AGCID_PATTERN, isAgcid } from './header.js';
4
- const hyphenate = (hex) => [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
5
- // RFC 9562 UUIDv7: 48-bit unix ms, version 7, variant 10, the rest random.
6
- export const uuidv7 = (now = Date.now(), random = randomBytes(10)) => {
7
- const bytes = Buffer.alloc(16);
8
- bytes.writeUIntBE(now, 0, 6);
9
- random.copy(bytes, 6, 0, 10);
10
- bytes.writeUInt8((bytes.readUInt8(6) & 0x0f) | 0x70, 6);
11
- bytes.writeUInt8((bytes.readUInt8(8) & 0x3f) | 0x80, 8);
12
- return hyphenate(bytes.toString('hex'));
5
+ export { uuidv7 };
6
+ const DASHED = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
7
+ const ZERO = '0'.repeat(32);
8
+ // 32 hex, or a UUID in its 8-4-4-4-12 form without the dashes; all zeros is no id (W3C).
9
+ const ownOf = (value) => {
10
+ if (typeof value !== 'string')
11
+ return undefined;
12
+ const lower = value.toLowerCase();
13
+ const id = DASHED.test(lower) ? lower.replaceAll('-', '') : lower;
14
+ return isAgcid(id) && id !== ZERO ? id : undefined;
13
15
  };
14
- export const agcidOf = (incoming) => (isAgcid(incoming) ? incoming : uuidv7());
16
+ const traceIdOf = (traceparent) => typeof traceparent === 'string' && TRACEPARENT_PATTERN.test(traceparent)
17
+ ? ownOf(traceparent.slice(3, 35))
18
+ : undefined;
19
+ // A valid agcid header, else the traceparent trace id, else minted.
20
+ export const agcidOf = (incoming, traceparent) => ownOf(incoming) ?? traceIdOf(traceparent) ?? uuidv7();
@@ -1,9 +1,12 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
- interface RequestScope {
2
+ import { type RowContext } from '../vendor/logs/index.js';
3
+ interface RequestScope extends RowContext {
3
4
  agcid: string;
4
5
  traceparent?: string;
6
+ exit?: boolean;
5
7
  }
6
8
  export declare const requestScope: AsyncLocalStorage<RequestScope>;
7
9
  export declare const currentAgcid: () => string | undefined;
10
+ export declare const sigtermOnce: () => void;
8
11
  export declare const TRACEPARENT_PATTERN: RegExp;
9
12
  export {};
@@ -1,5 +1,14 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import {} from '../vendor/logs/index.js';
2
3
  // Apart from the middleware, so code the cli loads (logs, the build tool) never imports express.
3
4
  export const requestScope = new AsyncLocalStorage();
4
5
  export const currentAgcid = () => requestScope.getStore()?.agcid;
6
+ let exiting = false;
7
+ // One SIGTERM per process: ctx.exit() twice, or in two requests, drains once.
8
+ export const sigtermOnce = () => {
9
+ if (exiting)
10
+ return;
11
+ exiting = true;
12
+ process.kill(process.pid, 'SIGTERM');
13
+ };
5
14
  export const TRACEPARENT_PATTERN = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
@@ -1 +1,2 @@
1
+ export declare const KIT_FETCH_TIMEOUT_MS = 10000;
1
2
  export declare const kitFetch: (url: string, init?: RequestInit, impl?: typeof fetch) => Promise<Response>;
@@ -1,11 +1,13 @@
1
1
  import { AGCID_HEADER, uuidv7 } from './agcid.js';
2
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.
3
+ export const KIT_FETCH_TIMEOUT_MS = 10_000;
4
+ // Every fetch the kit makes: the scope's agcid (a fresh one outside a scope), its traceparent, a timeout.
4
5
  export const kitFetch = (url, init = {}, impl = fetch) => {
5
6
  const scope = requestScope.getStore();
6
7
  const headers = new Headers(init.headers);
7
8
  headers.set(AGCID_HEADER, scope?.agcid ?? uuidv7());
8
9
  if (scope?.traceparent)
9
10
  headers.set('traceparent', scope.traceparent);
10
- return impl(url, { ...init, headers });
11
+ const signal = init.signal ?? AbortSignal.timeout(KIT_FETCH_TIMEOUT_MS);
12
+ return impl(url, { ...init, headers, signal });
11
13
  };
@@ -1,3 +1,4 @@
1
1
  export const AGCID_HEADER = 'agcid';
2
- export const AGCID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
2
+ // A UUIDv7 as 32 lowercase hex, a valid W3C trace id (api-standards section 6).
3
+ export const AGCID_PATTERN = /^[0-9a-f]{32}$/;
3
4
  export const isAgcid = (value) => typeof value === 'string' && AGCID_PATTERN.test(value);
@@ -1,14 +1,16 @@
1
1
  import {} from 'express';
2
+ import { whoOf } from '../log/who.js';
2
3
  import { AGCID_HEADER, agcidOf } from './agcid.js';
3
4
  import { requestScope, TRACEPARENT_PATTERN } from './current.js';
4
5
  // Keeps a valid incoming agcid, else mints one; echoed on every response and tags every log line.
5
6
  export const agcidMiddleware = (req, res, next) => {
6
- const agcid = agcidOf(req.get(AGCID_HEADER));
7
+ const traceparent = req.get('traceparent');
8
+ const agcid = agcidOf(req.get(AGCID_HEADER), traceparent);
7
9
  res.locals['agcid'] = agcid;
8
10
  res.setHeader(AGCID_HEADER, agcid);
9
- const traceparent = req.get('traceparent');
10
11
  const valid = traceparent !== undefined && TRACEPARENT_PATTERN.test(traceparent);
11
- requestScope.run(valid ? { agcid, traceparent } : { agcid }, next);
12
+ const who = whoOf((name) => req.get(name), req.path);
13
+ requestScope.run({ agcid, ...(valid ? { traceparent } : {}), ...who }, next);
12
14
  };
13
15
  export const agcidOfResponse = (res) => {
14
16
  const agcid = res.locals['agcid'];
@@ -6,6 +6,7 @@ export interface Caller {
6
6
  sub: string;
7
7
  scopes: readonly string[];
8
8
  }
9
+ export declare const withJti: (caller: Caller, jti: string | undefined) => Caller;
9
10
  export type TokenCheck = (authorization: string | undefined, access: Access) => Promise<Caller | null>;
10
11
  export declare const setCaller: (request: object, caller: Caller | null) => void;
11
12
  export declare const callerOf: (request: object) => Caller | null;
@@ -1,4 +1,5 @@
1
1
  import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { requestScope } from '../agcid/current.js';
2
3
  // What a route or tool declares (api-standards section 5): public, optional (anonymous or a read bearer), or a verb.
3
4
  export const ACCESS = ['public', 'optional', 'read', 'write', 'admin'];
4
5
  export const VERBS = ['read', 'write', 'admin'];
@@ -6,8 +7,23 @@ export const VERBS = ['read', 'write', 'admin'];
6
7
  export const badScope = (scope, allowed = ACCESS) => scope === undefined || allowed.includes(scope)
7
8
  ? null
8
9
  : `scope ${String(scope)}: one of ${allowed.join(', ')}`;
10
+ // The token id beside a caller, never on it: the log's session when the client sends no agsid.
11
+ const tokenIds = new WeakMap();
12
+ export const withJti = (caller, jti) => {
13
+ if (jti !== undefined)
14
+ tokenIds.set(caller, jti);
15
+ return caller;
16
+ };
9
17
  const callers = new WeakMap();
10
- export const setCaller = (request, caller) => void callers.set(request, caller);
18
+ // Also the request scope's sub and session, so every row after the check says who.
19
+ export const setCaller = (request, caller) => {
20
+ callers.set(request, caller);
21
+ const scope = requestScope.getStore();
22
+ if (!scope || !caller)
23
+ return;
24
+ scope.sub = caller.sub;
25
+ scope.session ??= tokenIds.get(caller) ?? null;
26
+ };
11
27
  export const callerOf = (request) => callers.get(request) ?? null;
12
28
  export const rank = (access) => ACCESS.indexOf(access);
13
29
  export const scopeOf = (id, access = 'read') => access === 'public' ? 'public' : `${id}:${access === 'optional' ? 'read' : access}`;
@@ -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, VERBS } from './token-check.js';
4
+ import { rank, retryOnce, scopeOf, VERBS, withJti, } 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),
@@ -66,5 +66,5 @@ export const createTokenCheck = (deps) => async (authorization, access) => {
66
66
  throw invalid(deps.origin, 'Token revoked');
67
67
  if (!grants(scope, deps.id, access))
68
68
  throw forbidden(scopeOf(deps.id, access));
69
- return { sub, scopes: scope.split(' ') };
69
+ return withJti({ sub, scopes: scope.split(' ') }, jti);
70
70
  };
@@ -3,6 +3,7 @@ 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
5
  import { type Span } from '../log/span.js';
6
+ import type { HealthCheck } from '../health/health.js';
6
7
  import { type Store } from '../store/store.types.js';
7
8
  import { type Secrets } from './secrets.js';
8
9
  export type ServerPartKind = 'pages' | 'api' | 'mcp' | 'worker';
@@ -32,7 +33,10 @@ export interface PartContext {
32
33
  readonly store: Store;
33
34
  readonly secrets: Secrets;
34
35
  readonly platform: Readonly<PlatformInfo>;
36
+ readonly exit: () => void;
37
+ readonly health: (name: string, check: HealthCheck) => void;
35
38
  }
39
+ export declare const healthRegistrar: (checks: Record<string, HealthCheck>) => (name: string, check: HealthCheck) => void;
36
40
  export declare const NO_STORE: Store;
37
41
  export declare const settingDefaults: (pkg: ExtensionPackage) => Record<string, SettingValue>;
38
42
  export interface ContextInput {
@@ -45,5 +49,6 @@ export interface ContextInput {
45
49
  store?: Store;
46
50
  secrets?: Secrets;
47
51
  platform?: PlatformInfo;
52
+ checks?: Record<string, HealthCheck>;
48
53
  }
49
54
  export declare const createContext: (input: ContextInput) => PartContext;
@@ -1,3 +1,4 @@
1
+ import { requestScope, sigtermOnce } from '../agcid/current.js';
1
2
  import { callerOf } from '../auth/token-check.js';
2
3
  import {} from '../manifest/manifest.schema.js';
3
4
  import { storeOf } from '../manifest/parts.js';
@@ -7,6 +8,20 @@ import { createSpan } from '../log/span.js';
7
8
  import {} from '../store/store.types.js';
8
9
  import {} from './secrets.js';
9
10
  export const NO_PLATFORM = Object.freeze({ issuer: '', audience: '' });
11
+ const CHECK_NAME = /^[a-z][a-z0-9-]*$/;
12
+ export const healthRegistrar = (checks) => (name, check) => {
13
+ if (!CHECK_NAME.test(name) || name in checks)
14
+ throw new Error(`health check ${name}: taken or not a-z0-9-`);
15
+ checks[name] = check;
16
+ };
17
+ // Inside a request: after its answer (server/request-line.ts); outside one: now.
18
+ const exitAfterAnswer = () => {
19
+ const scope = requestScope.getStore();
20
+ if (scope)
21
+ scope.exit = true;
22
+ else
23
+ sigtermOnce();
24
+ };
10
25
  // ctx.store is always there; without a store part in the manifest it says so on first use.
11
26
  export const NO_STORE = {
12
27
  query: async () => {
@@ -40,5 +55,7 @@ export const createContext = (input) => {
40
55
  store: store ?? NO_STORE,
41
56
  secrets,
42
57
  platform,
58
+ exit: exitAfterAnswer,
59
+ health: healthRegistrar(input.checks ?? {}),
43
60
  });
44
61
  };
@@ -1,6 +1,7 @@
1
- import { type Log, type LogFields, type LogLevel } from '../log/log.js';
1
+ import { type Level } from '../vendor/logs/index.js';
2
+ import { type Log, type LogFields } from '../log/log.js';
2
3
  export interface LogEntry {
3
- level: LogLevel;
4
+ level: Level;
4
5
  message: string;
5
6
  fields: LogFields;
6
7
  }
@@ -1,10 +1,12 @@
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 }));
1
+ import { createLogger } from '../vendor/logs/index.js';
2
+ import { messageOf } from '../log/log.js';
3
+ // The test context's log: every row as an entry; error keeps the thrown value under err.
4
+ export const recordingLog = (logs) => {
5
+ const sink = ({ level, msg, fields }) => void logs.push({ level, message: msg, fields });
6
+ const log = createLogger({ extension: 'test', part: 'test', sink, strict: true });
7
+ const error = (err, where = {}) => {
8
+ const fields = typeof where === 'string' ? { 'agentage.where': where } : where;
9
+ logs.push({ level: 'error', message: messageOf(err), fields: { ...fields, err } });
10
+ };
11
+ return { ...log, error };
12
+ };
@@ -1,5 +1,6 @@
1
1
  import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
2
2
  import { type WellKnownRegistrar } from '../api/well-known.js';
3
+ import type { HealthCheck } from '../health/health.js';
3
4
  import { type SpanRecord } from '../log/span.js';
4
5
  import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
5
6
  import { type JobOptions } from '../worker/job-options.js';
@@ -21,6 +22,8 @@ export interface TestContext extends PartContext {
21
22
  readonly wellKnown: WellKnownRegistrar;
22
23
  readonly jobs: ScheduledJob[];
23
24
  readonly spans: SpanRecord[];
25
+ readonly exits: number[];
26
+ readonly checks: Record<string, HealthCheck>;
24
27
  runJob(name: string): Promise<JobRun | undefined>;
25
28
  }
26
29
  export interface ScheduledJob {
@@ -10,7 +10,7 @@ import { runLog } from '../worker/run-log.js';
10
10
  import { memoryRuns } from '../worker/runs.js';
11
11
  import { createScheduler } from '../worker/scheduler.js';
12
12
  import {} from '../manifest/primitives.schema.js';
13
- import { NO_PLATFORM, NO_STORE, } from './context.js';
13
+ import { NO_PLATFORM, healthRegistrar, NO_STORE, } from './context.js';
14
14
  import { packageExtension } from './package-extension.js';
15
15
  import { recordingLog } from './recording-log.js';
16
16
  import { commandContext, } from './test-command-context.js';
@@ -57,11 +57,13 @@ const identityOf = (options) => {
57
57
  };
58
58
  const serverContext = (options) => {
59
59
  const logs = [];
60
- const log = runLog(recordingLog(logs));
60
+ const log = runLog(recordingLog(logs), true);
61
61
  const spans = [];
62
62
  const { extension, ...open } = identityOf(options);
63
63
  const store = testStore(open.store, recordingLog([]));
64
64
  const caller = { sub: 'usr_test', scopes: [`${extension.id}:read`] };
65
+ const exits = [];
66
+ const checks = {};
65
67
  return {
66
68
  extension,
67
69
  auth: { caller: () => caller },
@@ -73,6 +75,10 @@ const serverContext = (options) => {
73
75
  store: store ?? NO_STORE,
74
76
  secrets: Object.freeze({ ...options.secrets }),
75
77
  platform: Object.freeze({ ...(options.platform ?? NO_PLATFORM) }),
78
+ exits,
79
+ exit: () => void exits.push(Date.now()),
80
+ checks,
81
+ health: healthRegistrar(checks),
76
82
  close: async () => store?.close(),
77
83
  ...recorders(log),
78
84
  };
@@ -41,7 +41,7 @@ export declare const discoveryDocument: (record: ExtensionRecord, host: string)
41
41
  image: string;
42
42
  } | undefined;
43
43
  store?: {
44
- kind: "postgres" | "signoz" | "git";
44
+ kind: "postgres" | "signoz" | "git" | "clickhouse";
45
45
  migrations?: number | undefined;
46
46
  } | undefined;
47
47
  };
@@ -32,6 +32,7 @@ export declare const ExtensionRecordSchema: z.ZodObject<{
32
32
  postgres: "postgres";
33
33
  signoz: "signoz";
34
34
  git: "git";
35
+ clickhouse: "clickhouse";
35
36
  }>;
36
37
  migrations: z.ZodOptional<z.ZodInt>;
37
38
  }, z.core.$strict>>;
@@ -75,6 +76,7 @@ export declare const DiscoveryDocumentSchema: z.ZodObject<{
75
76
  postgres: "postgres";
76
77
  signoz: "signoz";
77
78
  git: "git";
79
+ clickhouse: "clickhouse";
78
80
  }>;
79
81
  migrations: z.ZodOptional<z.ZodInt>;
80
82
  }, z.core.$strict>>;
@@ -1,5 +1,6 @@
1
1
  import { type RequestHandler } from 'express';
2
2
  import { type BuildInfo } from '../discovery/discovery.js';
3
+ import { type Log } from '../log/log.js';
3
4
  import { type ImagePartKind } from '../manifest/primitives.schema.js';
4
5
  import { type HealthBody, type HealthStatus } from './health.schema.js';
5
6
  export type HealthCheck = () => Promise<HealthStatus>;
@@ -12,6 +13,7 @@ export interface HealthOptions {
12
13
  instance?: string;
13
14
  startedAt?: number;
14
15
  now?: () => Date;
16
+ log?: Log;
15
17
  }
16
18
  export declare const worstOf: (statuses: HealthStatus[]) => HealthStatus;
17
19
  export declare const CHECK_TIMEOUT_MS = 1000;
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto';
2
2
  import {} from 'express';
3
3
  import {} from '../discovery/discovery.js';
4
4
  import { fail } from '../envelope/envelope.js';
5
+ import {} from '../log/log.js';
5
6
  import {} from '../manifest/primitives.schema.js';
6
7
  import { isoSeconds } from '../runtime/build-info.js';
7
8
  import {} from './health.schema.js';
@@ -15,7 +16,9 @@ const settle = async (check) => {
15
16
  timer = setTimeout(() => resolve('unavailable'), CHECK_TIMEOUT_MS).unref();
16
17
  });
17
18
  try {
18
- return await Promise.race([check(), expiry]);
19
+ const status = await Promise.race([check(), expiry]);
20
+ // A check answering anything but a status is not a healthy one.
21
+ return Object.hasOwn(RANK, status) ? status : 'unavailable';
19
22
  }
20
23
  catch {
21
24
  return 'unavailable';
@@ -41,6 +44,16 @@ export const healthBody = async (options) => {
41
44
  data: { ...data, uptimeSeconds, checkedAt: isoSeconds(now), checks },
42
45
  };
43
46
  };
47
+ // Names a check whose status moved, so a recovery names what recovered.
48
+ const changed = (log, from, to, was, now) => {
49
+ const check = Object.keys(now).find((name) => was[name] !== now[name]) ?? '';
50
+ const fields = {
51
+ 'agentage.health.from': from,
52
+ 'agentage.health.to': to,
53
+ 'agentage.health.check': check,
54
+ };
55
+ log?.event('health.changed', fields, `health.changed ${from} to ${to}`);
56
+ };
44
57
  // Answers only on loopback: the container HEALTHCHECK and an operator on the node, never the gateway.
45
58
  export const createHealthHandler = (options) => {
46
59
  const resolved = {
@@ -48,10 +61,16 @@ export const createHealthHandler = (options) => {
48
61
  instance: options.instance ?? randomBytes(4).toString('hex'),
49
62
  startedAt: options.startedAt ?? Date.now(),
50
63
  };
64
+ let last;
65
+ let lastChecks = {};
51
66
  return async (req, res) => {
52
67
  if (!isLoopback(req.socket.localAddress))
53
68
  throw fail('NOT_FOUND', 'Not found');
54
69
  const body = await healthBody(resolved);
70
+ const { status: to, checks } = body.data;
71
+ if (last !== undefined && last !== to)
72
+ changed(options.log, last, to, lastChecks, checks);
73
+ [last, lastChecks] = [to, checks];
55
74
  res.setHeader('Cache-Control', 'no-store');
56
75
  res.status(body.data.status === 'unavailable' ? 503 : 200).json(body);
57
76
  };
package/dist/index.d.ts CHANGED
@@ -15,6 +15,7 @@ export { ErrorEnvelopeSchema, OkEnvelopeSchema } from './envelope/envelope.schem
15
15
  export { parse, type ParseSchema } from './envelope/parse.js';
16
16
  export { type HealthBody, type HealthStatus } from './health/health.schema.js';
17
17
  export { type Log, type LogFields } from './log/log.js';
18
+ export { createEventsClient, EventSchema, parseLine, type Event, type EventsClientOptions, type PostEvent, } from './vendor/logs/index.js';
18
19
  export { type Span, type SpanRecord } from './log/span.js';
19
20
  export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, } from './mcp/tools.js';
20
21
  export { versionPage, type PagesContext, type PagesEntry, type PagesSite } from './pages/pages.js';
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ export { ErrorEnvelopeSchema, OkEnvelopeSchema } from './envelope/envelope.schem
16
16
  export { parse } from './envelope/parse.js';
17
17
  export {} from './health/health.schema.js';
18
18
  export {} from './log/log.js';
19
+ export { createEventsClient, EventSchema, parseLine, } from './vendor/logs/index.js';
19
20
  export {} from './log/span.js';
20
21
  export {} from './mcp/tools.js';
21
22
  export { versionPage } from './pages/pages.js';
package/dist/log/log.d.ts CHANGED
@@ -1,20 +1,5 @@
1
- export type LogLevel = 'info' | 'warn' | 'error';
2
- export type LogFields = Record<string, unknown>;
3
- export interface Log {
4
- info(message: string, fields?: LogFields): void;
5
- warn(message: string, fields?: LogFields): void;
6
- error(error: unknown, fields?: LogFields): void;
7
- }
8
- export interface LogTags {
9
- extension: string;
10
- part: string;
11
- version?: string;
12
- base?: LogFields;
13
- }
14
- export type LogWrite = (line: string) => void;
1
+ import { type Fields, type Logger, type LoggerOptions } from '../vendor/logs/index.js';
2
+ export type LogFields = Fields;
3
+ export type Log = Logger;
15
4
  export declare const messageOf: (error: unknown) => string;
16
- export declare const errorFields: (error: unknown) => LogFields;
17
- export type LineAt = (level: LogLevel, message: string, fields: LogFields) => void;
18
- export declare const withLineAt: (log: Log, at: LineAt) => Log;
19
- export declare const createLog: (tags: LogTags, write?: LogWrite) => Log;
20
- export declare const logAt: (log: Log, level: LogLevel, message: string, fields: LogFields) => void;
5
+ export declare const createLog: (tags: Pick<LoggerOptions, "extension" | "part" | "version" | "base">, write?: LoggerOptions["write"]) => Log;
package/dist/log/log.js CHANGED
@@ -1,42 +1,12 @@
1
- import { currentAgcid } from '../agcid/current.js';
2
- export const messageOf = (error) => error instanceof Error ? error.message : String(error);
3
- export const errorFields = (error) => {
4
- if (!(error instanceof Error))
5
- return { err: { message: String(error) } };
6
- return { err: { type: error.name, message: error.message, stack: error.stack } };
7
- };
8
- // Spread twice: the key order stays, and a field never overwrites time, level, msg, tags or agcid.
9
- const line = (level, message, tags, fields) => {
10
- const agcid = currentAgcid();
11
- const ids = { 'extension.id': tags.extension, 'extension.part': tags.part };
12
- const version = tags.version === undefined ? {} : { version: tags.version };
13
- const own = { time: new Date().toISOString(), level, msg: message, ...ids, ...version };
14
- const fixed = agcid ? { ...own, agcid } : own;
15
- return `${JSON.stringify({ ...fixed, ...tags.base, ...fields, ...fixed })}\n`;
16
- };
17
- const stderrWrite = (text) => void process.stderr.write(text);
18
- const raw = new WeakMap();
19
- // Registers how a Log writes a line as given, so logAt keeps every field on it.
20
- export const withLineAt = (log, at) => {
21
- raw.set(log, at);
22
- return log;
23
- };
24
- export const createLog = (tags, write = stderrWrite) => {
25
- const at = (level, message, fields) => write(line(level, message, tags, fields));
26
- const log = {
27
- info: (message, fields = {}) => at('info', message, fields),
28
- warn: (message, fields = {}) => at('warn', message, fields),
29
- error: (error, fields = {}) => at('error', messageOf(error), { ...fields, ...errorFields(error) }),
30
- };
31
- return withLineAt(log, at);
32
- };
33
- // A line at any level with no err field (an error-level line that is not an error event).
34
- export const logAt = (log, level, message, fields) => {
35
- const at = raw.get(log);
36
- if (at)
37
- at(level, message, fields);
38
- else if (level === 'error')
39
- log.error(message, fields);
40
- else
41
- log[level](message, fields);
42
- };
1
+ import { createLogger } from '../vendor/logs/index.js';
2
+ import { requestScope } from '../agcid/current.js';
3
+ // Never throws: a value with no printable form (a null-prototype object) reads [unprintable].
4
+ export const messageOf = (error) => {
5
+ try {
6
+ return error instanceof Error ? String(error.message) : String(error);
7
+ }
8
+ catch {
9
+ return '[unprintable]';
10
+ }
11
+ };
12
+ export const createLog = (tags, write) => createLogger({ ...tags, context: () => requestScope.getStore(), write });
package/dist/log/span.js CHANGED
@@ -1,19 +1,15 @@
1
- import { errorFields, logAt } from './log.js';
2
- // One line per span; a nested span is its own line, the agcid on both links them.
1
+ import {} from './log.js';
2
+ // One span row per call; a nested span is its own row, the agcid on both links them.
3
3
  export const createSpan = (log, spans) => async (name, fn) => {
4
4
  const start = performance.now();
5
- const end = (ok, err) => {
6
- const span = { name, ms: Math.round(performance.now() - start), ok };
7
- spans?.push(ok ? span : { ...span, err });
8
- logAt(log, ok ? 'info' : 'error', 'span', ok ? span : { ...span, ...errorFields(err) });
9
- };
5
+ const ms = () => Math.round(performance.now() - start);
10
6
  try {
11
- const value = await fn();
12
- end(true);
7
+ const value = await log.span(name, fn);
8
+ spans?.push({ name, ms: ms(), ok: true });
13
9
  return value;
14
10
  }
15
11
  catch (err) {
16
- end(false, err);
12
+ spans?.push({ name, ms: ms(), ok: false, err });
17
13
  throw err;
18
14
  }
19
15
  };
@@ -0,0 +1,13 @@
1
+ import { type UserType } from '../vendor/logs/index.js';
2
+ type Header = (name: string) => string | undefined;
3
+ export declare const printable: (text: string | undefined) => string;
4
+ export declare const declaredType: (header: Header) => UserType | undefined;
5
+ export declare const clientOf: (header: Header) => string | null;
6
+ export declare const userTypeOf: (header: Header, path: string) => UserType;
7
+ export declare const whoOf: (header: Header, path: string) => {
8
+ user_type: "test" | "user" | "agent" | "automation" | "service" | "bot";
9
+ client: string | null;
10
+ session: string | null;
11
+ sub: null;
12
+ };
13
+ export {};
@@ -0,0 +1,48 @@
1
+ import {} from '../vendor/logs/index.js';
2
+ const DECLARED = ['test', 'service', 'automation'];
3
+ // The user agent families, specific first: an AI client's agent string also says Mozilla.
4
+ const FAMILIES = [
5
+ ['claude-code', /claude-code|claude-cli/i],
6
+ ['cursor', /cursor/i],
7
+ ['chatgpt', /chatgpt|openai/i],
8
+ ['vscode', /vscode|visual studio code/i],
9
+ ['curl', /^curl\//i],
10
+ ['node', /^node|undici|axios|node-fetch/i],
11
+ ['browser', /mozilla/i],
12
+ ];
13
+ const AI = ['claude-code', 'cursor', 'chatgpt'];
14
+ const BOT = /bot|crawl|spider|slurp|scan|nikto|zgrab|masscan/i;
15
+ const BOT_PATH = /\.(php|asp|aspx|env)$|^\/wp-|^\/\.git/i;
16
+ const MACHINE = /^(curl|wget|node|undici|python|go-http|axios|java|okhttp|libwww)/i;
17
+ // A header value as a line: control characters out (the length cut is the caller's).
18
+ export const printable = (text) => (text ?? '').replace(/[\u0000-\u001f\u007f]/g, '');
19
+ export const declaredType = (header) => {
20
+ const declared = header('x-client-type');
21
+ return declared && DECLARED.includes(declared) ? declared : undefined;
22
+ };
23
+ export const clientOf = (header) => {
24
+ const named = printable(header('x-client')).trim().toLowerCase().slice(0, 64);
25
+ if (named)
26
+ return named;
27
+ const agent = header('user-agent') ?? '';
28
+ return FAMILIES.find(([, pattern]) => pattern.test(agent))?.[0] ?? null;
29
+ };
30
+ // Declared first, then a known AI client, a crawler or scanner, a machine agent, else a person.
31
+ export const userTypeOf = (header, path) => {
32
+ const agent = header('user-agent') ?? '';
33
+ const client = clientOf(header);
34
+ const declared = declaredType(header);
35
+ if (declared)
36
+ return declared;
37
+ if (client && AI.includes(client))
38
+ return 'agent';
39
+ if (BOT.test(agent) || BOT_PATH.test(path))
40
+ return 'bot';
41
+ return MACHINE.test(agent) ? 'automation' : 'user';
42
+ };
43
+ export const whoOf = (header, path) => ({
44
+ user_type: userTypeOf(header, path),
45
+ client: clientOf(header),
46
+ session: printable(header('agsid')).slice(0, 128) || null,
47
+ sub: null,
48
+ });
@@ -0,0 +1 @@
1
+ export { createEventsClient, createLogger, EventSchema, KINDS, LEVELS, parseLine, USER_TYPES, type Event, type EventInput, type EventsClientOptions, type Fields, type HttpRow, type JobRow, type Kind, type Level, type LineSource, type Logger, type LoggerOptions, type McpRow, type PostEvent, type PostResult, type Row, type RowContext, type UserType, } from '../vendor/logs/index.js';
@@ -0,0 +1,2 @@
1
+ // @agentage/extension/logs: the event line, shipped inside the kit until @agentage/logs is on npm.
2
+ export { createEventsClient, createLogger, EventSchema, KINDS, LEVELS, parseLine, USER_TYPES, } from '../vendor/logs/index.js';