@agentage/extension 0.12.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.
@@ -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 { uuidv7 };
3
4
  export declare const agcidOf: (incoming: unknown, traceparent?: unknown) => string;
@@ -1,16 +1,8 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { uuidv7 } from '../vendor/logs/index.js';
2
2
  import { TRACEPARENT_PATTERN } from './current.js';
3
3
  import { isAgcid } from './header.js';
4
4
  export { AGCID_HEADER, AGCID_PATTERN, isAgcid } from './header.js';
5
- // RFC 9562 UUIDv7 as 32 lowercase hex, a valid W3C trace id: 48-bit ms, version 7, variant 10.
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 bytes.toString('hex');
13
- };
5
+ export { uuidv7 };
14
6
  const DASHED = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
15
7
  const ZERO = '0'.repeat(32);
16
8
  // 32 hex, or a UUID in its 8-4-4-4-12 form without the dashes; all zeros is no id (W3C).
@@ -7,6 +7,6 @@ interface RequestScope extends RowContext {
7
7
  }
8
8
  export declare const requestScope: AsyncLocalStorage<RequestScope>;
9
9
  export declare const currentAgcid: () => string | undefined;
10
- export declare const currentContext: () => RowContext | undefined;
10
+ export declare const sigtermOnce: () => void;
11
11
  export declare const TRACEPARENT_PATTERN: RegExp;
12
12
  export {};
@@ -3,5 +3,12 @@ import {} from '../vendor/logs/index.js';
3
3
  // Apart from the middleware, so code the cli loads (logs, the build tool) never imports express.
4
4
  export const requestScope = new AsyncLocalStorage();
5
5
  export const currentAgcid = () => requestScope.getStore()?.agcid;
6
- export const currentContext = () => requestScope.getStore();
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
+ };
7
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,4 +1,4 @@
1
- import { requestScope } from '../agcid/current.js';
1
+ import { requestScope, sigtermOnce } from '../agcid/current.js';
2
2
  import { callerOf } from '../auth/token-check.js';
3
3
  import {} from '../manifest/manifest.schema.js';
4
4
  import { storeOf } from '../manifest/parts.js';
@@ -20,7 +20,7 @@ const exitAfterAnswer = () => {
20
20
  if (scope)
21
21
  scope.exit = true;
22
22
  else
23
- process.kill(process.pid, 'SIGTERM');
23
+ sigtermOnce();
24
24
  };
25
25
  // ctx.store is always there; without a store part in the manifest it says so on first use.
26
26
  export const NO_STORE = {
@@ -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
  }
@@ -3,7 +3,7 @@ import { messageOf } from '../log/log.js';
3
3
  // The test context's log: every row as an entry; error keeps the thrown value under err.
4
4
  export const recordingLog = (logs) => {
5
5
  const sink = ({ level, msg, fields }) => void logs.push({ level, message: msg, fields });
6
- const log = createLogger({ extension: 'test', part: 'test', sink });
6
+ const log = createLogger({ extension: 'test', part: 'test', sink, strict: true });
7
7
  const error = (err, where = {}) => {
8
8
  const fields = typeof where === 'string' ? { 'agentage.where': where } : where;
9
9
  logs.push({ level: 'error', message: messageOf(err), fields: { ...fields, err } });
@@ -57,7 +57,7 @@ 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([]));
@@ -16,7 +16,9 @@ const settle = async (check) => {
16
16
  timer = setTimeout(() => resolve('unavailable'), CHECK_TIMEOUT_MS).unref();
17
17
  });
18
18
  try {
19
- 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';
20
22
  }
