@agentage/extension 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  interface RequestScope {
3
3
  agcid: string;
4
+ traceparent?: string;
4
5
  }
5
6
  export declare const requestScope: AsyncLocalStorage<RequestScope>;
6
7
  export declare const currentAgcid: () => string | undefined;
8
+ export declare const TRACEPARENT_PATTERN: RegExp;
7
9
  export {};
@@ -2,3 +2,4 @@ import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  // Apart from the middleware, so code the cli loads (logs, the build tool) never imports express.
3
3
  export const requestScope = new AsyncLocalStorage();
4
4
  export const currentAgcid = () => requestScope.getStore()?.agcid;
5
+ export const TRACEPARENT_PATTERN = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
@@ -0,0 +1 @@
1
+ export declare const kitFetch: (url: string, init?: RequestInit, impl?: typeof fetch) => Promise<Response>;
@@ -0,0 +1,11 @@
1
+ import { AGCID_HEADER, uuidv7 } from './agcid.js';
2
+ import { requestScope } from './current.js';
3
+ // Every fetch the kit makes: the scope's agcid (a fresh one outside a scope) and its traceparent.
4
+ export const kitFetch = (url, init = {}, impl = fetch) => {
5
+ const scope = requestScope.getStore();
6
+ const headers = new Headers(init.headers);
7
+ headers.set(AGCID_HEADER, scope?.agcid ?? uuidv7());
8
+ if (scope?.traceparent)
9
+ headers.set('traceparent', scope.traceparent);
10
+ return impl(url, { ...init, headers });
11
+ };
@@ -1,12 +1,14 @@
1
1
  import {} from 'express';
2
2
  import { AGCID_HEADER, agcidOf } from './agcid.js';
3
- import { requestScope } from './current.js';
3
+ import { requestScope, TRACEPARENT_PATTERN } from './current.js';
4
4
  // Keeps a valid incoming agcid, else mints one; echoed on every response and tags every log line.
5
5
  export const agcidMiddleware = (req, res, next) => {
6
6
  const agcid = agcidOf(req.get(AGCID_HEADER));
7
7
  res.locals['agcid'] = agcid;
8
8
  res.setHeader(AGCID_HEADER, agcid);
9
- requestScope.run({ agcid }, next);
9
+ const traceparent = req.get('traceparent');
10
+ const valid = traceparent !== undefined && TRACEPARENT_PATTERN.test(traceparent);
11
+ requestScope.run(valid ? { agcid, traceparent } : { agcid }, next);
10
12
  };
