@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
@@ -3,8 +3,10 @@ import { pipeline } from 'node:stream/promises';
3
3
  import cors from 'cors';
4
4
  import express, {} from 'express';
5
5
  import { createMcpHandler } from '@modelcontextprotocol/server';
6
- import { strongest } from '../auth/token-check.js';
6
+ import { requestScope } from '../agcid/current.js';
7
+ import { setCaller, strongest } from '../auth/token-check.js';
7
8
  import { fail } from '../envelope/envelope.js';
9
+ import { declaredType } from '../log/who.js';
8
10
  import { BODY_LIMIT, createPartApp, PUBLIC_CORS } from '../server/app.js';
9
11
  import { serverFactory } from './server.js';
10
12
  import { prefixed } from './tools.js';
@@ -43,7 +45,25 @@ const guard = async (options, req, body) => {
43
45
  }
44
46
  if (needed.length === 0)
45
47
  return false;
46
- return (await options.tokenCheck(req.get('authorization'), strongest(needed))) !== null;
48
+ const caller = await options.tokenCheck(req.get('authorization'), strongest(needed));
49
+ setCaller(req, caller);
50
+ return caller !== null;
51
+ };
52
+ // A tools/call leaves its mcp row and no http row (Q1); initialize names the client (Q14).
53
+ const markRow = (options, req, res, body) => {
54
+ const messages = messagesOf(body);
55
+ const scope = requestScope.getStore();
56
+ const id = options.pkg.agentage.id;
57
+ const known = (m) => options.tools.some((t) => prefixed(id, t.name) === m?.params?.name);
58
+ // An unknown tool never reaches a handler, so it keeps its http row.
59
+ if (messages.some((m) => m?.method === 'tools/call' && known(m))) {
60
+ res.locals['toolCall'] = true;
61
+ if (scope)
62
+ scope.user_type = declaredType((name) => req.get(name)) ?? 'agent';
63
+ }
64
+ const name = messages.find((m) => m?.method === 'initialize')?.params?.clientInfo?.name;
65
+ if (typeof name === 'string')
66
+ res.locals['clientInfo'] = name.slice(0, 64);
47
67
  };