21
23
  catch {
22
24
  return 'unavailable';
package/dist/log/log.d.ts CHANGED
@@ -1,13 +1,5 @@
1
- import { type Fields, type Level, type Logger } from '../vendor/logs/index.js';
2
- export type LogLevel = Level;
1
+ import { type Fields, type Logger, type LoggerOptions } from '../vendor/logs/index.js';
3
2
  export type LogFields = Fields;
4
3
  export type Log = Logger;
5
- export interface LogTags {
6
- extension: string;
7
- part: string;
8
- version?: string;
9
- base?: LogFields;
10
- }
11
- export type LogWrite = (line: string) => void;
12
4
  export declare const messageOf: (error: unknown) => string;
13
- export declare const createLog: (tags: LogTags, write?: LogWrite) => Log;
5
+ export declare const createLog: (tags: Pick<LoggerOptions, "extension" | "part" | "version" | "base">, write?: LoggerOptions["write"]) => Log;
package/dist/log/log.js CHANGED
@@ -1,4 +1,12 @@
1
1
  import { createLogger } from '../vendor/logs/index.js';
2
- import { currentContext } from '../agcid/current.js';
3
- export const messageOf = (error) => error instanceof Error ? error.message : String(error);
4
- export const createLog = (tags, write) => createLogger({ ...tags, context: currentContext, ...(write ? { write } : {}) });
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/who.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type UserType } from '../vendor/logs/index.js';
2
2
  type Header = (name: string) => string | undefined;
3
+ export declare const printable: (text: string | undefined) => string;
3
4
  export declare const declaredType: (header: Header) => UserType | undefined;
4
5
  export declare const clientOf: (header: Header) => string | null;
5
6
  export declare const userTypeOf: (header: Header, path: string) => UserType;
package/dist/log/who.js CHANGED
@@ -14,12 +14,14 @@ const AI = ['claude-code', 'cursor', 'chatgpt'];
14
14
  const BOT = /bot|crawl|spider|slurp|scan|nikto|zgrab|masscan/i;
15
15
  const BOT_PATH = /\.(php|asp|aspx|env)$|^\/wp-|^\/\.git/i;
16
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, '');
17
19
  export const declaredType = (header) => {
18
20
  const declared = header('x-client-type');
19
21
  return declared && DECLARED.includes(declared) ? declared : undefined;
20
22
  };
21
23
  export const clientOf = (header) => {
22
- const named = header('x-client')?.trim().toLowerCase().slice(0, 64);
24
+ const named = printable(header('x-client')).trim().toLowerCase().slice(0, 64);
23
25
  if (named)
24
26
  return named;
25
27
  const agent = header('user-agent') ?? '';
@@ -41,6 +43,6 @@ export const userTypeOf = (header, path) => {
41
43
  export const whoOf = (header, path) => ({
42
44
  user_type: userTypeOf(header, path),
43
45
  client: clientOf(header),
44
- session: header('agsid')?.slice(0, 128) ?? null,
46
+ session: printable(header('agsid')).slice(0, 128) || null,
45
47
  sub: null,
46
48
  });
@@ -6,7 +6,7 @@ import { createMcpHandler } from '@modelcontextprotocol/server';
6
6
  import { requestScope } from '../agcid/current.js';
7
7
  import { setCaller, strongest } from '../auth/token-check.js';
8
8
  import { fail } from '../envelope/envelope.js';
9
- import { declaredType } from '../log/who.js';
9
+ import { declaredType, printable } from '../log/who.js';
10
10
  import { BODY_LIMIT, createPartApp, PUBLIC_CORS } from '../server/app.js';
11
11
  import { serverFactory } from './server.js';
12
12
  import { prefixed } from './tools.js';
@@ -63,7 +63,7 @@ const markRow = (options, req, res, body) => {
63
63
  }
64
64
  const name = messages.find((m) => m?.method === 'initialize')?.params?.clientInfo?.name;
65
65
  if (typeof name === 'string')
66
- res.locals['clientInfo'] = name.slice(0, 64);
66
+ res.locals['clientInfo'] = printable(name).slice(0, 64);
67
67
  };
68
68
  const webRequest = (req, body) => {
69
69
  const headers = new Headers();
@@ -1,5 +1,5 @@
1
1
  import {} from 'express';
2
- import { requestScope } from '../agcid/current.js';
2
+ import { requestScope, sigtermOnce } from '../agcid/current.js';
3
3
  import {} from '../log/log.js';
4
4
  const MOUNTS = ['/api/v1', '/mcp', '/.well-known', '/ui'];
5
5
  const ASSET = /\.(m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf)$/i;
@@ -38,7 +38,7 @@ export const requestLine = (log) => (req, res, next) => {
38
38
  clientInfo: localOf(res, 'clientInfo'),
39
39
  });
40
40
  if (scope?.exit)
41
- process.kill(process.pid, 'SIGTERM');
41
+ sigtermOnce();
42
42
  });
