@canonry/canonry 7.72.1 → 7.72.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.
@@ -10,7 +10,7 @@ import {
10
10
  backfillSnapshotAttributionCommand,
11
11
  backfillTrafficClassificationCommand,
12
12
  replayQueryAuditLog
13
- } from "./chunk-TUVG7BIF.js";
13
+ } from "./chunk-CF6BUJRK.js";
14
14
  import "./chunk-JO73L677.js";
15
15
  import "./chunk-JE5QURTR.js";
16
16
  import "./chunk-HGMYEDAQ.js";
@@ -437,7 +437,7 @@ No DB writes performed. Re-run without --dry-run to apply.`);
437
437
  }
438
438
  }
439
439
  async function backfillInsightsCommand(project, opts) {
440
- const { IntelligenceService } = await import("./intelligence-service-YNHDEY4M.js");
440
+ const { IntelligenceService } = await import("./intelligence-service-LVRH4RJG.js");
441
441
  const config = loadConfig();
442
442
  const db = createClient(config.database);
443
443
  migrate(db);
@@ -696,7 +696,7 @@ var DEMO_CLI_COMMANDS = [{
696
696
  options: { host: stringOption(), port: stringOption(), "trust-proxy": multiStringOption() },
697
697
  allowPositionals: false,
698
698
  run: async (input) => {
699
- const { demoCommand } = await import("./demo-HYDPECCK.js");
699
+ const { demoCommand } = await import("./demo-GLV22DPY.js");
700
700
  await demoCommand({
701
701
  host: getString(input.values, "host"),
702
702
  port: getString(input.values, "port"),
@@ -717,7 +717,7 @@ var BACKFILL_CLI_COMMANDS = [
717
717
  allowPositionals: false,
718
718
  supportsDryRun: true,
719
719
  run: async (input) => {
720
- const { backfillAnswerVisibilityCommand } = await import("./backfill-7SGCPH6J.js");
720
+ const { backfillAnswerVisibilityCommand } = await import("./backfill-NE55YL6X.js");
721
721
  await backfillAnswerVisibilityCommand({
722
722
  project: getString(input.values, "project"),
723
723
  dryRun: input.dryRun,
@@ -734,7 +734,7 @@ var BACKFILL_CLI_COMMANDS = [
734
734
  allowPositionals: false,
735
735
  supportsDryRun: true,
736
736
  run: async (input) => {
737
- const { backfillAnswerMentionsCommand } = await import("./backfill-7SGCPH6J.js");
737
+ const { backfillAnswerMentionsCommand } = await import("./backfill-NE55YL6X.js");
738
738
  await backfillAnswerMentionsCommand({
739
739
  project: getString(input.values, "project"),
740
740
  dryRun: input.dryRun,
@@ -752,7 +752,7 @@ var BACKFILL_CLI_COMMANDS = [
752
752
  },
753
753
  supportsDryRun: true,
754
754
  run: async (input) => {
755
- const { backfillInsightsCommand } = await import("./backfill-7SGCPH6J.js");
755
+ const { backfillInsightsCommand } = await import("./backfill-NE55YL6X.js");
756
756
  const usage = "canonry backfill insights <project> [--from-run <id>] [--to-run <id>] [--since <date>] [--dry-run] [--format json]";
757
757
  const project3 = requireProject(input, "backfill insights", usage);
758
758
  await backfillInsightsCommand(project3, {
@@ -772,7 +772,7 @@ var BACKFILL_CLI_COMMANDS = [
772
772
  },
773
773
  allowPositionals: false,
774
774
  run: async (input) => {
775
- const { backfillNormalizedPathsCommand } = await import("./backfill-7SGCPH6J.js");
775
+ const { backfillNormalizedPathsCommand } = await import("./backfill-NE55YL6X.js");
776
776
  await backfillNormalizedPathsCommand({
777
777
  project: getString(input.values, "project"),
778
778
  format: input.format
@@ -787,7 +787,7 @@ var BACKFILL_CLI_COMMANDS = [
787
787
  },
788
788
  allowPositionals: false,
789
789
  run: async (input) => {
790
- const { backfillAiReferralPathsCommand } = await import("./backfill-7SGCPH6J.js");
790
+ const { backfillAiReferralPathsCommand } = await import("./backfill-NE55YL6X.js");
791
791
  await backfillAiReferralPathsCommand({
792
792
  project: getString(input.values, "project"),
793
793
  format: input.format
@@ -799,7 +799,7 @@ var BACKFILL_CLI_COMMANDS = [
799
799
  usage: "canonry backfill snapshot-attribution <project> [--dry-run] [--format json]",
800
800
  supportsDryRun: true,
801
801
  run: async (input) => {
802
- const { backfillSnapshotAttributionCommand } = await import("./backfill-7SGCPH6J.js");
802
+ const { backfillSnapshotAttributionCommand } = await import("./backfill-NE55YL6X.js");
803
803
  const usage = "canonry backfill snapshot-attribution <project> [--dry-run] [--format json]";
804
804
  const project3 = requireProject(input, "backfill snapshot-attribution", usage);
805
805
  await backfillSnapshotAttributionCommand({
@@ -818,7 +818,7 @@ var BACKFILL_CLI_COMMANDS = [
818
818
  allowPositionals: false,
819
819
  supportsDryRun: true,
820
820
  run: async (input) => {
821
- const { backfillTrafficClassificationCommand } = await import("./backfill-7SGCPH6J.js");
821
+ const { backfillTrafficClassificationCommand } = await import("./backfill-NE55YL6X.js");
822
822
  await backfillTrafficClassificationCommand({
823
823
  project: getString(input.values, "project"),
824
824
  dryRun: input.dryRun,
@@ -6829,7 +6829,7 @@ var SYSTEM_CLI_COMMANDS = [
6829
6829
  options: { access: stringOption() },
6830
6830
  run: async (input) => {
6831
6831
  if (input.positionals.length > 1) throw usageError("Expected at most one command group");
6832
- const [{ printCliCatalog }, { REGISTERED_CLI_COMMANDS: REGISTERED_CLI_COMMANDS2 }] = await Promise.all([import("./cli-catalog-NEZE5QU5.js"), import("./cli-commands-HGCYU4MQ.js")]);
6832
+ const [{ printCliCatalog }, { REGISTERED_CLI_COMMANDS: REGISTERED_CLI_COMMANDS2 }] = await Promise.all([import("./cli-catalog-NEZE5QU5.js"), import("./cli-commands-ARJWPTFW.js")]);
6833
6833
  printCliCatalog(REGISTERED_CLI_COMMANDS2, input.format, input.positionals[0], getString(input.values, "access"));
6834
6834
  }
6835
6835
  },
@@ -6878,7 +6878,7 @@ var SYSTEM_CLI_COMMANDS = [
6878
6878
  },
6879
6879
  allowPositionals: false,
6880
6880
  run: async (input) => {
6881
- const { initCommand } = await import("./init-TV4ZKAAW.js");
6881
+ const { initCommand } = await import("./init-Q33HEJJN.js");
6882
6882
  await initCommand({
6883
6883
  force: getBoolean(input.values, "force"),
6884
6884
  ref: getString(input.values, "ref"),
@@ -6933,7 +6933,7 @@ var SYSTEM_CLI_COMMANDS = [
6933
6933
  allowPositionals: false,
6934
6934
  run: async (input) => {
6935
6935
  applyServerEnv(input.values);
6936
- const { serveCommand } = await import("./serve-76BGQFPW.js");
6936
+ const { serveCommand } = await import("./serve-SJTQQQQE.js");
6937
6937
  await serveCommand(input.format);
6938
6938
  }
6939
6939
  },
@@ -8251,7 +8251,7 @@ var AGENT_CLI_COMMANDS = [
8251
8251
  "timeout-ms": stringOption()
8252
8252
  },
8253
8253
  run: async (input) => {
8254
- const { coerceAgentProvider } = await import("./session-JBTIV7SS.js");
8254
+ const { coerceAgentProvider } = await import("./session-VHCKM3AI.js");
8255
8255
  const { AERO_TOOL_PROFILES, isAeroToolProfile } = await import("./tools-4VRHKUBE.js");
8256
8256
  const { agentAsk } = await import("./agent-ask-OBHTCYFR.js");
8257
8257
  const usage = `canonry agent ask <project> "<prompt>" [--provider ${AGENT_PROVIDER_IDS.join("|")}] [--model <id>] [--scope all|read-only] [--profile default|ads-operator] [--context <json>] [--conversation <id>] [--max-tool-calls <n>] [--timeout-ms <ms>] [--format json]`;
@@ -0,0 +1,269 @@
1
+ import {
2
+ getRequestContext
3
+ } from "./chunk-BADJCT6U.js";
4
+ import {
5
+ diagnosticIdentity,
6
+ redactLogString,
7
+ redactLogValue
8
+ } from "./chunk-YXAKL5HM.js";
9
+
10
+ // ../api-routes/src/runtime-logger.ts
11
+ import { format } from "util";
12
+ var IS_TTY = process.stdout.isTTY === true;
13
+ var MAX_IDENTITY_LENGTH = 512;
14
+ var RESERVED_FIELDS = /* @__PURE__ */ new Set([
15
+ "ts",
16
+ "level",
17
+ "module",
18
+ "action",
19
+ "msg",
20
+ "requestId",
21
+ "actor",
22
+ "credentialId",
23
+ "userAgent",
24
+ "actorSession",
25
+ "__runtimeRequestId"
26
+ ]);
27
+ var listeners = /* @__PURE__ */ new Set();
28
+ function addLogListener(listener) {
29
+ listeners.add(listener);
30
+ return () => listeners.delete(listener);
31
+ }
32
+ function createLogger(module) {
33
+ const emit = (level, action, context) => {
34
+ const msg = context ? safeProperty(context, "msg") : void 0;
35
+ emitRuntimeLog({ level, module, action, context, ...typeof msg === "string" ? { msg } : {} });
36
+ };
37
+ return {
38
+ info: (action, ctx) => emit("info", action, ctx),
39
+ warn: (action, ctx) => emit("warn", action, ctx),
40
+ error: (action, ctx) => emit("error", action, ctx)
41
+ };
42
+ }
43
+ function createFastifyLogger(options = {}) {
44
+ return buildFastifyLogger(options.module ?? "HTTP", options.enabled !== false, {});
45
+ }
46
+ var LEVELS = { trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60, silent: Infinity };
47
+ function buildFastifyLogger(module, enabled, bindings, inheritedLevel = "info") {
48
+ let level = inheritedLevel;
49
+ const emit = (severity, args) => {
50
+ if (LEVELS[severity] >= LEVELS[level]) logFastify(severity, module, enabled, bindings, args);
51
+ };
52
+ const logger = {
53
+ get level() {
54
+ return level;
55
+ },
56
+ set level(value) {
57
+ if (Object.hasOwn(LEVELS, value)) level = value;
58
+ },
59
+ trace: (...args) => emit("trace", args),
60
+ debug: (...args) => emit("debug", args),
61
+ info: (...args) => emit("info", args),
62
+ warn: (...args) => emit("warn", args),
63
+ error: (...args) => emit("error", args),
64
+ fatal: (...args) => emit("fatal", args),
65
+ silent: () => void 0,
66
+ child: (childBindings) => buildFastifyLogger(module, enabled, mergeBindings(bindings, childBindings), level)
67
+ };
68
+ return logger;
69
+ }
70
+ function logFastify(level, module, enabled, bindings, args) {
71
+ const { context, msg } = normalizePinoArgs(args);
72
+ emitRuntimeLog({
73
+ level,
74
+ module,
75
+ action: `fastify.${level}`,
76
+ msg,
77
+ context: { ...bindings, ...context },
78
+ trustedRequestId: asBoundString(bindings.__runtimeRequestId),
79
+ enabled
80
+ });
81
+ }
82
+ function normalizePinoArgs(args) {
83
+ const first = args[0];
84
+ const second = args[1];
85
+ if (typeof first === "string") return { context: {}, msg: safeFormat(first, args.slice(1)) };
86
+ if (first instanceof Error) {
87
+ return { context: { err: first }, msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
88
+ }
89
+ if (isObject(first)) {
90
+ return { context: copyOwnData(first), msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
91
+ }
92
+ return { context: {}, msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
93
+ }
94
+ function emitRuntimeLog({
95
+ level,
96
+ module,
97
+ action,
98
+ msg,
99
+ context,
100
+ trustedRequestId,
101
+ enabled = true
102
+ }) {
103
+ const safeContext = sanitizeContext(context);
104
+ const error = safeContext.err ?? safeContext.error;
105
+ const errorMessage = typeof error === "string" ? error : isRecord(error) && typeof error.message === "string" ? error.message : void 0;
106
+ const message = errorMessage && errorMessage !== msg ? [msg, errorMessage].filter(Boolean).join(": ") : msg;
107
+ const entry = {
108
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
109
+ level,
110
+ module: boundText(module, "Runtime"),
111
+ action: boundText(action, "log"),
112
+ ...message === void 0 ? {} : { msg: redactLogString(message) },
113
+ ...safeContext,
114
+ ...trustedAttribution(getRequestContext(trustedRequestId), trustedRequestId)
115
+ };
116
+ if (enabled) writeEntry(entry);
117
+ for (const listener of listeners) {
118
+ try {
119
+ listener(entry);
120
+ } catch {
121
+ }
122
+ }
123
+ }
124
+ function sanitizeContext(context) {
125
+ if (!context) return {};
126
+ const output = {};
127
+ for (const key of safeKeys(context).slice(0, 100)) {
128
+ if (RESERVED_FIELDS.has(key)) continue;
129
+ const value = safeProperty(context, key);
130
+ if (key === "req" || key === "request") {
131
+ Object.assign(output, normalizeRequest(value));
132
+ continue;
133
+ }
134
+ if (key === "res" || key === "reply") {
135
+ Object.assign(output, normalizeReply(value));
136
+ continue;
137
+ }
138
+ if (key === "responseTime" || key === "duration") {
139
+ if (typeof value === "number" && Number.isFinite(value)) output.durationMs = value;
140
+ continue;
141
+ }
142
+ output[key] = value;
143
+ }
144
+ delete output.__runtimeRequestId;
145
+ const redacted = redactLogValue(output);
146
+ return isRecord(redacted) ? redacted : {};
147
+ }
148
+ function trustedAttribution(context, trustedRequestId) {
149
+ const requestId = boundOptional(context?.requestId) ?? trustedRequestId;
150
+ const actor = diagnosticIdentity("actor", context?.actor);
151
+ const credentialId = diagnosticIdentity("credentialId", context?.credentialId);
152
+ const userAgent = boundOptional(context?.userAgent);
153
+ const actorSession = boundOptional(context?.actorSession);
154
+ const method = boundOptional(context?.method);
155
+ const route = boundOptional(context?.route);
156
+ return {
157
+ ...requestId ? { requestId } : {},
158
+ ...actor ? { actor } : {},
159
+ ...credentialId ? { credentialId } : {},
160
+ ...userAgent ? { userAgent } : {},
161
+ ...actorSession ? { actorSession } : {},
162
+ ...method ? { method } : {},
163
+ ...route ? { route } : {},
164
+ ...context?.statusCode === void 0 ? {} : { statusCode: context.statusCode }
165
+ };
166
+ }
167
+ function mergeBindings(parent, child) {
168
+ const merged = { ...parent };
169
+ if (!isObject(child)) return merged;
170
+ for (const key of safeKeys(child).slice(0, 100)) {
171
+ const value = safeProperty(child, key);
172
+ if (key === "req" || key === "request") Object.assign(merged, normalizeRequest(value));
173
+ else if (key === "res" || key === "reply") Object.assign(merged, normalizeReply(value));
174
+ else if (key === "reqId") {
175
+ merged.reqId = value;
176
+ merged.__runtimeRequestId = value;
177
+ } else if (!RESERVED_FIELDS.has(key)) merged[key] = value;
178
+ }
179
+ return merged;
180
+ }
181
+ function normalizeRequest(value) {
182
+ if (!isObject(value)) return {};
183
+ const id = asBoundString(safeProperty(value, "id"));
184
+ const method = asBoundString(safeProperty(value, "method"));
185
+ const routeOptions = safeProperty(value, "routeOptions");
186
+ const route = isObject(routeOptions) ? asBoundString(safeProperty(routeOptions, "url")) : void 0;
187
+ return {
188
+ ...id ? { reqId: id, __runtimeRequestId: id } : {},
189
+ ...method ? { method } : {},
190
+ ...route ? { route } : {}
191
+ };
192
+ }
193
+ function normalizeReply(value) {
194
+ if (!isObject(value)) return {};
195
+ const statusCode = safeProperty(value, "statusCode");
196
+ return typeof statusCode === "number" && Number.isFinite(statusCode) ? { statusCode } : {};
197
+ }
198
+ function writeEntry(entry) {
199
+ const stream = entry.level === "error" || entry.level === "fatal" ? process.stderr : process.stdout;
200
+ const line = IS_TTY ? formatTTY(entry) : JSON.stringify(entry);
201
+ try {
202
+ stream.write(`${line}
203
+ `);
204
+ } catch {
205
+ }
206
+ }
207
+ function formatTTY(entry) {
208
+ const { ts, level, module, action, msg, ...context } = entry;
209
+ const levelTag = level === "fatal" || level === "error" ? "ERR" : level === "warn" ? "WRN" : "INF";
210
+ const parts = safeKeys(context).map((key) => `${key}=${safeDisplay(safeProperty(context, key))}`);
211
+ return `${ts.slice(11, 19)} ${levelTag} [${module}] ${action}${msg ? ` ${msg}` : ""}${parts.length ? ` ${parts.join(" ")}` : ""}`;
212
+ }
213
+ function safeDisplay(value) {
214
+ try {
215
+ return typeof value === "string" ? value : JSON.stringify(value);
216
+ } catch {
217
+ return "[UNSERIALIZABLE]";
218
+ }
219
+ }
220
+ function safeFormat(message, args) {
221
+ try {
222
+ return args.length ? format(message, ...args) : message;
223
+ } catch {
224
+ return message;
225
+ }
226
+ }
227
+ function isObject(value) {
228
+ return value !== null && typeof value === "object";
229
+ }
230
+ function isRecord(value) {
231
+ return isObject(value) && !Array.isArray(value);
232
+ }
233
+ function safeKeys(value) {
234
+ try {
235
+ return Object.keys(value);
236
+ } catch {
237
+ return [];
238
+ }
239
+ }
240
+ function safeProperty(value, key) {
241
+ try {
242
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
243
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
244
+ } catch {
245
+ return void 0;
246
+ }
247
+ }
248
+ function copyOwnData(value) {
249
+ const output = {};
250
+ for (const key of safeKeys(value)) output[key] = safeProperty(value, key);
251
+ return output;
252
+ }
253
+ function boundText(value, fallback) {
254
+ return boundOptional(value) ?? fallback;
255
+ }
256
+ function asBoundString(value) {
257
+ return typeof value === "string" ? boundOptional(value) : void 0;
258
+ }
259
+ function boundOptional(value) {
260
+ if (typeof value !== "string") return void 0;
261
+ const redacted = redactLogString(value).replace(/[\r\n]+/g, " ").trim().slice(0, MAX_IDENTITY_LENGTH);
262
+ return redacted || void 0;
263
+ }
264
+
265
+ export {
266
+ addLogListener,
267
+ createLogger,
268
+ createFastifyLogger
269
+ };
@@ -1,3 +1,6 @@
1
+ import {
2
+ createLogger
3
+ } from "./chunk-HZSE3WSG.js";
1
4
  import {
2
5
  pickProjectCitedDomain
3
6
  } from "./chunk-DRGCVTYH.js";
@@ -15,9 +18,6 @@ import {
15
18
  readGscQueryDailyRows,
16
19
  readLatestGscDataDate
17
20
  } from "./chunk-7KOAP47B.js";
18
- import {
19
- getRequestContext
20
- } from "./chunk-BADJCT6U.js";
21
21
  import {
22
22
  competitors,
23
23
  gbpDailyMetrics,
@@ -41,272 +41,12 @@ import {
41
41
  RunKinds,
42
42
  RunStatuses,
43
43
  RunTriggers,
44
- diagnosticIdentity,
45
- effectiveDomains,
46
- redactLogString,
47
- redactLogValue
44
+ effectiveDomains
48
45
  } from "./chunk-YXAKL5HM.js";
49
46
 
50
47
  // src/intelligence-service.ts
51
48
  import { eq, desc, asc, and, ne, or, inArray, gte, lte, isNull, sql, exists } from "drizzle-orm";
52
49
  import crypto from "crypto";
53
-
54
- // ../api-routes/src/runtime-logger.ts
55
- import { format } from "util";
56
- var IS_TTY = process.stdout.isTTY === true;
57
- var MAX_IDENTITY_LENGTH = 512;
58
- var RESERVED_FIELDS = /* @__PURE__ */ new Set([
59
- "ts",
60
- "level",
61
- "module",
62
- "action",
63
- "msg",
64
- "requestId",
65
- "actor",
66
- "credentialId",
67
- "userAgent",
68
- "actorSession",
69
- "__runtimeRequestId"
70
- ]);
71
- var listeners = /* @__PURE__ */ new Set();
72
- function addLogListener(listener) {
73
- listeners.add(listener);
74
- return () => listeners.delete(listener);
75
- }
76
- function createLogger(module) {
77
- const emit = (level, action, context) => {
78
- const msg = context ? safeProperty(context, "msg") : void 0;
79
- emitRuntimeLog({ level, module, action, context, ...typeof msg === "string" ? { msg } : {} });
80
- };
81
- return {
82
- info: (action, ctx) => emit("info", action, ctx),
83
- warn: (action, ctx) => emit("warn", action, ctx),
84
- error: (action, ctx) => emit("error", action, ctx)
85
- };
86
- }
87
- function createFastifyLogger(options = {}) {
88
- return buildFastifyLogger(options.module ?? "HTTP", options.enabled !== false, {});
89
- }
90
- var LEVELS = { trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60, silent: Infinity };
91
- function buildFastifyLogger(module, enabled, bindings, inheritedLevel = "info") {
92
- let level = inheritedLevel;
93
- const emit = (severity, args) => {
94
- if (LEVELS[severity] >= LEVELS[level]) logFastify(severity, module, enabled, bindings, args);
95
- };
96
- const logger = {
97
- get level() {
98
- return level;
99
- },
100
- set level(value) {
101
- if (Object.hasOwn(LEVELS, value)) level = value;
102
- },
103
- trace: (...args) => emit("trace", args),
104
- debug: (...args) => emit("debug", args),
105
- info: (...args) => emit("info", args),
106
- warn: (...args) => emit("warn", args),
107
- error: (...args) => emit("error", args),
108
- fatal: (...args) => emit("fatal", args),
109
- silent: () => void 0,
110
- child: (childBindings) => buildFastifyLogger(module, enabled, mergeBindings(bindings, childBindings), level)
111
- };
112
- return logger;
113
- }
114
- function logFastify(level, module, enabled, bindings, args) {
115
- const { context, msg } = normalizePinoArgs(args);
116
- emitRuntimeLog({
117
- level,
118
- module,
119
- action: `fastify.${level}`,
120
- msg,
121
- context: { ...bindings, ...context },
122
- trustedRequestId: asBoundString(bindings.__runtimeRequestId),
123
- enabled
124
- });
125
- }
126
- function normalizePinoArgs(args) {
127
- const first = args[0];
128
- const second = args[1];
129
- if (typeof first === "string") return { context: {}, msg: safeFormat(first, args.slice(1)) };
130
- if (first instanceof Error) {
131
- return { context: { err: first }, msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
132
- }
133
- if (isObject(first)) {
134
- return { context: copyOwnData(first), msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
135
- }
136
- return { context: {}, msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
137
- }
138
- function emitRuntimeLog({
139
- level,
140
- module,
141
- action,
142
- msg,
143
- context,
144
- trustedRequestId,
145
- enabled = true
146
- }) {
147
- const safeContext = sanitizeContext(context);
148
- const error = safeContext.err ?? safeContext.error;
149
- const errorMessage = typeof error === "string" ? error : isRecord(error) && typeof error.message === "string" ? error.message : void 0;
150
- const message = errorMessage && errorMessage !== msg ? [msg, errorMessage].filter(Boolean).join(": ") : msg;
151
- const entry = {
152
- ts: (/* @__PURE__ */ new Date()).toISOString(),
153
- level,
154
- module: boundText(module, "Runtime"),
155
- action: boundText(action, "log"),
156
- ...message === void 0 ? {} : { msg: redactLogString(message) },
157
- ...safeContext,
158
- ...trustedAttribution(getRequestContext(trustedRequestId), trustedRequestId)
159
- };
160
- if (enabled) writeEntry(entry);
161
- for (const listener of listeners) {
162
- try {
163
- listener(entry);
164
- } catch {
165
- }
166
- }
167
- }
168
- function sanitizeContext(context) {
169
- if (!context) return {};
170
- const output = {};
171
- for (const key of safeKeys(context).slice(0, 100)) {
172
- if (RESERVED_FIELDS.has(key)) continue;
173
- const value = safeProperty(context, key);
174
- if (key === "req" || key === "request") {
175
- Object.assign(output, normalizeRequest(value));
176
- continue;
177
- }
178
- if (key === "res" || key === "reply") {
179
- Object.assign(output, normalizeReply(value));
180
- continue;
181
- }
182
- if (key === "responseTime" || key === "duration") {
183
- if (typeof value === "number" && Number.isFinite(value)) output.durationMs = value;
184
- continue;
185
- }
186
- output[key] = value;
187
- }
188
- delete output.__runtimeRequestId;
189
- const redacted = redactLogValue(output);
190
- return isRecord(redacted) ? redacted : {};
191
- }
192
- function trustedAttribution(context, trustedRequestId) {
193
- const requestId = boundOptional(context?.requestId) ?? trustedRequestId;
194
- const actor = diagnosticIdentity("actor", context?.actor);
195
- const credentialId = diagnosticIdentity("credentialId", context?.credentialId);
196
- const userAgent = boundOptional(context?.userAgent);
197
- const actorSession = boundOptional(context?.actorSession);
198
- const method = boundOptional(context?.method);
199
- const route = boundOptional(context?.route);
200
- return {
201
- ...requestId ? { requestId } : {},
202
- ...actor ? { actor } : {},
203
- ...credentialId ? { credentialId } : {},
204
- ...userAgent ? { userAgent } : {},
205
- ...actorSession ? { actorSession } : {},
206
- ...method ? { method } : {},
207
- ...route ? { route } : {},
208
- ...context?.statusCode === void 0 ? {} : { statusCode: context.statusCode }
209
- };
210
- }
211
- function mergeBindings(parent, child) {
212
- const merged = { ...parent };
213
- if (!isObject(child)) return merged;
214
- for (const key of safeKeys(child).slice(0, 100)) {
215
- const value = safeProperty(child, key);
216
- if (key === "req" || key === "request") Object.assign(merged, normalizeRequest(value));
217
- else if (key === "res" || key === "reply") Object.assign(merged, normalizeReply(value));
218
- else if (key === "reqId") {
219
- merged.reqId = value;
220
- merged.__runtimeRequestId = value;
221
- } else if (!RESERVED_FIELDS.has(key)) merged[key] = value;
222
- }
223
- return merged;
224
- }
225
- function normalizeRequest(value) {
226
- if (!isObject(value)) return {};
227
- const id = asBoundString(safeProperty(value, "id"));
228
- const method = asBoundString(safeProperty(value, "method"));
229
- const routeOptions = safeProperty(value, "routeOptions");
230
- const route = isObject(routeOptions) ? asBoundString(safeProperty(routeOptions, "url")) : void 0;
231
- return {
232
- ...id ? { reqId: id, __runtimeRequestId: id } : {},
233
- ...method ? { method } : {},
234
- ...route ? { route } : {}
235
- };
236
- }
237
- function normalizeReply(value) {
238
- if (!isObject(value)) return {};
239
- const statusCode = safeProperty(value, "statusCode");
240
- return typeof statusCode === "number" && Number.isFinite(statusCode) ? { statusCode } : {};
241
- }
242
- function writeEntry(entry) {
243
- const stream = entry.level === "error" || entry.level === "fatal" ? process.stderr : process.stdout;
244
- const line = IS_TTY ? formatTTY(entry) : JSON.stringify(entry);
245
- try {
246
- stream.write(`${line}
247
- `);
248
- } catch {
249
- }
250
- }
251
- function formatTTY(entry) {
252
- const { ts, level, module, action, msg, ...context } = entry;
253
- const levelTag = level === "fatal" || level === "error" ? "ERR" : level === "warn" ? "WRN" : "INF";
254
- const parts = safeKeys(context).map((key) => `${key}=${safeDisplay(safeProperty(context, key))}`);
255
- return `${ts.slice(11, 19)} ${levelTag} [${module}] ${action}${msg ? ` ${msg}` : ""}${parts.length ? ` ${parts.join(" ")}` : ""}`;
256
- }
257
- function safeDisplay(value) {
258
- try {
259
- return typeof value === "string" ? value : JSON.stringify(value);
260
- } catch {
261
- return "[UNSERIALIZABLE]";
262
- }
263
- }
264
- function safeFormat(message, args) {
265
- try {
266
- return args.length ? format(message, ...args) : message;
267
- } catch {
268
- return message;
269
- }
270
- }
271
- function isObject(value) {
272
- return value !== null && typeof value === "object";
273
- }
274
- function isRecord(value) {
275
- return isObject(value) && !Array.isArray(value);
276
- }
277
- function safeKeys(value) {
278
- try {
279
- return Object.keys(value);
280
- } catch {
281
- return [];
282
- }
283
- }
284
- function safeProperty(value, key) {
285
- try {
286
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
287
- return descriptor && "value" in descriptor ? descriptor.value : void 0;
288
- } catch {
289
- return void 0;
290
- }
291
- }
292
- function copyOwnData(value) {
293
- const output = {};
294
- for (const key of safeKeys(value)) output[key] = safeProperty(value, key);
295
- return output;
296
- }
297
- function boundText(value, fallback) {
298
- return boundOptional(value) ?? fallback;
299
- }
300
- function asBoundString(value) {
301
- return typeof value === "string" ? boundOptional(value) : void 0;
302
- }
303
- function boundOptional(value) {
304
- if (typeof value !== "string") return void 0;
305
- const redacted = redactLogString(value).replace(/[\r\n]+/g, " ").trim().slice(0, MAX_IDENTITY_LENGTH);
306
- return redacted || void 0;
307
- }
308
-
309
- // src/intelligence-service.ts
310
50
  var RECURRENCE_LOOKBACK_RUNS = 5;
311
51
  var HISTORY_WINDOW_RUNS = Math.max(PERSISTENT_GAP_THRESHOLD, 5);
312
52
  var log = createLogger("IntelligenceService");
@@ -1026,9 +766,6 @@ var IntelligenceService = class {
1026
766
  };
1027
767
 
1028
768
  export {
1029
- addLogListener,
1030
- createLogger,
1031
- createFastifyLogger,
1032
769
  HISTORY_WINDOW_RUNS,
1033
770
  IntelligenceService
1034
771
  };