@agentage/extension 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +2 -0
  2. package/dist/agcid/agcid.d.ts +1 -1
  3. package/dist/agcid/agcid.js +18 -4
  4. package/dist/agcid/current.d.ts +4 -1
  5. package/dist/agcid/current.js +2 -0
  6. package/dist/agcid/header.js +2 -1
  7. package/dist/agcid/scope.js +5 -3
  8. package/dist/auth/token-check.d.ts +1 -0
  9. package/dist/auth/token-check.js +17 -1
  10. package/dist/auth/verify-token.js +2 -2
  11. package/dist/context/context.d.ts +5 -0
  12. package/dist/context/context.js +17 -0
  13. package/dist/context/recording-log.js +12 -10
  14. package/dist/context/test-context.d.ts +3 -0
  15. package/dist/context/test-context.js +7 -1
  16. package/dist/discovery/discovery.d.ts +1 -1
  17. package/dist/discovery/discovery.schema.d.ts +2 -0
  18. package/dist/health/health.d.ts +2 -0
  19. package/dist/health/health.js +17 -0
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/log/log.d.ts +4 -11
  23. package/dist/log/log.js +3 -41
  24. package/dist/log/span.js +6 -10
  25. package/dist/log/who.d.ts +12 -0
  26. package/dist/log/who.js +46 -0
  27. package/dist/logs/index.d.ts +1 -0
  28. package/dist/logs/index.js +2 -0
  29. package/dist/manifest/manifest.schema.d.ts +4 -0
  30. package/dist/manifest/primitives.schema.d.ts +4 -0
  31. package/dist/manifest/primitives.schema.js +2 -1
  32. package/dist/mcp/mcp-app.js +23 -2
  33. package/dist/mcp/server.js +11 -5
  34. package/dist/pages/pages-app.js +6 -3
  35. package/dist/runtime/main.js +7 -2
  36. package/dist/runtime/part-runners.js +2 -1
  37. package/dist/runtime/run-part.d.ts +2 -0
  38. package/dist/runtime/run-part.js +20 -6
  39. package/dist/server/app.js +5 -4
  40. package/dist/server/errors.js +24 -3
  41. package/dist/server/request-line.d.ts +2 -2
  42. package/dist/server/request-line.js +31 -12
  43. package/dist/tool/up/local-record.d.ts +1 -1
  44. package/dist/vendor/logs/error-row.d.ts +3 -0
  45. package/dist/vendor/logs/error-row.js +16 -0
  46. package/dist/vendor/logs/event.schema.d.ts +46 -0
  47. package/dist/vendor/logs/event.schema.js +24 -0
  48. package/dist/vendor/logs/events-client.d.ts +22 -0
  49. package/dist/vendor/logs/events-client.js +74 -0
  50. package/dist/vendor/logs/index.d.ts +5 -0
  51. package/dist/vendor/logs/index.js +5 -0
  52. package/dist/vendor/logs/logger.d.ts +31 -0
  53. package/dist/vendor/logs/logger.js +56 -0
  54. package/dist/vendor/logs/parse-line.d.ts +6 -0
  55. package/dist/vendor/logs/parse-line.js +29 -0
  56. package/dist/vendor/logs/redact.d.ts +3 -0
  57. package/dist/vendor/logs/redact.js +27 -0
  58. package/dist/vendor/logs/rows.d.ts +34 -0
  59. package/dist/vendor/logs/rows.js +57 -0
  60. package/dist/vendor/logs/uuidv7.d.ts +1 -0
  61. package/dist/vendor/logs/uuidv7.js +10 -0
  62. package/dist/worker/run-log.js +15 -18
  63. package/dist/worker/scheduler.js +11 -4
  64. package/package.json +10 -3
  65. package/schemas/error-envelope.schema.json +1 -1
  66. package/schemas/extension-discovery.schema.json +2 -1
  67. package/schemas/extension-package.schema.json +4 -2
  68. 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,3 @@
1
1
  export { AGCID_HEADER, AGCID_PATTERN, isAgcid } from './header.js';
2
2
  export declare const uuidv7: (now?: number, random?: Buffer) => string;
3
- export declare const agcidOf: (incoming: unknown) => string;
3
+ export declare const agcidOf: (incoming: unknown, traceparent?: unknown) => string;
@@ -1,14 +1,28 @@
1
1
  import { randomBytes } from 'node:crypto';
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.
5
+ // RFC 9562 UUIDv7 as 32 lowercase hex, a valid W3C trace id: 48-bit ms, version 7, variant 10.
6
6
  export const uuidv7 = (now = Date.now(), random = randomBytes(10)) => {
7
7
  const bytes = Buffer.alloc(16);
8
8
  bytes.writeUIntBE(now, 0, 6);
9
9
  random.copy(bytes, 6, 0, 10);
10
10
  bytes.writeUInt8((bytes.readUInt8(6) & 0x0f) | 0x70, 6);
11
11
  bytes.writeUInt8((bytes.readUInt8(8) & 0x3f) | 0x80, 8);
12
- return hyphenate(bytes.toString('hex'));
12
+ return bytes.toString('hex');
13
13
  };