43
43
  next();
44
44
  };
@@ -7,18 +7,30 @@ export const listen = (app, port, host) => new Promise((resolve, reject) => {
7
7
  const done = (err) => (err ? reject(err) : resolve(server));
8
8
  const server = host === undefined ? app.listen(port, done) : app.listen(port, host, done);
9
9
  });
10
- // SIGTERM drains: no new connections, idle ones closed, a hard exit after the grace period.
10
+ // SIGTERM drains; a close error or a drain past the grace period exits 1; a second Ctrl-C at once.
11
11
  export const shutdownOn = (server, options) => {
12
- const exit = options.exit ?? ((code) => process.exit(code));
13
- const stop = () => {
12
+ const exitWith = options.exit ?? ((code) => process.exit(code));
13
+ let [stopping, exited] = [false, false];
14
+ const exit = (code) => {
15
+ if (exited)
16
+ return;
17
+ exited = true;
18
+ exitWith(code);
19
+ };
20
+ const stop = (signal) => {
21
+ if (stopping && signal === 'SIGINT')
22
+ exit(130);
23
+ if (stopping)
24
+ return;
25
+ stopping = true;
14
26
  options.log.info('shutting down');
15
- server.close(() => exit(0));
27
+ server.close((err) => exit(err ? 1 : 0));
16
28
  server.closeIdleConnections();
17
- setTimeout(() => exit(0), GRACE_MS).unref();
29
+ setTimeout(() => exit(1), GRACE_MS).unref();
18
30
  };
19
31
  for (const signal of options.signals ?? ['SIGTERM', 'SIGINT'])
20
- process.once(signal, stop);
21
- return stop;
32
+ process.on(signal, () => stop(signal));
33
+ return () => stop();
22
34
  };
23
35
  export const serve = async (options) => {
24
36
  const server = await listen(options.app, options.port);
@@ -2,7 +2,6 @@ import { z } from 'zod';
2
2
  export declare const KINDS: readonly ["http", "mcp", "job", "span", "error", "event", "log"];
3
3
  export declare const LEVELS: readonly ["info", "warn", "error"];
4
4
  export declare const USER_TYPES: readonly ["user", "agent", "automation", "service", "test", "bot"];
5
- export declare const AGCID_HEX: RegExp;
6
5
  export type Kind = (typeof KINDS)[number];
7
6
  export type Level = (typeof LEVELS)[number];
8
7
  export type UserType = (typeof USER_TYPES)[number];
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  export const KINDS = ['http', 'mcp', 'job', 'span', 'error', 'event', 'log'];
3
3
  export const LEVELS = ['info', 'warn', 'error'];
4
4
  export const USER_TYPES = ['user', 'agent', 'automation', 'service', 'test', 'bot'];
5
- export const AGCID_HEX = /^[0-9a-f]{32}$/;
5
+ const AGCID_HEX = /^[0-9a-f]{32}$/;
6
6
  const name = z.string().min(1).max(64);
7
7
  const id = z.string().max(128).nullable().default(null);
8
8
  // The line (logs-events section 1): snake_case on the wire; host is set by the shipper or the client.
@@ -1,11 +1,11 @@
1
1
  import { type Event, type EventInput, type Level } from './event.schema.js';
2
- export declare const MAX_BATCH_BYTES = 900000;
3
2
  export declare const MAX_BATCH_ITEMS = 1000;
4
3
  export interface EventsClientOptions {
5
4
  url: string;
6
5
  token: string;
7
6
  host?: string;
8
7
  timeoutMs?: number;
8
+ retryDelayMs?: number;
9
9
  fetch?: typeof fetch;
10
10
  }
11
11
  export type PostEvent = Omit<EventInput, 'ts' | 'level'> & {
@@ -1,16 +1,24 @@
1
1
  import { hostname } from 'node:os';
2
2
  import { EventSchema } from './event.schema.js';
3
- import { redact } from './redact.js';
3
+ import { redact, scrub } from './redact.js';
4
4
  import { uuidv7 } from './uuidv7.js';
5
- export const MAX_BATCH_BYTES = 900_000;
5
+ const MAX_BATCH_BYTES = 900_000;
6
6
  export const MAX_BATCH_ITEMS = 1000;
7
+ // A row the schema refuses is dropped with a warning and counted as rejected; the rest still go.
7
8
  const complete = (event, host) => {
8
9
  const filled = { ts: new Date().toISOString(), level: 'info', agcid: uuidv7(), host, ...event };
9
- return EventSchema.parse({ ...filled, fields: redact(event.fields ?? {}) });
10
+ const msg = typeof event.msg === 'string' ? scrub(event.msg) : event.msg;
11
+ const parsed = EventSchema.safeParse({ ...filled, msg, fields: redact(event.fields ?? {}) });
12
+ if (parsed.success)
13
+ return parsed.data;
14
+ process.emitWarning(`@agentage/logs: dropped an invalid row (${parsed.error.issues[0]?.path.join('.')})`);
15
+ return null;
10
16
  };
11
17
  const sizeOf = (event) => Buffer.byteLength(JSON.stringify(event)) + 1;
12
18
  // A row alone over the batch limit would be a 413: it is dropped with a warning instead.
13
19
  const fitting = (event) => {
20
+ if (event === null)
21
+ return false;
14
22
  if (sizeOf(event) + 2 <= MAX_BATCH_BYTES)
15
23
  return true;
16
24
  process.emitWarning(`@agentage/logs: dropped a ${event.kind} row over 900 KB`);
@@ -50,25 +58,31 @@ const sendOnce = async (o, body) => {
50
58
  });
51
59
  if (!res.ok)
52
60
  throw new IngestError(res.status);
53
- const reply = (await res.json());
61
+ // A 2xx was taken: an unreadable answer is never retried, it would post the rows twice.
62
+ const reply = (await res.json().catch(() => ({})));
54
63
  return reply.data ?? { accepted: 0, rejected: 0 };
55
64
  };
56
- const send = (o, body) => sendOnce(o, body).catch((err) => {
65
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
66
+ const send = (o, body) => sendOnce(o, body).catch(async (err) => {
57
67
  if (!retries(err))
58
68
  throw err;
69
+ await pause(o.retryDelayMs ?? 1000);
59
70
  return sendOnce(o, body);
60
71
  });
72
+ const post = async (o, events) => {
73
+ if (!o.url || !o.token)
74
+ throw new Error('@agentage/logs: the events client needs a url and a token');
75
+ const host = o.host ?? hostname();
76
+ const rows = events.map((event) => complete(event, host)).filter(fitting);
77
+ const total = { accepted: 0, rejected: events.length - rows.length };
78
+ for (const batch of batchesOf(rows)) {
79
+ const result = await send(o, JSON.stringify(batch));
80
+ total.accepted += result.accepted;
81
+ total.rejected += result.rejected;
82
+ }
83
+ return total;
84
+ };
61
85
  // Posts rows to the ingest; a refused or unreachable ingest rejects: the caller catches.
62
86
  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
- },
87
+ post: (events) => post(o, events),
74
88
  });
@@ -1,5 +1,6 @@
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';
1
+ export { EventSchema, KINDS, LEVELS, USER_TYPES, type Event, type EventInput, type Fields, type Kind, type Level, type UserType, } from './event.schema.js';
2
2
  export { parseLine, type LineSource } from './parse-line.js';
3
+ export { uuidv7 } from './uuidv7.js';
3
4
  export { createLogger, type Logger, type LoggerOptions, type RowContext } from './logger.js';
4
5
  export { type HttpRow, type JobRow, type McpRow, type Row } from './rows.js';
5
6
  export { createEventsClient, type EventsClientOptions, type PostEvent, type PostResult, } from './events-client.js';
@@ -1,5 +1,6 @@
1
- export { AGCID_HEX, EventSchema, KINDS, LEVELS, USER_TYPES, } from './event.schema.js';
1
+ export { EventSchema, KINDS, LEVELS, USER_TYPES, } from './event.schema.js';
2
2
  export { parseLine } from './parse-line.js';
3
+ export { uuidv7 } from './uuidv7.js';
3
4
  export { createLogger } from './logger.js';
4
5
  export {} from './rows.js';
5
6
  export { createEventsClient, } from './events-client.js';
@@ -27,5 +27,7 @@ export interface LoggerOptions {
27
27
  write?: (line: string) => void;
28
28
  sink?: (row: Row) => void;
29
29
  base?: Fields;
30
+ strict?: boolean;
30
31
  }
32
+ export declare const MAX_LINE_BYTES: number;
31
33
  export declare const createLogger: (o: LoggerOptions) => Logger;
@@ -1,7 +1,6 @@
1
1
  import {} from './event.schema.js';
2
- import { errorRow } from './error-row.js';
3
- import { MAX_STRING, redact } from './redact.js';
4
- import { eventRow, httpRow, jobRow, mcpRow, spanRow, } from './rows.js';
2
+ import { redact, scrub, stringOf } from './redact.js';
3
+ import { errorRow, eventRow, httpRow, jobRow, mcpRow, spanRow, } from './rows.js';
5
4
  const timed = async (fn, end) => {
6
5
  const start = performance.now();
7
6
  const ms = () => Math.round(performance.now() - start);
@@ -15,42 +14,70 @@ const timed = async (fn, end) => {
15
14
  throw err;
16
15
  }
17
16
  };
18
- // Every method is a row; row is the one sink, so a wrapper replaces only it.
19
- const loggerOf = (row) => ({
20
- info: (msg, fields = {}) => row({ kind: 'log', level: 'info', msg, fields }),
21
- warn: (msg, fields = {}) => row({ kind: 'log', level: 'warn', msg, fields }),
22
- error: (err, where) => row(errorRow(err, where)),
23
- http: (o) => {
24
- const r = httpRow(o);
17
+ // Builds and writes a row; outside a strict log, a failed row is dropped, never thrown at the caller.
18
+ const guarded = (row, strict) => (build) => {
19
+ try {
20
+ const r = build();
25
21
  if (r)
26
22
  row(r);
27
- },
28
- mcp: (o) => row(mcpRow(o)),
29
- job: (o) => row(jobRow(o)),
30
- span: (name, fn) => timed(fn, (ms, err) => row(spanRow(name, ms, err))),
31
- event: (name, fields = {}, msg) => row(eventRow(name, fields, msg)),
32
- row,
33
- });
34
- const lineOf = (o, r) => {
23
+ }
24
+ catch (err) {
25
+ if (strict)
26
+ throw err;
27
+ }
28
+ };
29
+ // Every method is a row; row is the one sink, so a wrapper replaces only it.
30
+ const loggerOf = (row, strict = false) => {
31
+ const emit = guarded(row, strict);
32
+ return {
33
+ info: (msg, fields = {}) => emit(() => ({ kind: 'log', level: 'info', msg, fields })),
34
+ warn: (msg, fields = {}) => emit(() => ({ kind: 'log', level: 'warn', msg, fields })),
35
+ error: (err, where) => emit(() => errorRow(err, where)),
36
+ http: (o) => emit(() => httpRow(o)),
37
+ mcp: (o) => emit(() => mcpRow(o)),
38
+ job: (o) => emit(() => jobRow(o)),
39
+ span: (name, fn) => timed(fn, (ms, err) => emit(() => spanRow(name, ms, err))),
40
+ event: (name, fields = {}, msg) => emit(() => eventRow(name, fields, msg)),
41
+ row: (r) => emit(() => r),
42
+ };
43
+ };
44
+ const CONTROL = /[\u0000-\u001f\u007f]/g;
45
+ // A line over this is written without its fields: a shipper splits longer lines.
46
+ export const MAX_LINE_BYTES = 64 * 1024;
47
+ const text = (value, max) => value == null ? null : scrub(stringOf(value).replace(CONTROL, ''), max) || null;
48
+ // The columns the kit sets from request headers and tokens, bounded as the schema bounds them.
49
+ const columnsOf = (o, r) => {
35
50
  const c = o.context?.() ?? {};
36
- const event = {
37
- ts: new Date().toISOString(),
38
- level: r.level,
39
- kind: r.kind,
40
- msg: r.msg.slice(0, MAX_STRING),
41
- extension: o.extension,
42
- part: o.part,
43
- version: o.version ?? '',
51
+ const { extension, part, version = '' } = o;
52
+ const [level, kind, msg] = [r.level, r.kind, scrub(r.msg)];
53
+ return {
54
+ ...{ ts: new Date().toISOString(), level, kind, msg, extension, part, version },
44
55
  ...(o.host ? { host: o.host } : {}),
45
56
  agcid: c.agcid ?? null,
46
- sub: c.sub ?? null,
47
- session: c.session ?? null,
57
+ sub: text(c.sub, 128),
58
+ session: text(c.session, 128),
48
59
  user_type: c.user_type ?? 'service',
49
- client: c.client ?? null,
50
- fields: redact({ ...o.base, ...r.fields }),
60
+ client: text(c.client, 64),
51
61
  };
52
- return `${JSON.stringify(event)}\n`;
53
62
  };
54
- const stderr = (line) => void process.stderr.write(line);
63
+ const lineOf = (o, r) => {
64
+ const columns = columnsOf(o, r);
65
+ const line = JSON.stringify({
66
+ ...columns,
67
+ fields: { ...redact(o.base ?? {}), ...redact(r.fields) },
68
+ });
69
+ if (Buffer.byteLength(line) <= MAX_LINE_BYTES)
70
+ return `${line}\n`;
71
+ return `${JSON.stringify({ ...columns, fields: { 'agentage.dropped': 'fields over 64 KB' } })}\n`;
72
+ };
73
+ let quiet = false;
74
+ // A closed stderr (EPIPE) emits an error event; with no listener that would crash the part.
75
+ const stderr = (line) => {
76
+ if (!quiet) {
77
+ process.stderr.on('error', () => undefined);
78
+ quiet = true;
79
+ }
80
+ process.stderr.write(line);
81
+ };
55
82
  // One JSON line per unit of work on stderr; the host ships it.
56
- export const createLogger = (o) => loggerOf(o.sink ?? ((r) => (o.write ?? stderr)(lineOf(o, r))));
83
+ export const createLogger = (o) => loggerOf(o.sink ?? ((r) => (o.write ?? stderr)(lineOf(o, r))), o.strict);
@@ -1,5 +1,5 @@
1
1
  import { EventSchema } from './event.schema.js';
2
- import { MAX_STRING, redact } from './redact.js';
2
+ import { cut, redact, scrub } from './redact.js';
3
3
  const RAW_ERROR = /\b(ERROR|FATAL)\b/;
4
4
  const jsonOf = (text) => {
5
5
  try {
@@ -10,20 +10,21 @@ const jsonOf = (text) => {
10
10
  }
11
11
  };
12
12
  const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
13
- // A line that is not a valid event is a raw log row; a JSON object keeps its keys, redacted.
13
+ const nameOf = (value) => cut(value ?? '', 64) || 'unknown';
14
+ // Not a valid event: a raw log row, a JSON object keeping its keys; both redacted as the logger does.
14
15
  export const parseLine = (text, source = {}) => {
15
16
  const line = text.trim();
16
17
  const json = jsonOf(line);
17
18
  const parsed = EventSchema.safeParse(json);
18
19
  if (parsed.success)
19
- return parsed.data;
20
+ return { ...parsed.data, msg: scrub(parsed.data.msg), fields: redact(parsed.data.fields) };
20
21
  return EventSchema.parse({
21
22
  ts: new Date().toISOString(),
22
23
  level: RAW_ERROR.test(line) ? 'error' : 'info',
23
24
  kind: 'log',
24
- msg: line.slice(0, MAX_STRING),
25
- extension: source.extension ?? 'unknown',
26
- part: source.part ?? 'unknown',
25
+ msg: scrub(line),
26
+ extension: nameOf(source.extension),
27
+ part: nameOf(source.part),
27
28
  fields: { ...(isObject(json) ? redact(json) : {}), 'agentage.raw': true },
28
29
  });
29
30
  };
@@ -1,3 +1,7 @@
1
1
  import { type Fields } from './event.schema.js';
2
2
  export declare const MAX_STRING = 200;
3
+ export declare const cut: (text: string, max: number) => string;
4
+ export declare const stringOf: (value: unknown) => string;
5
+ export declare const scrub: (text: unknown, max?: number) => string;
6
+ export declare const read: (value: object, key: string) => unknown;
3
7
  export declare const redact: (fields: Fields) => Fields;
@@ -1,19 +1,47 @@
1
1
  import {} from './event.schema.js';
2
2
  const SECRET = /token|secret|password|key|authorization|cookie/i;
3
+ // A JWT (three parts, or a token-length first part a cut left), an aga_ PAT, a Bearer credential.
4
+ const JWT = String.raw `(?<![\w-])eyJ(?:[\w-]{8,}\.[\w-]+\.[\w-]*|[\w-]{17,}(?:\.[\w-]*)?)`;
5
+ const PAT = String.raw `(?<![\w-])aga_[\w.-]{16,}`;
6
+ // An opaque Bearer value is mixed case with a digit, or 32 characters and more.
7
+ const OPAQUE = String.raw `(?=[\w.~+/=-]*\d)(?=[\w.~+/=-]*[A-Z])[\w.~+/=-]{16,}|[\w.~+/=-]{32,}`;
8
+ const BEARER = String.raw `\b[Bb]earer\s+(?:${OPAQUE})`;
9
+ const CREDENTIAL = new RegExp(`${JWT}|${PAT}|${BEARER}`, 'g');
3
10
  export const MAX_STRING = 200;
4
11
  const MAX_STACK = 2000;
5
12
  const MAX_DEPTH = 3;
6
- const cut = (text, max) => (text.length > max ? text.slice(0, max) : text);
13
+ // On a code point boundary: a cut never leaves half a surrogate pair.
14
+ export const cut = (text, max) => text.length > max ? text.slice(0, max).replace(/[\uD800-\uDBFF]$/, '') : text;
15
+ export const stringOf = (value) => {
16
+ try {
17
+ return typeof value === 'string' ? value : String(value);
18
+ }
19
+ catch {
20
+ return '[unprintable]';
21
+ }
22
+ };
23
+ // Masked before the cut, so the cut never leaves a credential shape half-matched.
24
+ export const scrub = (text, max = MAX_STRING) => cut(stringOf(text).replace(CREDENTIAL, '[redacted]'), max);
25
+ export const read = (value, key) => {
26
+ try {
27
+ return Reflect.get(value, key);
28
+ }
29
+ catch {
30
+ return '[unreadable]';
31
+ }
32
+ };
7
33
  const clean = (value, depth) => {
8
34
  if (typeof value === 'string')
9
- return cut(value, MAX_STRING);
35
+ return scrub(value);
36
+ if (typeof value === 'bigint')
37
+ return value.toString();
10
38
  if (value === null || typeof value !== 'object')
11
39
  return value;
12
40
  if (depth >= MAX_DEPTH)
13
41
  return '[depth]';
14
42
  if (Array.isArray(value))
15
43
  return value.map((item) => clean(item, depth + 1));
16
- const entries = Object.entries(value).map(([k, v]) => [k, keyed(k, v, depth + 1)]);
44
+ const entries = Object.keys(value).map((k) => [k, keyed(k, read(value, k), depth + 1)]);
17
45
  return Object.fromEntries(entries);
18
46
  };
19
47
  // A stack keeps more than 200 characters: the first in-app frame is rarely in the first line.
@@ -21,7 +49,15 @@ const keyed = (key, value, depth) => {
21
49
  if (SECRET.test(key))
22
50
  return '[redacted]';
23
51
  if (key === 'exception.stacktrace' && typeof value === 'string')
24
- return cut(value, MAX_STACK);
52
+ return scrub(value, MAX_STACK);
25
53
  return clean(value, depth);
26
54
  };
27
- export const redact = (fields) => clean(fields, 0);
55
+ // Never throws: a getter that throws reads [unreadable], a bigint its digits, a proxy that throws empty.
56
+ export const redact = (fields) => {
57
+ try {
58
+ return clean(fields, 0);
59
+ }
60
+ catch {
61
+ return { 'agentage.unreadable': true };
62
+ }
63
+ };
@@ -26,9 +26,9 @@ export interface JobRow {
26
26
  ms: number;
27
27
  error?: unknown;
28
28
  }
29
- export declare const typeOf: (err: unknown) => string;
30
29
  export declare const httpRow: (o: HttpRow) => Row | null;
31
30
  export declare const mcpRow: (o: McpRow) => Row;
32
31
  export declare const jobRow: (o: JobRow) => Row;
33
32
  export declare const spanRow: (name: string, ms: number, error?: unknown) => Row;
34
33
  export declare const eventRow: (name: string, fields: Fields, msg?: string) => Row;
34
+ export declare const errorRow: (err: unknown, where?: string | Fields) => Row;
@@ -1,13 +1,14 @@
1
1
  import {} from './event.schema.js';
2
+ import { cut, MAX_STRING, read, stringOf } from './redact.js';
2
3
  const HEALTH = /^\/(health|healthz|livez|readyz)$/;
3
- export const typeOf = (err) => (err instanceof Error ? err.name : 'Error');
4
+ const typeOf = (err) => (err instanceof Error ? err.name : 'Error');
4
5
  const failed = (err) => (err === undefined ? {} : { 'error.type': typeOf(err) });
5
6
  const httpLevel = (status, ms) => status >= 500 ? 'error' : status >= 400 || ms > 1000 ? 'warn' : 'info';
6
7
  // Health probes leave no row (logs-events Q2).
7
8
  export const httpRow = (o) => {
8
9
  if (HEALTH.test(o.route))
9
10
  return null;
10
- const route = o.route.slice(0, 200);
11
+ const route = cut(o.route, MAX_STRING);
11
12
  const fields = {
12
13
  'http.request.method': o.method,
13
14
  'http.route': route,
@@ -55,3 +56,13 @@ export const eventRow = (name, fields, msg = name) => ({
55
56
  msg,
56
57
  fields: { 'event.name': name, ...fields },
57
58
  });
59
+ // where: the route, tool or job; an author's agentage.fingerprint passes through (Q11 A).
60
+ export const errorRow = (err, where) => {
61
+ const own = typeof where === 'string' ? { 'agentage.where': where } : (where ?? {});
62
+ const error = err instanceof Error;
63
+ const text = (key) => stringOf(read(err, key) ?? '');
64
+ const [type, message] = error ? [text('name'), text('message')] : ['Error', stringOf(err)];
65
+ const stack = error ? { 'exception.stacktrace': text('stack') } : {};
66
+ const fields = { 'exception.type': type, 'exception.message': message, ...stack, ...own };
67
+ return { kind: 'error', level: 'error', msg: `${type}: ${message}`, fields };
68
+ };
@@ -6,4 +6,4 @@ export interface RunBuffer {
6
6
  }
7
7
  export declare const withRunBuffer: <T>(buffer: RunBuffer, fn: () => Promise<T>) => Promise<T>;
8
8
  export declare const append: (buffer: RunBuffer, line: string) => void;
9
- export declare const runLog: (base: Log) => Log;
9
+ export declare const runLog: (base: Log, strict?: boolean) => Log;
@@ -23,10 +23,11 @@ const record = (level, message) => {
23
23
  append(buffer, `${level} ${message}`);
24
24
  };
25
25
  // ctx.log for a worker: the usual JSON line, and inside a run also the run's own log.
26
- export const runLog = (base) => ({
26
+ export const runLog = (base, strict = false) => ({
27
27
  ...createLogger({
28
28
  extension: 'worker',
29
29
  part: 'worker',
30
+ strict,
30
31
  sink: (row) => {
31
32
  record(row.level, row.msg);
32
33
  base.row(row);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.12.1",
3
+ "version": "0.12.2",
4
4
  "description": "The agentage extension kit: create(ctx) per part (pages, ui, api, mcp, worker, cli), the store, /health, discovery, the envelope, and the build tool with up and token",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,3 +0,0 @@
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;
@@ -1,16 +0,0 @@
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
- };