logquill 0.3.0 → 0.4.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.
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import { createHash } from 'crypto';
1
+ import { randomUUID, randomBytes, createHash } from 'crypto';
2
+ import { AsyncLocalStorage } from 'async_hooks';
3
+ import { createRequire } from 'module';
2
4
  import { gzipSync } from 'zlib';
3
5
  import { mkdirSync, openSync, writeSync, fstatSync, closeSync, existsSync, unlinkSync, renameSync } from 'fs';
4
6
  import { dirname } from 'path';
@@ -80,6 +82,99 @@ var ContextPlugin = class {
80
82
  return { ...record, meta: { ...this.context, ...record.meta } };
81
83
  }
82
84
  };
85
+ var RunPlugin = class {
86
+ runId;
87
+ step = 0;
88
+ constructor(options = {}) {
89
+ this.runId = options.runId ?? randomUUID();
90
+ }
91
+ beforeLog(record) {
92
+ record.meta.runId ??= this.runId;
93
+ record.meta.step = this.step++;
94
+ return record;
95
+ }
96
+ };
97
+ var traceparentStore = new AsyncLocalStorage();
98
+ function setTraceparent(value) {
99
+ const previous = traceparentStore.getStore();
100
+ traceparentStore.enterWith(value);
101
+ return () => {
102
+ traceparentStore.enterWith(previous);
103
+ };
104
+ }
105
+ function getTraceparent() {
106
+ return traceparentStore.getStore();
107
+ }
108
+ function generateTraceId() {
109
+ return randomBytes(16).toString("hex");
110
+ }
111
+ var W3C_TRACEPARENT_RE = /^[0-9a-f]{2}-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/;
112
+ var XRAY_ROOT_RE = /Root=1-([0-9a-f]{8})-([0-9a-f]{24})/;
113
+ var GCP_TRACE_RE = /^([0-9a-f]{32})\/\d+(;o=\d)?$/;
114
+ function parseTraceHeader(header) {
115
+ const trimmed = header.trim();
116
+ const w3c = W3C_TRACEPARENT_RE.exec(trimmed);
117
+ if (w3c?.[1]) {
118
+ return w3c[1];
119
+ }
120
+ const xray = XRAY_ROOT_RE.exec(trimmed);
121
+ if (xray?.[1] && xray[2]) {
122
+ return xray[1] + xray[2];
123
+ }
124
+ const gcp = GCP_TRACE_RE.exec(trimmed);
125
+ if (gcp?.[1]) {
126
+ return gcp[1];
127
+ }
128
+ return void 0;
129
+ }
130
+ function defaultResolveActiveOtelTraceId() {
131
+ try {
132
+ const require2 = createRequire(import.meta.url);
133
+ const otel = require2("@opentelemetry/api");
134
+ const span = otel.trace.getActiveSpan();
135
+ if (!span) {
136
+ return void 0;
137
+ }
138
+ const spanContext = span.spanContext();
139
+ if (!otel.trace.isSpanContextValid(spanContext)) {
140
+ return void 0;
141
+ }
142
+ return spanContext.traceId;
143
+ } catch {
144
+ return void 0;
145
+ }
146
+ }
147
+ var TraceContextPlugin = class {
148
+ traceKey;
149
+ explicitTraceparent;
150
+ resolveActiveOtelTraceId;
151
+ constructor(options = {}) {
152
+ this.traceKey = options.traceKey ?? "traceId";
153
+ this.explicitTraceparent = options.traceparent;
154
+ this.resolveActiveOtelTraceId = options.resolveActiveOtelTraceId ?? defaultResolveActiveOtelTraceId;
155
+ }
156
+ beforeLog(record) {
157
+ if (record.meta[this.traceKey] != null) {
158
+ return record;
159
+ }
160
+ record.meta[this.traceKey] = this.resolveTraceId();
161
+ return record;
162
+ }
163
+ resolveTraceId() {
164
+ const fromOtel = this.resolveActiveOtelTraceId();
165
+ if (fromOtel) {
166
+ return fromOtel;
167
+ }
168
+ const header = this.explicitTraceparent ?? getTraceparent();
169
+ if (header) {
170
+ const parsed = parseTraceHeader(header);
171
+ if (parsed) {
172
+ return parsed;
173
+ }
174
+ }
175
+ return generateTraceId();
176
+ }
177
+ };
83
178
 