14
- export const agcidOf = (incoming) => (isAgcid(incoming) ? incoming : uuidv7());
14
+ const DASHED = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
15
+ const ZERO = '0'.repeat(32);
16
+ // 32 hex, or a UUID in its 8-4-4-4-12 form without the dashes; all zeros is no id (W3C).
17
+ const ownOf = (value) => {
18
+ if (typeof value !== 'string')
19
+ return undefined;
20
+ const lower = value.toLowerCase();
21
+ const id = DASHED.test(lower) ? lower.replaceAll('-', '') : lower;
22
+ return isAgcid(id) && id !== ZERO ? id : undefined;
23
+ };
24
+ const traceIdOf = (traceparent) => typeof traceparent === 'string' && TRACEPARENT_PATTERN.test(traceparent)
25
+ ? ownOf(traceparent.slice(3, 35))
26
+ : undefined;
27
+ // A valid agcid header, else the traceparent trace id, else minted.
28
+ 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 currentContext: () => RowContext | undefined;
8
11
  export declare const TRACEPARENT_PATTERN: RegExp;
9
12
  export {};
@@ -1,5 +1,7 @@
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
+ export const currentContext = () => requestScope.getStore();
5
7
  export const TRACEPARENT_PATTERN = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
@@ -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 } 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
+ process.kill(process.pid, 'SIGTERM');
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,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 });
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';
@@ -62,6 +62,8 @@ const serverContext = (options) => {
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';
@@ -41,6 +42,16 @@ export const healthBody = async (options) => {
41
42
  data: { ...data, uptimeSeconds, checkedAt: isoSeconds(now), checks },
42
43
  };
43
44
  };
45
+ // Names a check whose status moved, so a recovery names what recovered.
46
+ const changed = (log, from, to, was, now) => {
47
+ const check = Object.keys(now).find((name) => was[name] !== now[name]) ?? '';
48
+ const fields = {
49
+ 'agentage.health.from': from,
50
+ 'agentage.health.to': to,
51
+ 'agentage.health.check': check,
52
+ };
53
+ log?.event('health.changed', fields, `health.changed ${from} to ${to}`);
54
+ };
44
55
  // Answers only on loopback: the container HEALTHCHECK and an operator on the node, never the gateway.