48
68
  const webRequest = (req, body) => {
49
69
  const headers = new Headers();
@@ -74,6 +94,7 @@ const handle = (handler, options) => async (req, res) => {
74
94
  if (message === undefined)
75
95
  return void res.status(400).json(PARSE_ERROR);
76
96
  const auth = await guard(options, req, message);
97
+ markRow(options, req, res, message);
77
98
  await send(await handler.fetch(webRequest(req, body), { parsedBody: message }), res, auth);
78
99
  };
79
100
  const methodNotAllowed = (_req, res) => {
@@ -6,10 +6,10 @@ import {} from '../log/log.js';
6
6
  import { prefixed } from './tools.js';
7
7
  const text = (value) => [{ type: 'text', text: value }];
8
8
  // A failed tool: isError, the REST error shape, an agcid (minted outside a request); else INTERNAL.
9
- const errorResult = (err, log) => {
9
+ const errorResult = (err, log, tool) => {
10
10
  const failure = isFailure(err) ? err : fail('INTERNAL', 'Internal error');
11
11
  if (failure.status >= 500)
12
- log.error(err);
12
+ log.error(err, tool);
13
13
  const error = { code: failure.code, message: failure.message, agcid: agcidOf(currentAgcid()) };
14
14
  return { isError: true, content: text(error.message), structuredContent: { error } };
15
15
  };
@@ -24,14 +24,19 @@ const argsOf = (entry, args) => {
24
24
  const fields = new Set(parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'));
25
25
  throw fail('VALIDATION_ERROR', `Invalid arguments: ${[...fields].join(', ')}`);
26
26
  };
27
- const callback = (entry, log) => async (args) => {
27
+ const callback = (entry, log, tool) => async (args) => {
28
+ const start = performance.now();
29
+ const ms = () => Math.round(performance.now() - start);
28
30
  try {
29
31
  const output = entry.spec.output.parse(await entry.handler(argsOf(entry, args)));
32
+ log.mcp({ tool, ms: ms() });
30
33
  const content = text(JSON.stringify(output));
31
34
  return { content, structuredContent: output };
32
35
  }
33
36
  catch (err) {
34
- return errorResult(err, log);
37
+ // A 4xx is a rejection, not a failure: the row stays info.
38
+ log.mcp({ tool, ms: ms(), ...(isFailure(err) && err.status < 500 ? {} : { error: err }) });
39
+ return errorResult(err, log, tool);
35
40
  }
36
41
  };
37
42
  // One fresh server per request (stateless); serverInfo agentage-{id} at the package version.
@@ -43,7 +48,8 @@ export const serverFactory = (identity, tools, log) => () => {
43
48
  inputSchema: listedOnly(entry.spec.input),
44
49
  outputSchema: entry.spec.output,
45
50
  };
46
- server.registerTool(prefixed(identity.id, entry.name), config, callback(entry, log));
51
+ const tool = prefixed(identity.id, entry.name);
52
+ server.registerTool(tool, config, callback(entry, log, tool));
47
53
  }
48
54
  return server;
49
55
  };
@@ -36,18 +36,21 @@ const SiteSchema = z.record(z.string().regex(KEY), ENTRY).superRefine((site, ctx
36
36
  });
37
37
  const lookup = (site, path) => {
38
38
  if (site[path] !== undefined)
39
- return { entry: site[path], rest: '' };
39
+ return { entry: site[path], rest: '', key: path };
40
40
  const key = Object.keys(site)
41
41
  .filter((k) => k.endsWith('/*') && path.startsWith(k.slice(0, -1)))
42
42
  .sort((a, b) => b.length - a.length)[0];
43
- return key ? { entry: site[key], rest: path.slice(key.length - 1) } : undefined;
43
+ return key
44
+ ? { entry: site[key], rest: path.slice(key.length - 1), key }
45
+ : undefined;
44
46
  };
45
47
  export const NOT_FOUND_PAGE = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><title>Not found</title></head><body><p>Not found</p></body></html>\n';
46
48
  const serve = (site) => (req, res, next) => {
47
49
  const found = lookup(site, req.path);
48
50
  if (!found)
49
51
  return next();
50
- const { entry, rest } = found;
52
+ const { entry, rest, key } = found;
53
+ res.locals['route'] = key;
51
54
  const query = req.originalUrl.indexOf('?');
52
55
  if (typeof entry === 'object' && 'redirect' in entry)
53
56
  return res.redirect(308, entry.redirect + rest + (query < 0 ? '' : req.originalUrl.slice(query)));
@@ -1,13 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { createLog } from '../log/log.js';
3
- import { runPart } from './run-part.js';
3
+ import { partLog, runPart } from './run-part.js';
4
4
  // Image entry: `node node_modules/@agentage/extension/dist/runtime/main.js api` in /app.
5
5
  const part = process.argv[2] ?? 'api';
6
+ const crashLog = () => partLog() ?? createLog({ extension: 'unknown', part });
7
+ process.on('uncaughtException', (err) => {
8
+ crashLog().error(err, 'uncaughtException');
9
+ process.exit(1);
10
+ });
6
11
  try {
7
12
  await runPart({ dir: process.cwd(), part, env: process.env });
8
13
  }
9
14
  catch (err) {
10
15
  // The manifest may be what failed, so the id is not known here; the line keeps the stack.
11
- createLog({ extension: 'unknown', part }).error(err);
16
+ crashLog().error(err);
12
17
  process.exit(1);
13
18
  }
@@ -56,7 +56,8 @@ const worker = async (input) => {
56
56
  span: createSpan(log),
57
57
  schedule: scheduler.schedule,
58
58
  });
59
- const checks = { ...input.base.checks, ...scheduler.checks() };
59
+ // The same object ctx.health adds to, so a later registration still shows.
60
+ const checks = Object.assign(input.base.checks ?? {}, scheduler.checks());
60
61
  scheduler.start();
61
62
  return {
62
63
  app: createPartApp({ ...input.base, checks, part: 'worker', mount: () => undefined }),
@@ -1,4 +1,5 @@
1
1
  import { type Server } from 'node:http';
2
+ import { type Log } from '../log/log.js';
2
3
  import { type ImportModule } from '../manifest/entry.js';
3
4
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
4
5
  import { type ImagePartKind } from '../manifest/primitives.schema.js';
@@ -13,4 +14,5 @@ export interface RunPartOptions {
13
14
  serve?: Pick<ServeOptions, 'signals' | 'exit'>;
14
15
  }
15
16
  export declare const partOf: (pkg: ExtensionPackage, part: string) => ImagePartKind;
17
+ export declare const partLog: () => Log | undefined;
16
18
  export declare const runPart: (options: RunPartOptions) => Promise<Server>;
@@ -1,4 +1,5 @@
1
1
  import {} from 'node:http';
2
+ import { hostname } from 'node:os';
2
3
  import { createContext } from '../context/context.js';
3
4
  import { readSecrets, SECRETS_DIR } from '../context/secrets.js';
4
5
  import { settingsFromEnv } from '../context/settings.js';
@@ -7,6 +8,7 @@ import {} from '../discovery/discovery.schema.js';
7
8
  import { declaredScopes, partAuth, platformOf } from '../auth/part-auth.js';
8
9
  import { readOpenapi } from '../discovery/openapi.js';
9
10
  import { createLog } from '../log/log.js';
11
+ import {} from '../health/health.js';
10
12
  import {} from '../manifest/entry.js';
11
13
  import {} from '../manifest/manifest.schema.js';
12
14
  import { hasStore, imageParts } from '../manifest/parts.js';
@@ -33,7 +35,7 @@ export const partOf = (pkg, part) => {
33
35
  };
34
36
  // ui serves files and gets no ctx; every other part gets the store when the manifest has postgres.
35
37
  const storeFor = ({ pkg, part, env, log }) => part !== 'ui' && hasStore(pkg, 'postgres') ? createStore(env, log) : undefined;
36
- const contextFor = (start, part, store) => createContext({
38
+ const contextFor = (start, part, store, checks) => createContext({
37
39
  pkg: start.pkg,
38
40
  part,
39
41
  origin: start.env['AGENTAGE_ORIGIN'] || `http://127.0.0.1:${portFromEnv(start.env)}`,
@@ -43,14 +45,15 @@ const contextFor = (start, part, store) => createContext({
43
45
  store,
44
46
  secrets: start.secrets,
45
47
  platform: platformOf(start.env),
48
+ checks,
46
49
  });
47
50
  // Built on first use, so the ui runner, which never asks, has no ctx at all.
48
- const lazyContext = (start, store) => {
51
+ const lazyContext = (start, store, checks) => {
49
52
  let ctx;
50
53
  return () => {
51
54
  if (start.part === 'ui')
52
55
  throw new Error('the ui part gets no ctx');
53
- return (ctx ??= contextFor(start, start.part, store));
56
+ return (ctx ??= contextFor(start, start.part, store, checks));
54
57
  };
55
58
  };
56
59
  const guardFor = async (start, openapi, record) => {
@@ -77,20 +80,25 @@ const baseFor = async (start, store, openapi) => {
77
80
  const inputFor = async (options, start) => {
78
81
  const store = storeFor(start);
79
82
  const openapi = await readOpenapi(options.dir);
83
+ const base = await baseFor(start, store, openapi);
80
84
  return {
81
85
  dir: options.dir,
82
86
  pkg: start.pkg,
83
87
  env: start.env,
84
- ctx: lazyContext(start, store),
85
- base: await baseFor(start, store, openapi),
88
+ ctx: lazyContext(start, store, base.checks),
89
+ base,
86
90
  openapi,
87
91
  importModule: options.importModule,
88
92
  };
89
93
  };
94
+ let running;
95
+ // The running part's log, so a crash in the image entry is an error row of that part.
96
+ export const partLog = () => running;
90
97
  export const runPart = async (options) => {
91
98
  const pkg = await readManifest(options.dir);
92
99
  const part = partOf(pkg, options.part);
93
100
  const log = createLog({ extension: pkg.agentage.id, part, version: pkg.version });
101
+ running = log;
94
102
  const names = part === 'ui' ? [] : (pkg.agentage.secrets ?? []);
95
103
  const secrets = await readSecrets(names, options.secretsDir ?? SECRETS_DIR, part);
96
104
  const start = { pkg, part, env: options.env, log, secrets };
@@ -98,5 +106,11 @@ export const runPart = async (options) => {
98
106
  if (stop)
99
107
  for (const signal of options.serve?.signals ?? ['SIGTERM', 'SIGINT'])
100
108
  process.once(signal, stop);
101
- return serve({ app, port: portFromEnv(options.env), log, ...options.serve });
109
+ const server = await serve({ app, port: portFromEnv(options.env), log, ...options.serve });
110
+ const { commit } = buildInfoFromEnv(options.env);
111
+ log.event('startup', {
112
+ 'agentage.startup.commit': commit,
113
+ 'agentage.startup.instance': hostname(),
114
+ });
115
+ return server;
102
116
  };
@@ -48,6 +48,7 @@ const healthHandler = (options) => createHealthHandler({
48
48
  version: options.pkg.version,
49
49
  build: options.build,
50
50
  checks: options.checks,
51
+ log: options.log,
51
52
  });
52
53
  // The kit app every part image runs: agcid, headers, /health, discovery, the part, the envelope.
53
54
  export const createPartApp = (options) => {
@@ -83,11 +84,11 @@ const wellKnownHandler = (render) => async (_req, res) => {
83
84
  };
84
85
  // Before the body is read: each request checked for the access its OpenAPI operation declares.
85
86
  const routeGuard = (options) => async (req, res, next) => {
86
- if (!options.tokenCheck)
87
- return next();
88
87
  const { routes } = options;
89
- const known = routes?.some((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
90
- if (routes?.length && !known)
88
+ const known = routes?.find((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
89
+ if (known)
90
+ res.locals['route'] = `/api/v1${known.path}`;
91
+ if (!options.tokenCheck || (routes?.length && !known))
91
92
  return next();
92
93
  const access = routeAccess(options.openapi, req.method, `/api/v1${req.path}`);
93
94
  const caller = await options.tokenCheck(req.get('authorization'), access);
@@ -2,6 +2,7 @@ import {} from 'express';
2
2
  import { agcidOfResponse } from '../agcid/scope.js';
3
3
  import { errorEnvelope, fail, isFailure } from '../envelope/envelope.js';
4
4
  import {} from '../log/log.js';
5
+ import { routeOf } from './request-line.js';
5
6
  const bodyParserFailure = (err) => {
6
7
  const type = err?.type;
7
8
  if (type === 'entity.too.large')
@@ -22,19 +23,39 @@ export const notFound = () => {
22
23
  const GONE_CODES = ['ERR_STREAM_PREMATURE_CLOSE', 'ECONNABORTED'];
23
24
  // A client abort leaves the socket destroyed; the same code from an app-side stream does not.
24
25
  const clientGone = (err, res) => GONE_CODES.includes(err?.code) && res.socket?.destroyed !== false;
25
- export const errorHandler = (log) => (err, _req, res, _next) => {
26
+ // The http row's agentage.auth.reason on a 401 or 403.
27
+ const authReason = (req, failure) => {
28
+ if (failure.status === 403)
29
+ return 'insufficient_scope';
30
+ if (failure.status !== 401)
31
+ return undefined;
32
+ if (!req.get('authorization'))
33
+ return 'missing_token';
34
+ return /expired/i.test(failure.message)
35
+ ? 'expired'
36
+ : /revoked/i.test(failure.message)
37
+ ? 'revoked'
38
+ : 'invalid_token';
39
+ };
40
+ const markRow = (req, res, failure, err) => {
41
+ res.locals['authReason'] = authReason(req, failure);
42
+ if (failure.status >= 500)
43
+ res.locals['errorType'] = err instanceof Error ? err.name : 'Error';
44
+ };
45
+ export const errorHandler = (log) => (err, req, res, _next) => {
26
46
  // A gone client or a started answer cannot take an envelope: close it, never write twice.
27
47
  const gone = clientGone(err, res);
28
48
  if (gone || res.headersSent) {
29
49
  if (gone)
30
50
  log.warn('client closed early');
31
51
  else
32
- log.error(err);
52
+ log.error(err, routeOf(req, res));
33
53
  return void res.destroy();
34
54
  }
35
55
  const failure = toFailure(err);
36
56
  if (failure.status >= 500)
37
- log.error(err);
57
+ log.error(err, routeOf(req, res));
58
+ markRow(req, res, failure, err);
38
59
  if (failure.retryAfter !== undefined)
39
60
  res.setHeader('Retry-After', String(failure.retryAfter));
40
61
  for (const [name, value] of Object.entries(failure.headers ?? {}))
@@ -1,4 +1,4 @@
1
- import { type Request, type RequestHandler } from 'express';
1
+ import { type Request, type RequestHandler, type Response } from 'express';
2
2
  import { type Log } from '../log/log.js';
3
- export declare const routeOf: (req: Request) => string;
3
+ export declare const routeOf: (req: Request, res?: Response) => string;
4
4
  export declare const requestLine: (log: Log) => RequestHandler;
@@ -1,25 +1,44 @@
1
1
  import {} from 'express';
2
- import { agcidOfResponse } from '../agcid/scope.js';
3
- import { logAt } from '../log/log.js';
2
+ import { requestScope } from '../agcid/current.js';
3
+ import {} from '../log/log.js';
4
4
  const MOUNTS = ['/api/v1', '/mcp', '/.well-known', '/ui'];
5
- const levelOf = (status) => status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info';
5
+ const ASSET = /\.(m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf)$/i;
6
6
  // The matched route template, never the raw URL, so no id or query string reaches the log.
7
- export const routeOf = (req) => {
8
- const url = req.originalUrl.split('?')[0] ?? '';
9
- const prefix = MOUNTS.find((m) => url === m || url.startsWith(`${m}/`)) ?? '/';
7
+ export const routeOf = (req, res) => {
8
+ const known = res?.locals?.['route'];
9
+ if (typeof known === 'string')
10
+ return known;
11
+ const url = req.originalUrl?.split('?')[0] ?? '';
12
+ const prefix = MOUNTS.find((m) => url === m || url.startsWith(`${m}/`)) ?? '';
10
13
  const path = req.route?.path;
11
14
  if (typeof path !== 'string')
12
- return prefix;
15
+ return '(unmatched)';
13
16
  return path.startsWith(prefix) ? path : `${prefix}${path}`;
14
17
  };
15
- // One line per request on finish; the 5xx error itself is errors.ts's line, never repeated here.
18
+ // A tools/call is its mcp row (Q1); a page asset served fine leaves none (Q2).
19
+ const skipped = (req, res) => res.locals['toolCall'] === true || (res.statusCode < 400 && ASSET.test(req.path));
20
+ const localOf = (res, key) => {
21
+ const value = res.locals[key];
22
+ return typeof value === 'string' ? value : undefined;
23
+ };
24
+ // One http row per request on finish; a ctx.exit() asked for in it shuts the part down after.
16
25
  export const requestLine = (log) => (req, res, next) => {
17
26
  const start = performance.now();
27
+ const scope = requestScope.getStore();
18
28
  res.on('finish', () => {
19
- const { statusCode: status } = res;
20
- const ms = Math.round(performance.now() - start);
21
- const fields = { agcid: agcidOfResponse(res), method: req.method, route: routeOf(req) };
22
- logAt(log, levelOf(status), 'request', { ...fields, status, ms });
29
+ if (!skipped(req, res))
30
+ log.http({
31
+ method: req.method,
32
+ route: routeOf(req, res),
33
+ status: res.statusCode,
34
+ ms: Math.round(performance.now() - start),
35
+ bytes: Number(res.getHeader('content-length') ?? 0),
36
+ reason: localOf(res, 'authReason'),
37
+ errorType: localOf(res, 'errorType'),
38
+ clientInfo: localOf(res, 'clientInfo'),
39
+ });
40
+ if (scope?.exit)
41
+ process.kill(process.pid, 'SIGTERM');
23
42
  });
24
43
  next();
25
44
  };
@@ -28,7 +28,7 @@ export declare const writeLocalRecord: (dir: string, pkg: ExtensionPackage, buil
28
28
  image: string;
29
29
  } | undefined;
30
30
  store?: {
31
- kind: "postgres" | "signoz" | "git";
31
+ kind: "postgres" | "signoz" | "git" | "clickhouse";
32
32
  migrations?: number | undefined;
33
33
  } | undefined;
34
34
  };
@@ -0,0 +1,3 @@
1
+ import { type Fields } from './event.schema.js';
2
+ import { type Row } from './rows.js';
3
+ export declare const errorRow: (err: unknown, where?: string | Fields) => Row;
@@ -0,0 +1,16 @@
1
+ import {} from './event.schema.js';
2
+ import { typeOf } from './rows.js';
3
+ const exceptionOf = (err) => err instanceof Error
4
+ ? {
5
+ 'exception.type': typeOf(err),
6
+ 'exception.message': err.message,
7
+ 'exception.stacktrace': err.stack ?? '',
8
+ }
9
+ : { 'exception.type': 'Error', 'exception.message': String(err) };
10
+ // where: the route, tool or job; an author's agentage.fingerprint passes through (Q11 A).
11
+ export const errorRow = (err, where) => {
12
+ const own = typeof where === 'string' ? { 'agentage.where': where } : (where ?? {});
13
+ const exception = exceptionOf(err);
14
+ const msg = `${String(exception['exception.type'])}: ${String(exception['exception.message'])}`;
15
+ return { kind: 'error', level: 'error', msg, fields: { ...exception, ...own } };
16
+ };
@@ -0,0 +1,46 @@
1
+ import { z } from 'zod';
2
+ export declare const KINDS: readonly ["http", "mcp", "job", "span", "error", "event", "log"];
3
+ export declare const LEVELS: readonly ["info", "warn", "error"];
4
+ export declare const USER_TYPES: readonly ["user", "agent", "automation", "service", "test", "bot"];
5
+ export declare const AGCID_HEX: RegExp;
6
+ export type Kind = (typeof KINDS)[number];
7
+ export type Level = (typeof LEVELS)[number];
8
+ export type UserType = (typeof USER_TYPES)[number];
9
+ export type Fields = Record<string, unknown>;
10
+ export declare const EventSchema: z.ZodObject<{
11
+ ts: z.ZodISODateTime;
12
+ level: z.ZodEnum<{
13
+ error: "error";
14
+ info: "info";
15
+ warn: "warn";
16
+ }>;
17
+ kind: z.ZodEnum<{
18
+ http: "http";
19
+ mcp: "mcp";
20
+ job: "job";
21
+ span: "span";
22
+ error: "error";
23
+ event: "event";
24
+ log: "log";
25
+ }>;
26
+ msg: z.ZodString;
27
+ extension: z.ZodString;
28
+ part: z.ZodString;
29
+ version: z.ZodDefault<z.ZodString>;
30
+ host: z.ZodOptional<z.ZodString>;
31
+ agcid: z.ZodDefault<z.ZodNullable<z.ZodString>>;
32
+ sub: z.ZodDefault<z.ZodNullable<z.ZodString>>;
33
+ session: z.ZodDefault<z.ZodNullable<z.ZodString>>;
34
+ user_type: z.ZodDefault<z.ZodEnum<{
35
+ user: "user";
36
+ agent: "agent";
37
+ automation: "automation";
38
+ service: "service";
39
+ test: "test";
40
+ bot: "bot";
41
+ }>>;
42
+ client: z.ZodDefault<z.ZodNullable<z.ZodString>>;
43
+ fields: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
44
+ }, z.core.$strip>;
45
+ export type Event = z.output<typeof EventSchema>;
46
+ export type EventInput = z.input<typeof EventSchema>;
@@ -0,0 +1,24 @@
1
+ import { z } from 'zod';
2
+ export const KINDS = ['http', 'mcp', 'job', 'span', 'error', 'event', 'log'];
3
+ export const LEVELS = ['info', 'warn', 'error'];
4
+ export const USER_TYPES = ['user', 'agent', 'automation', 'service', 'test', 'bot'];
5
+ export const AGCID_HEX = /^[0-9a-f]{32}$/;
6
+ const name = z.string().min(1).max(64);
7
+ const id = z.string().max(128).nullable().default(null);
8
+ // The line (logs-events section 1): snake_case on the wire; host is set by the shipper or the client.
9
+ export const EventSchema = z.object({
10
+ ts: z.iso.datetime({ offset: true }),
11
+ level: z.enum(LEVELS),
12
+ kind: z.enum(KINDS),
13
+ msg: z.string().max(2000),
14
+ extension: name,
15
+ part: name,
16
+ version: z.string().max(64).default(''),
17
+ host: z.string().max(253).optional(),
18
+ agcid: z.string().regex(AGCID_HEX).nullable().default(null),
19
+ sub: id,
20
+ session: id,
21
+ user_type: z.enum(USER_TYPES).default('service'),
22
+ client: z.string().max(64).nullable().default(null),
23
+ fields: z.record(z.string(), z.unknown()).default({}),
24
+ });
@@ -0,0 +1,22 @@
1
+ import { type Event, type EventInput, type Level } from './event.schema.js';
2
+ export declare const MAX_BATCH_BYTES = 900000;
3
+ export declare const MAX_BATCH_ITEMS = 1000;
4
+ export interface EventsClientOptions {
5
+ url: string;
6
+ token: string;
7
+ host?: string;
8
+ timeoutMs?: number;
9
+ fetch?: typeof fetch;
10
+ }
11
+ export type PostEvent = Omit<EventInput, 'ts' | 'level'> & {
12
+ ts?: string;
13
+ level?: Level;
14
+ };
15
+ export interface PostResult {
16
+ accepted: number;
17
+ rejected: number;
18
+ }
19
+ export declare const batchesOf: (events: Event[]) => Event[][];
20
+ export declare const createEventsClient: (o: EventsClientOptions) => {
21
+ post: (events: PostEvent[]) => Promise<PostResult>;
22
+ };
@@ -0,0 +1,74 @@
1
+ import { hostname } from 'node:os';
2
+ import { EventSchema } from './event.schema.js';
3
+ import { redact } from './redact.js';
4
+ import { uuidv7 } from './uuidv7.js';
5
+ export const MAX_BATCH_BYTES = 900_000;
6
+ export const MAX_BATCH_ITEMS = 1000;
7
+ const complete = (event, host) => {
8
+ const filled = { ts: new Date().toISOString(), level: 'info', agcid: uuidv7(), host, ...event };
9
+ return EventSchema.parse({ ...filled, fields: redact(event.fields ?? {}) });
10
+ };
11
+ const sizeOf = (event) => Buffer.byteLength(JSON.stringify(event)) + 1;
12
+ // A row alone over the batch limit would be a 413: it is dropped with a warning instead.
13
+ const fitting = (event) => {
14
+ if (sizeOf(event) + 2 <= MAX_BATCH_BYTES)
15
+ return true;
16
+ process.emitWarning(`@agentage/logs: dropped a ${event.kind} row over 900 KB`);
17
+ return false;
18
+ };
19
+ // Each batch under 1 MB and at most 1000 rows (the ingest wire, C3).
20
+ export const batchesOf = (events) => {
21
+ const batches = [];
22
+ let batch = [];
23
+ let bytes = 2;
24
+ for (const event of events) {
25
+ const size = sizeOf(event);
26
+ if (batch.length > 0 && (bytes + size > MAX_BATCH_BYTES || batch.length >= MAX_BATCH_ITEMS)) {
27
+ batches.push(batch);
28
+ [batch, bytes] = [[], 2];
29
+ }
30
+ batch.push(event);
31
+ bytes += size;
32
+ }
33
+ return batch.length > 0 ? [...batches, batch] : batches;
34
+ };
35
+ class IngestError extends Error {
36
+ status;
37
+ constructor(status) {
38
+ super(`POST /api/v1/events answered ${status}`);
39
+ this.status = status;
40
+ }
41
+ }
42
+ // A network error, 429 or 5xx is tried once more; a 4xx would fail the same way again.
43
+ const retries = (err) => !(err instanceof IngestError) || err.status === 429 || err.status >= 500;
44
+ const sendOnce = async (o, body) => {
45
+ const res = await (o.fetch ?? fetch)(`${o.url.replace(/\/+$/, '')}/api/v1/events`, {
46
+ method: 'POST',
47
+ headers: { authorization: `Bearer ${o.token}`, 'content-type': 'application/json' },
48
+ body,
49
+ signal: AbortSignal.timeout(o.timeoutMs ?? 5000),
50
+ });
51
+ if (!res.ok)
52
+ throw new IngestError(res.status);
53
+ const reply = (await res.json());
54
+ return reply.data ?? { accepted: 0, rejected: 0 };
55
+ };
56
+ const send = (o, body) => sendOnce(o, body).catch((err) => {
57
+ if (!retries(err))
58
+ throw err;
59
+ return sendOnce(o, body);
60
+ });
61
+ // Posts rows to the ingest; a refused or unreachable ingest rejects: the caller catches.
62
+ export const createEventsClient = (o) => ({
63
+ post: async (events) => {
64
+ const host = o.host ?? hostname();
65
+ const total = { accepted: 0, rejected: 0 };
66
+ const rows = events.map((event) => complete(event, host)).filter(fitting);
67
+ for (const batch of batchesOf(rows)) {
68
+ const result = await send(o, JSON.stringify(batch));
69
+ total.accepted += result.accepted;
70
+ total.rejected += result.rejected;
71
+ }
72
+ return total;
73
+ },
74
+ });
@@ -0,0 +1,5 @@
1
+ export { AGCID_HEX, EventSchema, KINDS, LEVELS, USER_TYPES, type Event, type EventInput, type Fields, type Kind, type Level, type UserType, } from './event.schema.js';
2
+ export { parseLine, type LineSource } from './parse-line.js';
3
+ export { createLogger, type Logger, type LoggerOptions, type RowContext } from './logger.js';
4
+ export { type HttpRow, type JobRow, type McpRow, type Row } from './rows.js';
5
+ export { createEventsClient, type EventsClientOptions, type PostEvent, type PostResult, } from './events-client.js';
@@ -0,0 +1,5 @@
1
+ export { AGCID_HEX, EventSchema, KINDS, LEVELS, USER_TYPES, } from './event.schema.js';
2
+ export { parseLine } from './parse-line.js';
3
+ export { createLogger } from './logger.js';
4
+ export {} from './rows.js';
5
+ export { createEventsClient, } from './events-client.js';
@@ -0,0 +1,31 @@
1
+ import { type Fields, type UserType } from './event.schema.js';
2
+ import { type HttpRow, type JobRow, type McpRow, type Row } from './rows.js';
3
+ export interface RowContext {
4
+ agcid?: string | null;
5
+ sub?: string | null;
6
+ session?: string | null;
7
+ user_type?: UserType;
8
+ client?: string | null;
9
+ }
10
+ export interface Logger {
11
+ info(msg: string, fields?: Fields): void;
12
+ warn(msg: string, fields?: Fields): void;
13
+ error(err: unknown, where?: string | Fields): void;
14
+ http(o: HttpRow): void;
15
+ mcp(o: McpRow): void;
16
+ job(o: JobRow): void;
17
+ span<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
18
+ event(name: string, fields?: Fields, msg?: string): void;
19
+ row(row: Row): void;
20
+ }
21
+ export interface LoggerOptions {
22
+ extension: string;
23
+ part: string;
24
+ version?: string;
25
+ host?: string;
26
+ context?: () => RowContext | undefined;
27
+ write?: (line: string) => void;
28
+ sink?: (row: Row) => void;
29
+ base?: Fields;
30
+ }
31
+ export declare const createLogger: (o: LoggerOptions) => Logger;