84
179
  // src/plugins/redact-plugin.ts
85
180
  var DEFAULT_REDACTED_KEYS = ["password", "token", "secret", "api_key", "authorization"];
@@ -1708,8 +1803,24 @@ var HTTPTransport = class extends Transport {
1708
1803
  this.flush();
1709
1804
  }
1710
1805
  };
1806
+ var spanIdStore = new AsyncLocalStorage();
1807
+ function currentSpanId() {
1808
+ return spanIdStore.getStore();
1809
+ }
1810
+ function newSpanId() {
1811
+ return randomBytes(8).toString("hex");
1812
+ }
1813
+ function runInSpan(spanId, fn) {
1814
+ return spanIdStore.run(spanId, fn);
1815
+ }
1711
1816
 
1712
1817
  // src/core/logger.ts
1818
+ function formatSpanError(error) {
1819
+ if (error instanceof Error) {
1820
+ return `${error.name}: ${error.message}`;
1821
+ }
1822
+ return String(error);
1823
+ }
1713
1824
  var Logger = class _Logger {
1714
1825
  name;
1715
1826
  transports;
@@ -1773,6 +1884,10 @@ var Logger = class _Logger {
1773
1884
  message,
1774
1885
  meta: { ...this.baseMeta, ...meta }
1775
1886
  });