11
13
  export const agcidOfResponse = (res) => {
12
14
  const agcid = res.locals['agcid'];
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { kitFetch } from '../agcid/fetch.js';
2
3
  import {} from '../health/health.js';
3
4
  import { messageOf } from '../log/log.js';
4
5
  import { retryOnce } from './token-check.js';
@@ -9,7 +10,7 @@ const RevokedSchema = z.object({
9
10
  generatedAt: z.string(),
10
11
  });
11
12
  const readList = async (url) => {
12
- const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
13
+ const res = await kitFetch(url, { signal: AbortSignal.timeout(5000) });
13
14
  if (!res.ok)
14
15
  throw new Error(`the issuer answered ${res.status}`);
15
16
  return new Set(RevokedSchema.parse(await res.json()).revoked.map((entry) => entry.jti));
@@ -1,6 +1,7 @@
1
1
  import { readManifest } from '../manifest/read-manifest.js';
2
2
  import { createOut } from './out.js';
3
- import { contextFor, loadHandlers } from './run-command.js';
3
+ import { cliContext } from './cli-context.js';
4
+ import { loadHandlers } from './run-command.js';
4
5
  const quiet = () => undefined;
5
6
  // null when the cli entry exports create and its handlers are exactly the declared commands.
6
7
  export const checkCli = async (dir) => {
@@ -8,7 +9,7 @@ export const checkCli = async (dir) => {
8
9
  const pkg = await readManifest(dir);
9
10
  const declared = (pkg.agentage.commands ?? []).map((command) => command.name).sort();
10
11
  const out = createOut({ json: false, stdout: quiet, stderr: quiet });
11
- const handlers = Object.keys(await loadHandlers(dir, pkg, contextFor(pkg, {}, out))).sort();
12
+ const handlers = Object.keys(await loadHandlers(dir, pkg, cliContext(pkg, { command: 'check', args: {}, out, stderr: quiet }))).sort();
12
13
  if (JSON.stringify(handlers) === JSON.stringify(declared))
13
14
  return null;
14
15
  return `cli handlers [${handlers.join(', ')}] differ from commands [${declared.join(', ')}]`;
@@ -0,0 +1,15 @@
1
+ import { type Caller } from '../auth/token-check.js';
2
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
+ import { type CliClient, type CliContext } from './command.types.js';
4
+ import { type Out, type Write } from './out.js';
5
+ export interface CommandRun {
6
+ command: string;
7
+ args: CliContext['args'];
8
+ out: Out;
9
+ stderr: Write;
10
+ user?: Caller | null;
11
+ client?: CliClient;
12
+ dataDir?: string;
13
+ }
14
+ export declare const NO_CLIENT: CliClient;
15
+ export declare const cliContext: (pkg: ExtensionPackage, run: CommandRun) => CliContext;
@@ -0,0 +1,34 @@
1
+ import { chmodSync, mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import {} from '../auth/token-check.js';
4
+ import { createLog } from '../log/log.js';
5
+ import {} from '../manifest/manifest.schema.js';
6
+ import {} from './command.types.js';
7
+ import {} from './out.js';
8
+ const unwired = () => Promise.reject(new Error('ctx.client: this host does not provide a client yet'));
9
+ export const NO_CLIENT = Object.freeze({ api: unwired, tool: unwired });
10
+ // Owner-only, made on first read, so --help and the build check never create a folder.
11
+ const ownDir = (dataDir, id) => () => {
12
+ if (dataDir === undefined)
13
+ throw new Error('ctx.dir: this host passes no data dir');
14
+ const dir = join(dataDir, id);
15
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
16
+ chmodSync(dir, 0o700);
17
+ return dir;
18
+ };
19
+ export const cliContext = (pkg, run) => {
20
+ const { id } = pkg.agentage;
21
+ const tags = { extension: id, part: 'cli', version: pkg.version, base: { command: run.command } };
22
+ const dir = ownDir(run.dataDir, id);
23
+ return Object.freeze({
24
+ extension: Object.freeze({ id, version: pkg.version, part: 'cli' }),
25
+ args: Object.freeze(run.args),
26
+ out: run.out,
27
+ log: createLog(tags, run.stderr),
28
+ user: run.user ?? null,
29
+ client: run.client ?? NO_CLIENT,
30
+ get dir() {
31
+ return dir();
32
+ },
33
+ });
34
+ };
@@ -1,3 +1,6 @@
1
+ import { type RouteMethod } from '../api/routes.js';
2
+ import { type Caller } from '../auth/token-check.js';
3
+ import { type Log } from '../log/log.js';
1
4
  import { type Out } from './out.js';
2
5
  import { type ArgValue } from './args.js';
3
6
  export interface CommandExtension {
@@ -5,10 +8,18 @@ export interface CommandExtension {
5
8
  version: string;
6
9
  part: 'cli';
7
10
  }
11
+ export interface CliClient {
12
+ api(method: RouteMethod, path: string, input?: unknown): Promise<unknown>;
13
+ tool(name: string, args?: Record<string, unknown>): Promise<unknown>;
14
+ }
8
15
  export interface CliContext {
9
16
  readonly extension: Readonly<CommandExtension>;
10
17
  readonly args: Readonly<Record<string, ArgValue>>;
11
18
  readonly out: Out;
19
+ readonly log: Log;
20
+ readonly user: Caller | null;
21
+ readonly client: CliClient;
22
+ readonly dir: string;
12
23
  }
13
24
  export type CommandHandler = () => unknown;
14
25
  export type CliCreate = (ctx: CliContext) => Record<string, CommandHandler>;
@@ -1,2 +1,5 @@
1
+ import {} from '../api/routes.js';
2
+ import {} from '../auth/token-check.js';
3
+ import {} from '../log/log.js';
1
4
  import {} from './out.js';
2
5
  import {} from './args.js';
@@ -1,4 +1,5 @@
1
1
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
2
+ import { type CommandRun } from './cli-context.js';
2
3
  import { type CliContext, type CommandHandler } from './command.types.js';
3
4
  import { type Write } from './out.js';
4
5
  export interface RunCommandOptions {
@@ -7,10 +8,12 @@ export interface RunCommandOptions {
7
8
  argv: string[];
8
9
  stdout?: Write;
9
10
  stderr?: Write;
11
+ user?: CommandRun['user'];
12
+ client?: CommandRun['client'];
13
+ dataDir?: string;
10
14
  }
11
15
  export declare const EXIT_OK = 0;
12
16
  export declare const EXIT_FAILED = 1;
13
17
  export declare const EXIT_USAGE = 2;
14
18
  export declare const loadHandlers: (dir: string, pkg: ExtensionPackage, ctx: CliContext) => Promise<Record<string, CommandHandler>>;
15
- export declare const contextFor: (pkg: ExtensionPackage, args: CliContext["args"], out: CliContext["out"]) => CliContext;
16
19
  export declare const runCommand: (o: RunCommandOptions) => Promise<number>;
@@ -1,7 +1,10 @@
1
+ import { uuidv7 } from '../agcid/agcid.js';
2
+ import { requestScope } from '../agcid/current.js';
1
3
  import { loadCreate } from '../manifest/entry.js';
2
4
  import {} from '../manifest/manifest.schema.js';
3
5
  import { readManifest } from '../manifest/read-manifest.js';
4
6
  import { parseCommandArgs, usage, UsageError } from './args.js';
7
+ import { cliContext } from './cli-context.js';
5
8
  import {} from './command.types.js';
6
9
  import { createOut } from './out.js';
7
10
  export const EXIT_OK = 0;
@@ -10,11 +13,6 @@ export const EXIT_USAGE = 2;
10
13
  const writeOut = (text) => void process.stdout.write(text);
11
14
  const writeErr = (text) => void process.stderr.write(text);
12
15
  export const loadHandlers = async (dir, pkg, ctx) => (await loadCreate(dir, pkg, 'cli'))(ctx);
13
- export const contextFor = (pkg, args, out) => ({
14
- extension: Object.freeze({ id: pkg.agentage.id, version: pkg.version, part: 'cli' }),
15
- args: Object.freeze(args),
16
- out,
17
- });
18
16
  const execute = async (o, pkg, stdout, stderr) => {
19
17
  const spec = pkg.agentage.commands?.find((command) => command.name === o.command);
20
18
  if (!spec)
@@ -23,11 +21,17 @@ const execute = async (o, pkg, stdout, stderr) => {
23
21
  if (parsed.help)
24
22
  return (stdout(`${usage(spec)}\n`), EXIT_OK);
25
23
  const out = createOut({ json: parsed.json, stdout, stderr });
26
- const handler = (await loadHandlers(o.dir, pkg, contextFor(pkg, parsed.args, out)))[o.command];
24
+ const { user, client, dataDir, command } = o;
25
+ const ctx = cliContext(pkg, { command, args: parsed.args, out, stderr, user, client, dataDir });
26
+ // One agcid per command run: every log line and kit fetch of the run carries it.
27
+ const result = await requestScope.run({ agcid: uuidv7() }, () => handle(o, pkg, ctx));
28
+ return out.exitCode ?? (typeof result === 'number' ? result : EXIT_OK);
29
+ };
30
+ const handle = async (o, pkg, ctx) => {
31
+ const handler = (await loadHandlers(o.dir, pkg, ctx))[o.command];
27
32
  if (typeof handler !== 'function')
28
33
  throw new Error(`the cli entry has no handler for ${o.command}`);
29
- const result = await handler();
30
- return out.exitCode ?? (typeof result === 'number' ? result : EXIT_OK);
34
+ return handler();
31
35
  };
32
36
  // Exit codes: 0 ok, 2 usage, 1 failure (a throw, a missing handler, an invalid manifest).
33
37
  export const runCommand = async (o) => {
@@ -23,7 +23,7 @@ export const createContext = (input) => {
23
23
  commit,
24
24
  ...(kind && { store: kind }),
25
25
  });
26
- const log = input.log ?? createLog({ extension: pkg.agentage.id, part });
26
+ const log = input.log ?? createLog({ extension: pkg.agentage.id, part, version: pkg.version });
27
27
  const settings = Object.freeze({ ...settingDefaults(pkg), ...input.settings });
28
28
  const auth = Object.freeze({ caller: callerOf });
29
29
  const secrets = input.secrets ?? {};
@@ -0,0 +1,7 @@
1
+ import { type Log, type LogFields, type LogLevel } from '../log/log.js';
2
+ export interface LogEntry {
3
+ level: LogLevel;
4
+ message: string;
5
+ fields: LogFields;
6
+ }
7
+ export declare const recordingLog: (logs: LogEntry[]) => Log;
@@ -0,0 +1,10 @@
1
+ import { messageOf } from '../log/log.js';
2
+ export const recordingLog = (logs) => ({
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
+ });
@@ -0,0 +1,34 @@
1
+ import { type ArgValue } from '../command/args.js';
2
+ import { type Caller } from '../auth/token-check.js';
3
+ import { type CliClient, type CliContext } from '../command/command.types.js';
4
+ import { type LogEntry } from './recording-log.js';
5
+ export type ClientCall = {
6
+ kind: 'api';
7
+ method: string;
8
+ path: string;
9
+ input?: unknown;
10
+ } | {
11
+ kind: 'tool';
12
+ name: string;
13
+ args?: Record<string, unknown>;
14
+ };
15
+ export interface TestCommandContext extends CliContext {
16
+ readonly output: {
17
+ stdout: string[];
18
+ stderr: string[];
19
+ };
20
+ readonly exitCode: number | undefined;
21
+ readonly logs: LogEntry[];
22
+ readonly calls: ClientCall[];
23
+ }
24
+ export interface TestCommandOptions {
25
+ args: Record<string, ArgValue>;
26
+ extension?: {
27
+ id?: string;
28
+ version?: string;
29
+ };
30
+ json?: boolean;
31
+ user?: Caller | null;
32
+ client?: Partial<CliClient>;
33
+ }
34
+ export declare const commandContext: (options: TestCommandOptions) => TestCommandContext;
@@ -0,0 +1,51 @@
1
+ import { mkdtempSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import {} from '../command/args.js';
5
+ import {} from '../auth/token-check.js';
6
+ import {} from '../command/command.types.js';
7
+ import { createOut } from '../command/out.js';
8
+ import { packageExtension } from './package-extension.js';
9
+ import { recordingLog } from './recording-log.js';
10
+ // One recorded line per line written, the trailing newline dropped.
11
+ const lines = (into) => (text) => void into.push(...text.replace(/\n$/, '').split('\n'));
12
+ const recordingClient = (calls, answers = {}) => ({
13
+ api: async (method, path, input) => {
14
+ calls.push({ kind: 'api', method, path, ...(input === undefined ? {} : { input }) });
15
+ return answers.api?.(method, path, input);
16
+ },
17
+ tool: async (name, args) => {
18
+ calls.push({ kind: 'tool', name, ...(args === undefined ? {} : { args }) });
19
+ return answers.tool?.(name, args);
20
+ },
21
+ });
22
+ // A throwaway owner-only folder, made on first read like the real one.
23
+ const lazyDir = () => {
24
+ let dir;
25
+ return () => (dir ??= mkdtempSync(join(tmpdir(), 'agentage-cli-')));
26
+ };
27
+ const recorded = (options) => {
28
+ const output = { stdout: [], stderr: [] };
29
+ const json = options.json ?? false;
30
+ const out = createOut({ json, stdout: lines(output.stdout), stderr: lines(output.stderr) });
31
+ return { out, output, logs: [], calls: [] };
32
+ };
33
+ export const commandContext = (options) => {
34
+ const { out, output, logs, calls } = recorded(options);
35
+ const { id = 'test', version = '0.0.0' } = packageExtension();
36
+ const extension = { id, version, ...options.extension, part: 'cli' };
37
+ const fixedUser = { sub: 'usr_test', scopes: [`${extension.id}:read`] };
38
+ const dir = lazyDir();
39
+ return {
40
+ ...{ extension, args: { ...options.args }, out, output, logs, calls },
41
+ log: recordingLog(logs),
42
+ user: options.user === undefined ? fixedUser : options.user,
43
+ client: recordingClient(calls, options.client),
44
+ get dir() {
45
+ return dir();
46
+ },
47
+ get exitCode() {
48
+ return out.exitCode;
49
+ },
50
+ };
51
+ };
@@ -1,18 +1,14 @@
1
1
  import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
2
2
  import { type WellKnownRegistrar } from '../api/well-known.js';
3
- import { type CliContext } from '../command/command.types.js';
4
- import { type LogFields, type LogLevel } from '../log/log.js';
5
3
  import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
6
4
  import { type JobOptions } from '../worker/job-options.js';
7
5
  import { type JobRun } from '../worker/runs.js';
8
6
  import { type Schedule } from '../worker/scheduler.js';
9
7
  import { type ExtensionInfo, type PartContext, type SettingValue } from './context.js';
10
- import { type ArgValue } from '../command/args.js';
11
- export interface LogEntry {
12
- level: LogLevel;
13
- message: string;
14
- fields: LogFields;
15
- }
8
+ import { type LogEntry } from './recording-log.js';
9
+ import { type TestCommandContext, type TestCommandOptions } from './test-command-context.js';
10
+ export { type LogEntry } from './recording-log.js';
11
+ export { type ClientCall, type TestCommandContext, type TestCommandOptions, } from './test-command-context.js';
16
12
  export interface TestContext extends PartContext {
17
13
  readonly logs: LogEntry[];
18
14
  close(): Promise<void>;
@@ -30,13 +26,6 @@ export interface ScheduledJob {
30
26
  cron: string;
31
27
  options?: JobOptions;
32
28
  }
33
- export interface TestCommandContext extends CliContext {
34
- readonly output: {
35
- stdout: string[];
36
- stderr: string[];
37
- };
38
- readonly exitCode: number | undefined;
39
- }
40
29
  export interface TestContextOptions {
41
30
  extension?: Partial<ExtensionInfo>;
42
31
  settings?: Record<string, SettingValue>;
@@ -45,13 +34,5 @@ export interface TestContextOptions {
45
34
  dir: string;
46
35
  };
47
36
  }
48
- export interface TestCommandOptions {
49
- args: Record<string, ArgValue>;
50
- extension?: {
51
- id?: string;
52
- version?: string;
53
- };
54
- json?: boolean;
55
- }
56
37
  export declare function createTestContext(options: TestCommandOptions): TestCommandContext;
57
38
  export declare function createTestContext(options?: TestContextOptions): TestContext;
@@ -1,8 +1,6 @@
1
1
  import { createRouteRegistry } from '../api/routes.js';
2
2
  import {} from '../api/well-known.js';
3
- import {} from '../command/command.types.js';
4
- import { createOut } from '../command/out.js';
5
- import { messageOf } from '../log/log.js';
3
+ import {} from '../log/log.js';
6
4
  import { createToolRegistry } from '../mcp/tools.js';
7
5
  import { migrate } from '../store/migrations.js';
8
6
  import { createTestStore } from '../store/test-store.js';
@@ -11,18 +9,12 @@ import { runLog } from '../worker/run-log.js';
11
9
  import { memoryRuns } from '../worker/runs.js';
12
10
  import { createScheduler } from '../worker/scheduler.js';
13
11
  import {} from '../manifest/primitives.schema.js';
14
- import { packageExtension } from './package-extension.js';
15
12
  import { NO_STORE } from './context.js';
16
- import {} from '../command/args.js';
17
- const recordingLog = (logs) => ({
18
- info: (message, fields = {}) => void logs.push({ level: 'info', message, fields }),
19
- warn: (message, fields = {}) => void logs.push({ level: 'warn', message, fields }),
20
- error: (error, fields = {}) => void logs.push({
21
- level: 'error',
22
- message: messageOf(error),
23
- fields: { ...fields, err: error },
24
- }),
25
- });
13
+ import { packageExtension } from './package-extension.js';
14
+ import { recordingLog } from './recording-log.js';
15
+ import { commandContext, } from './test-command-context.js';
16
+ export {} from './recording-log.js';
17
+ export {} from './test-command-context.js';
26
18
  const testStore = (option, log) => {
27
19
  if (!option)
28
20
  return undefined;
@@ -80,27 +72,6 @@ const serverContext = (options) => {
80
72
  ...recorders(log),
81
73
  };
82
74
  };
83
- // One recorded line per line written, the trailing newline dropped.
84
- const lines = (into) => (text) => void into.push(...text.replace(/\n$/, '').split('\n'));
85
- const commandContext = (options) => {
86
- const output = { stdout: [], stderr: [] };
87
- const out = createOut({
88
- json: options.json ?? false,
89
- stdout: lines(output.stdout),
90
- stderr: lines(output.stderr),
91
- });
92
- const { id = 'test', version = '0.0.0' } = packageExtension();
93
- const extension = { id, version, ...options.extension, part: 'cli' };
94
- return {
95
- extension,
96
- args: { ...options.args },
97
- out,
98
- output,
99
- get exitCode() {
100
- return out.exitCode;
101
- },
102
- };
103
- };
104
75
  export function createTestContext(options = {}) {
105
76
  return 'args' in options ? commandContext(options) : serverContext(options);
106
77
  }
package/dist/index.d.ts CHANGED
@@ -2,11 +2,11 @@ export { type ApiContext, type ParamsOf, type RouteHandler, type RouteMethod, ty
2
2
  export { pageOf, PageQuerySchema, type Pagination } from './api/page.js';
3
3
  export { type Access, type Caller } from './auth/token-check.js';
4
4
  export { type ArgValue } from './command/args.js';
5
- export { type CliContext, type CliCreate, type CommandExtension, type CommandHandler, } from './command/command.types.js';
5
+ export { type CliClient, type CliContext, type CliCreate, type CommandExtension, type CommandHandler, } from './command/command.types.js';
6
6
  export { type Out } from './command/out.js';
7
7
  export { type ExtensionInfo, type PartContext, type ServerPartKind, type SettingValue, } from './context/context.js';
8
8
  export { type Secrets } from './context/secrets.js';
9
- export { createTestContext, type LogEntry, type ScheduledJob, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
9
+ export { createTestContext, type ClientCall, type LogEntry, type ScheduledJob, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
10
10
  export { DiscoveryDocumentSchema, ExtensionRecordSchema, type DiscoveryDocument, type ExtensionRecord, } from './discovery/discovery.schema.js';
11
11
  export { AGCID_HEADER, isAgcid } from './agcid/agcid.js';
12
12
  export { ERROR_CODES, ERROR_STATUS, type ErrorCode } from './envelope/codes.js';
package/dist/log/log.d.ts CHANGED
@@ -8,7 +8,10 @@ export interface Log {
8
8
  export interface LogTags {
9
9
  extension: string;
10
10
  part: string;
11
+ version?: string;
12
+ base?: LogFields;
11
13
  }
12
14
  export type LogWrite = (line: string) => void;
13
15
  export declare const messageOf: (error: unknown) => string;
14
16
  export declare const createLog: (tags: LogTags, write?: LogWrite) => Log;
17
+ export declare const logAt: (log: Log, level: LogLevel, message: string, fields: LogFields) => void;
package/dist/log/log.js CHANGED
@@ -9,13 +9,30 @@ const errorFields = (error) => {
9
9
  const line = (level, message, tags, fields) => {
10
10
  const agcid = currentAgcid();
11
11
  const ids = { 'extension.id': tags.extension, 'extension.part': tags.part };
12
- const own = { time: new Date().toISOString(), level, msg: message, ...ids };
12
+ const version = tags.version === undefined ? {} : { version: tags.version };
13
+ const own = { time: new Date().toISOString(), level, msg: message, ...ids, ...version };
13
14
  const fixed = agcid ? { ...own, agcid } : own;
14
- return `${JSON.stringify({ ...fixed, ...fields, ...fixed })}\n`;
15
+ return `${JSON.stringify({ ...fixed, ...tags.base, ...fields, ...fixed })}\n`;
15
16
  };
16
17
  const stderrWrite = (text) => void process.stderr.write(text);
17
- export const createLog = (tags, write = stderrWrite) => ({
18
- info: (message, fields = {}) => write(line('info', message, tags, fields)),
19
- warn: (message, fields = {}) => write(line('warn', message, tags, fields)),
20
- error: (error, fields = {}) => write(line('error', messageOf(error), tags, { ...fields, ...errorFields(error) })),
21
- });
18
+ const raw = new WeakMap();
19
+ export const createLog = (tags, write = stderrWrite) => {
20
+ const at = (level, message, fields) => write(line(level, message, tags, fields));
21
+ const log = {
22
+ info: (message, fields = {}) => at('info', message, fields),
23
+ warn: (message, fields = {}) => at('warn', message, fields),
24
+ error: (error, fields = {}) => at('error', messageOf(error), { ...fields, ...errorFields(error) }),
25
+ };
26
+ raw.set(log, at);
27
+ return log;
28
+ };
29
+ // A line at any level with no err field (an error-level line that is not an error event).
30
+ export const logAt = (log, level, message, fields) => {
31
+ const at = raw.get(log);
32
+ if (at)
33
+ at(level, message, fields);
34
+ else if (level === 'error')
35
+ log.error(message, fields);
36
+ else
37
+ log[level](message, fields);
38
+ };
@@ -1,3 +1,4 @@
1
+ import { kitFetch } from '../agcid/fetch.js';
1
2
  export const PROTOCOL_VERSIONS = ['2025-11-25', '2026-07-28'];
2
3
  const CLIENT = { name: 'agentage-snapshot', version: '1.0.0' };
3
4
  // Key order never counts: the two eras serialize the same schema in different orders.
@@ -44,7 +45,7 @@ const post = async (url, version, method, params) => {
44
45
  method,
45
46
  params: modern ? { ...params, _meta: META } : params,
46
47
  };
47
- return payload(await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) }));
48
+ return payload(await kitFetch(url, { method: 'POST', headers, body: JSON.stringify(body) }));
48
49
  };
49
50
  const serverInfoOf = async (url, version) => {
50
51
  if (version === '2025-11-25') {
@@ -89,7 +89,7 @@ const inputFor = async (options, start) => {
89
89
  export const runPart = async (options) => {
90
90
  const pkg = await readManifest(options.dir);
91
91
  const part = partOf(pkg, options.part);
92
- const log = createLog({ extension: pkg.agentage.id, part });
92
+ const log = createLog({ extension: pkg.agentage.id, part, version: pkg.version });
93
93
  const names = part === 'ui' ? [] : (pkg.agentage.secrets ?? []);
94
94
  const secrets = await readSecrets(names, options.secretsDir ?? SECRETS_DIR, part);
95
95
  const start = { pkg, part, env: options.env, log, secrets };
@@ -12,6 +12,7 @@ import {} from '../log/log.js';
12
12
  import {} from '../manifest/manifest.schema.js';
13
13
  import {} from '../manifest/primitives.schema.js';
14
14
  import { errorHandler, notFound } from './errors.js';
15
+ import { requestLine } from './request-line.js';
15
16
  import {} from './part.types.js';
16
17
  // api-standards section 6: CORS * without credentials on /.well-known/, /api/, /ui/ and /mcp.
17
18
  export const PUBLIC_CORS = {
@@ -48,6 +49,8 @@ export const createPartApp = (options) => {
48
49
  app.set('trust proxy', 'loopback, linklocal, uniquelocal');
49
50
  app.use(dropCookie, agcidMiddleware, helmet(options.helmet));
50
51
  app.get('/health', healthHandler(options));
52
+ // After /health: it is probed every few seconds and never gets a request line.
53
+ app.use(requestLine(options.log));
51
54
  if (options.part !== 'worker') {
52
55
  app.use('/.well-known', cors(PUBLIC_CORS));
53
56
  app.get('/.well-known/agentage-extension.json', discoveryHandler(options));
@@ -0,0 +1,4 @@
1
+ import { type Request, type RequestHandler } from 'express';
2
+ import { type Log } from '../log/log.js';
3
+ export declare const routeOf: (req: Request) => string;
4
+ export declare const requestLine: (log: Log) => RequestHandler;
@@ -0,0 +1,25 @@
1
+ import {} from 'express';
2
+ import { agcidOfResponse } from '../agcid/scope.js';
3
+ import { logAt } from '../log/log.js';
4
+ const MOUNTS = ['/api/v1', '/mcp', '/.well-known', '/ui'];
5
+ const levelOf = (status) => status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info';
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}/`)) ?? '/';
10
+ const path = req.route?.path;
11
+ if (typeof path !== 'string')
12
+ return prefix;
13
+ return path.startsWith(prefix) ? path : `${prefix}${path}`;
14
+ };
15
+ // One line per request on finish; the 5xx error itself is errors.ts's line, never repeated here.
16
+ export const requestLine = (log) => (req, res, next) => {
17
+ const start = performance.now();
18
+ 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 });
23
+ });
24
+ next();
25
+ };
@@ -9,7 +9,7 @@ const MIGRATE_TIMEOUTS = { connectMs: 10_000, statementMs: 300_000 };
9
9
  let log = createLog({ extension: 'unknown', part: 'migrate' });
10
10
  try {
11
11
  const pkg = await readManifest(process.cwd());
12
- log = createLog({ extension: pkg.agentage.id, part: 'migrate' });
12
+ log = createLog({ extension: pkg.agentage.id, part: 'migrate', version: pkg.version });
13
13
  const store = createStore(process.env, log, MIGRATE_TIMEOUTS);
14
14
  const result = await migrate(store, process.cwd(), log);
15
15
  process.stdout.write(`${JSON.stringify(result)}\n`);
@@ -7,6 +7,7 @@ export interface JobRun {
7
7
  status: RunStatus;
8
8
  log: string;
9
9
  timeoutMs?: number;
10
+ agcid?: string;
10
11
  }
11
12
  export interface RunStore {
12
13
  save(run: JobRun): Promise<void>;
@@ -1,8 +1,8 @@
1
1
  import { JOB_RUNS_SQL } from '../store/kit-migrations.js';
2
2
  import {} from '../store/store.types.js';
3
3
  export const KEEP_RUNS = 50;
4
- const INSERT = `insert into agentage_job_runs (job, started_at, ended_at, status, log, timeout_ms)
5
- values ($1, $2, $3, $4, $5, $6)`;
4
+ const INSERT = `insert into agentage_job_runs
5
+ (job, started_at, ended_at, status, log, timeout_ms, agcid) values ($1, $2, $3, $4, $5, $6, $7)`;
6
6
  const PRUNE = `delete from agentage_job_runs where job = $1 and id not in
7
7
  (select id from agentage_job_runs where job = $1 order by id desc limit ${KEEP_RUNS})`;
8
8
  const fromRow = (row) => ({
@@ -12,6 +12,7 @@ const fromRow = (row) => ({
12
12
  status: row.status,
13
13
  log: row.log,
14
14
  ...(row.timeout_ms === null ? {} : { timeoutMs: row.timeout_ms }),
15
+ ...(row.agcid ? { agcid: row.agcid } : {}),
15
16
  });
16
17
  const LAST = 'select * from agentage_job_runs where job = $1 order by id desc limit 1';
17
18
  const valuesOf = (run) => [
@@ -21,6 +22,7 @@ const valuesOf = (run) => [
21
22
  run.status,
22
23
  run.log,
23
24
  run.timeoutMs ?? null,
25
+ run.agcid ?? null,
24
26
  ];
25
27
  // Runs live in the extension's own store, in a table the kit owns; the last 50 per job are kept.
26
28
  export const storeRuns = (store) => {
@@ -1,3 +1,5 @@
1
+ import { uuidv7 } from '../agcid/agcid.js';
2
+ import { requestScope } from '../agcid/current.js';
1
3
  import {} from '../health/health.js';
2
4
  import {} from '../log/log.js';
3
5
  import { nextRun, parseCron } from './cron.js';
@@ -45,14 +47,19 @@ const runJob = async (entry, log, buffer) => {
45
47
  }
46
48
  };
47
49
  // Never twice at once; every run saved with its log, a failed save is logged and the job goes on.
48
- const execute = async (s, entry) => {
50
+ const execute = (s, entry) => requestScope.run({ agcid: uuidv7() }, () => executeScoped(s, entry));
51
+ // Inside the run's scope: every log line of the job, its failure and its save share one agcid.
52
+ const executeScoped = async (s, entry) => {
49
53
  const startedAt = s.now();
50
54
  Object.assign(entry, { running: true, runningSince: startedAt, overran: false });
51
55
  const buffer = { text: '', truncated: false };
52
56
  const status = await runJob(entry, s.deps.log, buffer);
53
57
  entry.running = false;
54
58
  entry.last = status;
59
+ const agcid = requestScope.getStore()?.agcid;
55
60
  const run = { job: entry.name, startedAt, endedAt: s.now(), status, log: buffer.text };
61
+ if (agcid)
62
+ run.agcid = agcid;
56
63
  if (entry.timeoutMs !== undefined)
57
64
  run.timeoutMs = entry.timeoutMs;
58
65
  await s.deps.runs.save(run).catch((err) => s.deps.log.error(err, { job: entry.name }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
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",