45
56
  export const createHealthHandler = (options) => {
46
57
  const resolved = {
@@ -48,10 +59,16 @@ export const createHealthHandler = (options) => {
48
59
  instance: options.instance ?? randomBytes(4).toString('hex'),
49
60
  startedAt: options.startedAt ?? Date.now(),
50
61
  };
62
+ let last;
63
+ let lastChecks = {};
51
64
  return async (req, res) => {
52
65
  if (!isLoopback(req.socket.localAddress))
53
66
  throw fail('NOT_FOUND', 'Not found');
54
67
  const body = await healthBody(resolved);
68
+ const { status: to, checks } = body.data;
69
+ if (last !== undefined && last !== to)
70
+ changed(options.log, last, to, lastChecks, checks);
71
+ [last, lastChecks] = [to, checks];
55
72
  res.setHeader('Cache-Control', 'no-store');
56
73
  res.status(body.data.status === 'unavailable' ? 503 : 200).json(body);
57
74
  };
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,10 +1,7 @@
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
- }
1
+ import { type Fields, type Level, type Logger } from '../vendor/logs/index.js';
2
+ export type LogLevel = Level;
3
+ export type LogFields = Fields;
4
+ export type Log = Logger;
8
5
  export interface LogTags {
9
6
  extension: string;
10
7
  part: string;
@@ -13,8 +10,4 @@ export interface LogTags {
13
10
  }
14
11
  export type LogWrite = (line: string) => void;
15
12
  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
13
  export declare const createLog: (tags: LogTags, write?: LogWrite) => Log;
20
- export declare const logAt: (log: Log, level: LogLevel, message: string, fields: LogFields) => void;
package/dist/log/log.js CHANGED
@@ -1,42 +1,4 @@
1
- import { currentAgcid } from '../agcid/current.js';
1
+ import { createLogger } from '../vendor/logs/index.js';
2
+ import { currentContext } from '../agcid/current.js';
2
3
  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
- };
4
+ export const createLog = (tags, write) => createLogger({ ...tags, context: currentContext, ...(write ? { 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,12 @@
1
+ import { type UserType } from '../vendor/logs/index.js';
2
+ type Header = (name: string) => string | undefined;
3
+ export declare const declaredType: (header: Header) => UserType | undefined;
4
+ export declare const clientOf: (header: Header) => string | null;
5
+ export declare const userTypeOf: (header: Header, path: string) => UserType;
6
+ export declare const whoOf: (header: Header, path: string) => {
7
+ user_type: "test" | "user" | "agent" | "automation" | "service" | "bot";
8
+ client: string | null;
9
+ session: string | null;
10
+ sub: null;
11
+ };
12
+ export {};
@@ -0,0 +1,46 @@
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
+ export const declaredType = (header) => {
18
+ const declared = header('x-client-type');
19
+ return declared && DECLARED.includes(declared) ? declared : undefined;
20
+ };
21
+ export const clientOf = (header) => {
22
+ const named = header('x-client')?.trim().toLowerCase().slice(0, 64);
23
+ if (named)
24
+ return named;
25
+ const agent = header('user-agent') ?? '';
26
+ return FAMILIES.find(([, pattern]) => pattern.test(agent))?.[0] ?? null;
27
+ };
28
+ // Declared first, then a known AI client, a crawler or scanner, a machine agent, else a person.
29
+ export const userTypeOf = (header, path) => {
30
+ const agent = header('user-agent') ?? '';
31
+ const client = clientOf(header);
32
+ const declared = declaredType(header);
33
+ if (declared)
34
+ return declared;
35
+ if (client && AI.includes(client))
36
+ return 'agent';
37
+ if (BOT.test(agent) || BOT_PATH.test(path))
38
+ return 'bot';
39
+ return MACHINE.test(agent) ? 'automation' : 'user';
40
+ };
41
+ export const whoOf = (header, path) => ({
42
+ user_type: userTypeOf(header, path),
43
+ client: clientOf(header),
44
+ session: header('agsid')?.slice(0, 128) ?? null,
45
+ sub: null,
46
+ });
@@ -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';
@@ -25,11 +25,13 @@ declare const PartsSchema: z.ZodObject<{
25
25
  postgres: "postgres";
26
26
  signoz: "signoz";
27
27
  git: "git";
28
+ clickhouse: "clickhouse";
28
29
  }>, z.ZodObject<{
29
30
  kind: z.ZodEnum<{
30
31
  postgres: "postgres";
31
32
  signoz: "signoz";
32
33
  git: "git";
34
+ clickhouse: "clickhouse";
33
35
  }>;
34
36
  }, z.core.$strict>]>>;
35
37
  }, z.core.$strict>;
@@ -79,11 +81,13 @@ export declare const PackageSchema: z.ZodObject<{
79
81
  postgres: "postgres";
80
82
  signoz: "signoz";
81
83
  git: "git";
84
+ clickhouse: "clickhouse";
82
85
  }>, z.ZodObject<{
83
86
  kind: z.ZodEnum<{
84
87
  postgres: "postgres";
85
88
  signoz: "signoz";
86
89
  git: "git";
90
+ clickhouse: "clickhouse";
87
91
  }>;
88
92
  }, z.core.$strict>]>>;
89
93
  }, z.core.$strict>;
@@ -18,12 +18,16 @@ export declare const STORE_KINDS: {
18
18
  readonly git: {
19
19
  readonly migrations: false;
20
20
  };
21
+ readonly clickhouse: {
22
+ readonly migrations: false;
23
+ };
21
24
  };
22
25
  export declare const SERVED_KINDS: readonly StoreKind[];
23
26
  export declare const StoreKindSchema: z.ZodEnum<{
24
27
  postgres: "postgres";
25
28
  signoz: "signoz";
26
29
  git: "git";
30
+ clickhouse: "clickhouse";
27
31
  }>;
28
32
  export declare const FULL_SHA: RegExp;
29
33
  export declare const CommitSchema: z.ZodString;
@@ -48,9 +48,10 @@ export const STORE_KINDS = {
48
48
  postgres: { migrations: true },
49
49
  signoz: { migrations: false },
50
50
  git: { migrations: false },
51
+ clickhouse: { migrations: false },
51
52
  };
52
53
  // STORE_KINDS[kind].migrations: the api image carries a migrate job. SERVED_KINDS moves with the estate.
53
- export const SERVED_KINDS = ['postgres', 'signoz'];
54
+ export const SERVED_KINDS = ['postgres', 'signoz', 'clickhouse'];
54
55
  export const StoreKindSchema = z.enum(Object.keys(STORE_KINDS));
55
56
  export const FULL_SHA = /^[0-9a-f]{40}$/;
56
57
  export const CommitSchema = z.string().regex(FULL_SHA, { message: 'full 40-hex git sha' });