1887
+ const parentSpanId = currentSpanId();
1888
+ if (parentSpanId !== void 0) {
1889
+ record.meta.parentSpanId ??= parentSpanId;
1890
+ }
1776
1891
  for (const plugin of this.plugins) {
1777
1892
  let result;
1778
1893
  try {
@@ -1787,7 +1902,11 @@ var Logger = class _Logger {
1787
1902
  record = result;
1788
1903
  }
1789
1904
  for (const transport of this.transports) {
1790
- transport.write(transport.format(record), record);
1905
+ try {
1906
+ transport.write(transport.format(record), record);
1907
+ } catch (error) {
1908
+ console.error(`${transport.constructor.name}: failed to write a log record`, error);
1909
+ }
1791
1910
  }
1792
1911
  for (const plugin of this.plugins) {
1793
1912
  try {
@@ -1816,11 +1935,71 @@ var Logger = class _Logger {
1816
1935
  fatal(message, meta = {}) {
1817
1936
  return this.dispatch(50 /* FATAL */, message, meta);
1818
1937
  }
1938
+ /** `.info()` tagged `meta.kind = "thought"` — an agent's internal reasoning step, for harness/agentic tracing. */
1939
+ thought(message, meta = {}) {
1940
+ return this.dispatch(20 /* INFO */, message, { kind: "thought", ...meta });
1941
+ }
1942
+ /** `.info()` tagged `meta.kind = "action"` — an agent taking an action (a tool call, an LLM request), for harness/agentic tracing. */
1943
+ action(message, meta = {}) {
1944
+ return this.dispatch(20 /* INFO */, message, { kind: "action", ...meta });
1945
+ }
1946
+ /** `.info()` tagged `meta.kind = "observation"` — the result an agent observed from an action, for harness/agentic tracing. */
1947
+ observation(message, meta = {}) {
1948
+ return this.dispatch(20 /* INFO */, message, { kind: "observation", ...meta });
1949
+ }
1950
+ /** `.info()` tagged `meta.kind = "decision"` — an agent's concluding decision for a step or run, for harness/agentic tracing. */
1951
+ decision(message, meta = {}) {
1952
+ return this.dispatch(20 /* INFO */, message, { kind: "decision", ...meta });
1953
+ }
1954
+ /**
1955
+ * `await logger.span("callLlm", async () => {...})` — runs `fn`, and on
1956
+ * settling (success or throw) emits one record for the span itself
1957
+ * carrying `meta.spanId` and `meta.durationMs`. Every record logged
1958
+ * inside `fn` — through any method, and through any further `await` —
1959
+ * is automatically stamped with `meta.parentSpanId` pointing at this
1960
+ * span, so nested/sub-agent calls reconstruct their exact nesting when
1961
+ * sorted by `spanId`/`parentSpanId`.
1962
+ *
1963
+ * Still emits its record — at `ERROR`, with `meta.error` set — if `fn`
1964
+ * throws; the error itself propagates unchanged to the caller.
1965
+ *
1966
+ * `spanId`/`parentSpanId` normally auto-generate/auto-nest; pass them in
1967
+ * `options` to adopt an id handed in from elsewhere (e.g. a framework
1968
+ * adapter translating an id it already received).
1969
+ */
1970
+ async span(name, fn, options = {}) {
1971
+ const { spanId: explicitSpanId, parentSpanId: explicitParentSpanId, ...meta } = options;
1972
+ const spanId = explicitSpanId ?? newSpanId();
1973
+ const start = performance.now();
1974
+ try {
1975
+ const result = await runInSpan(spanId, () => fn());
1976
+ this.finishSpan(name, spanId, explicitParentSpanId, performance.now() - start, meta);
1977
+ return result;
1978
+ } catch (error) {
1979
+ this.finishSpan(name, spanId, explicitParentSpanId, performance.now() - start, meta, error);
1980
+ throw error;
1981
+ }
1982
+ }
1983
+ finishSpan(name, spanId, explicitParentSpanId, durationMs, meta, error) {
1984
+ const fullMeta = {
1985
+ spanId,
1986
+ durationMs: Math.round(durationMs * 1e3) / 1e3,
1987
+ ...meta
1988
+ };
1989
+ if (explicitParentSpanId !== void 0) {
1990
+ fullMeta.parentSpanId = explicitParentSpanId;
1991
+ }
1992
+ fullMeta.kind ??= "span";
1993
+ if (error !== void 0) {
1994
+ fullMeta.error = formatSpanError(error);
1995
+ }
1996
+ this.dispatch(error !== void 0 ? 40 /* ERROR */ : 20 /* INFO */, name, fullMeta);
1997
+ }
1819
1998
  };
1820
1999
 
1821
2000
  // src/index.ts
1822
2001
  var VERSION = "0.3.0";
1823
2002
 
1824
- export { AlertingPlugin, AppInsightsTransport, BaseQueueTransport, BaseSQLTransport, BatchingTransport, CloudLoggingTransport, CloudWatchTransport, CollectingTransport, ConsoleTransport, ContextPlugin, DEFAULT_PII_PATTERNS, DEFAULT_REDACTED_KEYS, DatadogTransport, DynamoDBTransport, ElasticsearchTransport, EmailAlertPlugin, FileTransport, FunctionPlugin, GENESIS_HASH, HTTPTransport, JSONFormatter, KafkaTransport, Level, Logger, MongoDBTransport, MySQLTransport, NewRelicTransport, PIIRedactPlugin, PagerDutyAlertPlugin, PostgresTransport, PubSubTransport, RabbitMQTransport, RedactPlugin, RedisTransport, SQLiteTransport, SQSTransport, SamplingPlugin, SlackAlertPlugin, TamperEvidentPlugin, Transport, VERSION, createRecord, levelName, parseLevel, utcTimestamp };
2003
+ export { AlertingPlugin, AppInsightsTransport, BaseQueueTransport, BaseSQLTransport, BatchingTransport, CloudLoggingTransport, CloudWatchTransport, CollectingTransport, ConsoleTransport, ContextPlugin, DEFAULT_PII_PATTERNS, DEFAULT_REDACTED_KEYS, DatadogTransport, DynamoDBTransport, ElasticsearchTransport, EmailAlertPlugin, FileTransport, FunctionPlugin, GENESIS_HASH, HTTPTransport, JSONFormatter, KafkaTransport, Level, Logger, MongoDBTransport, MySQLTransport, NewRelicTransport, PIIRedactPlugin, PagerDutyAlertPlugin, PostgresTransport, PubSubTransport, RabbitMQTransport, RedactPlugin, RedisTransport, RunPlugin, SQLiteTransport, SQSTransport, SamplingPlugin, SlackAlertPlugin, TamperEvidentPlugin, TraceContextPlugin, Transport, VERSION, createRecord, defaultResolveActiveOtelTraceId, generateTraceId, getTraceparent, levelName, parseLevel, parseTraceHeader, setTraceparent, utcTimestamp };
1825
2004
  //# sourceMappingURL=index.mjs.map
1826
2005
  //# sourceMappingURL=index.mjs.map