@jini-ai/diagnostics 0.1.1 → 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.
Files changed (67) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +114 -0
  3. package/dist/agent-logs.d.ts +9 -4
  4. package/dist/agent-logs.js +14 -15
  5. package/dist/domain-dns/index.d.ts +136 -0
  6. package/dist/domain-dns/index.js +117 -0
  7. package/dist/index.d.ts +41 -3
  8. package/dist/index.js +38 -1
  9. package/dist/manifest.d.ts +22 -16
  10. package/dist/manifest.js +9 -19
  11. package/dist/node-ports.d.ts +6 -0
  12. package/dist/node-ports.js +57 -0
  13. package/dist/observability/config.d.ts +24 -0
  14. package/dist/observability/config.js +21 -0
  15. package/dist/observability/hooks.d.ts +18 -0
  16. package/dist/observability/hooks.js +24 -0
  17. package/dist/observability/index.d.ts +14 -0
  18. package/dist/observability/index.js +14 -0
  19. package/dist/observability/noop.d.ts +4 -0
  20. package/dist/observability/noop.js +6 -0
  21. package/dist/observability/otel.d.ts +14 -0
  22. package/dist/observability/otel.js +28 -0
  23. package/dist/observability/ports.d.ts +79 -0
  24. package/dist/observability/ports.js +2 -0
  25. package/dist/ports.d.ts +45 -0
  26. package/dist/ports.js +2 -0
  27. package/dist/redaction/secret-patterns.d.ts +8 -0
  28. package/dist/redaction/secret-patterns.js +18 -0
  29. package/dist/redaction/secrets-only.d.ts +44 -0
  30. package/dist/redaction/secrets-only.js +179 -0
  31. package/dist/redaction.d.ts +12 -3
  32. package/dist/redaction.js +18 -8
  33. package/dist/sources.d.ts +22 -12
  34. package/dist/sources.js +22 -42
  35. package/dist/types.d.ts +24 -0
  36. package/dist/types.js +2 -0
  37. package/dist/web-evidence/browser-port.d.ts +166 -0
  38. package/dist/web-evidence/browser-port.js +6 -0
  39. package/dist/web-evidence/collect-page-evidence.d.ts +160 -0
  40. package/dist/web-evidence/collect-page-evidence.js +215 -0
  41. package/dist/web-evidence/index.d.ts +5 -0
  42. package/dist/web-evidence/index.js +5 -0
  43. package/dist/web-evidence/page-structure-script.d.ts +53 -0
  44. package/dist/web-evidence/page-structure-script.js +338 -0
  45. package/dist/web-evidence/page-work-budget.d.ts +27 -0
  46. package/dist/web-evidence/page-work-budget.js +53 -0
  47. package/dist/web-evidence/playwright-browser.d.ts +131 -0
  48. package/dist/web-evidence/playwright-browser.js +349 -0
  49. package/dist/web-evidence/same-origin.d.ts +126 -0
  50. package/dist/web-evidence/same-origin.js +141 -0
  51. package/dist/zip.d.ts +8 -3
  52. package/dist/zip.js +23 -16
  53. package/package.json +46 -5
  54. package/dist/agent-logs.d.ts.map +0 -1
  55. package/dist/agent-logs.js.map +0 -1
  56. package/dist/contract.d.ts.map +0 -1
  57. package/dist/contract.js.map +0 -1
  58. package/dist/index.d.ts.map +0 -1
  59. package/dist/index.js.map +0 -1
  60. package/dist/manifest.d.ts.map +0 -1
  61. package/dist/manifest.js.map +0 -1
  62. package/dist/redaction.d.ts.map +0 -1
  63. package/dist/redaction.js.map +0 -1
  64. package/dist/sources.d.ts.map +0 -1
  65. package/dist/sources.js.map +0 -1
  66. package/dist/zip.d.ts.map +0 -1
  67. package/dist/zip.js.map +0 -1
package/dist/index.js CHANGED
@@ -4,9 +4,45 @@
4
4
  * Diagnostics-bundle tooling shared by any host application's HTTP and desktop
5
5
  * export surfaces: endpoint constants, JSON/text secret redaction, log-source
6
6
  * collection (incl. macOS crash reports and coding-agent CLI logs), a manifest
7
- * builder, and a zip packager. See `source-map.md` for full provenance and
7
+ * builder, and a zip packager. See `archived provenance ledger` for full provenance and
8
8
  * scope-decision notes (this package is NOT yet in extraction-plan.md's
9
9
  * locked §3 package set — see that file for details).
10
+
11
+ * Archived provenance rationale:
12
+ * ## Design decision: `agent-logs.ts` carries real agent-CLI vocabulary, ported anyway
13
+ *
14
+ * `r2-packages.md`'s coupling grade for this package ("LOW... daemon-endpoint
15
+ * comments") was assessed at the whole-package level. Read in isolation,
16
+ * `agent-logs.ts` carries more domain content than the other six files: it
17
+ * hardcodes knowledge of four specific coding-agent CLIs — Claude Code, Codex,
18
+ * OpenCode, and an "AMR"-style OpenCode runtime — including their default
19
+ * config-home directory names (`.claude`, `.codex`, `opencode`) and env-var
20
+ * override names (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `OPENCODE_TEST_HOME`,
21
+ * `XDG_DATA_HOME`). "AMR" itself is OD's own internal name for an agent
22
+ * orchestration layer, not a generic term.
23
+ *
24
+ * This was ported anyway, deliberately, not dropped or trimmed, for three
25
+ * reasons: (1) the task brief explicitly lists `agent-logs` as one of the
26
+ * seven modules that make up "diagnostics-bundle tooling" and does not flag it
27
+ * for exclusion the way Target 2's task brief explicitly excluded
28
+ * `project-storage.ts`; (2) every one of these CLI integrations is optional
29
+ * and caller-parameterized (`homeDir`/`claudeConfigDir`/`codexHome`/
30
+ * `amrOpenCodeHome`/`xdgDataHome` are all inputs, not hardcoded paths the
31
+ * function reaches for on its own) — a Jini-based product that drives the same
32
+ * external agent CLIs (Claude Code, Codex, OpenCode are all plausible
33
+ * `@jini/agent-runtime` targets per extraction-plan.md's roadmap) can reuse
34
+ * this verbatim, and one that doesn't simply never calls
35
+ * `buildAgentCliLogSources`; (3) the "AMR" agent slot is additive-only (only
36
+ * appended to `agentDirs` when `amrOpenCodeHome`/`dataDir` is supplied) so a
37
+ * non-OD consumer never sees it activate. Flagged here explicitly rather than
38
+ * silently ported, per this porting session's own standard: a future
39
+ * Coordinator/Software-Architect review of this not-yet-locked package should
40
+ * weigh whether the Claude/Codex/OpenCode/AMR-specific vocabulary belongs in a
41
+ * neutral diagnostics package or should be generalized further (e.g. a
42
+ * caller-supplied list of `{agent, dir}` pairs instead of the four names being
43
+ * baked into the function body). Not resolved here — this is exactly the kind
44
+ * of judgment call flagged for sign-off, not a decision this task should make
45
+ * unilaterally.
10
46
  */
11
47
  export { DIAGNOSTICS_CONTENT_TYPE, DIAGNOSTICS_EXPORT_PATH, DIAGNOSTICS_FILENAME_PREFIX, } from "./contract.js";
12
48
  export { redactJsonValue, redactJsonText, redactText, } from "./redaction.js";
@@ -14,4 +50,5 @@ export { collectLogSource, collectLogSources, findMacOSCrashReports, } from "./s
14
50
  export { buildManifest, buildMachineInfo, diagnosticsFileName, } from "./manifest.js";
15
51
  export { buildDiagnosticsZip, } from "./zip.js";
16
52
  export { buildRunEventLogSources, buildAgentCliLogSources, } from "./agent-logs.js";
53
+ export { createNodeDiagnosticsPorts } from "./node-ports.js";
17
54
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,7 @@
1
- import type { CollectedFile } from "./sources.js";
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ import type { DiagnosticsSystemPort } from "./ports.js";
3
+ import type { CollectedFile, MachineInfo } from "./types.js";
4
+ export type { MachineInfo } from "./types.js";
2
5
  export interface DiagnosticsAppInfo {
3
6
  name: string;
4
7
  version?: string | undefined;
@@ -41,20 +44,23 @@ export interface DiagnosticsManifest {
41
44
  warnings: string[];
42
45
  extra?: Record<string, unknown> | undefined;
43
46
  }
44
- export interface MachineInfo {
45
- hostname: string;
46
- platform: string;
47
- release: string;
48
- arch: string;
49
- type: string;
50
- totalMemoryBytes: number;
51
- nodeVersion: string;
52
- pid: number;
53
- ppid: number;
54
- cwd: string;
47
+ /** Combines file and host warnings using only the caller's clock for the export timestamp. */
48
+ export declare function buildManifest({ context, files, clock }: {
49
+ context: DiagnosticsContext;
50
+ files: CollectedFile[];
51
+ clock: Clock;
52
+ }): DiagnosticsManifest;
53
+ /** Reads the injected machine snapshot and adds the caller's optional username. */
54
+ export declare function buildMachineInfo({ system }: {
55
+ system: DiagnosticsSystemPort;
56
+ }, { username }?: {
55
57
  username?: string | undefined;
56
- }
57
- export declare function buildManifest(context: DiagnosticsContext, files: CollectedFile[]): DiagnosticsManifest;
58
- export declare function buildMachineInfo(username: string | undefined): MachineInfo;
59
- export declare function diagnosticsFileName(prefix: string, now?: Date): string;
58
+ }): MachineInfo;
59
+ /** Uses an explicit date override or the supplied clock; never reads the ambient clock. */
60
+ export declare function diagnosticsFileName({ prefix, clock }: {
61
+ prefix: string;
62
+ clock: Clock;
63
+ }, { now }?: {
64
+ now?: Date;
65
+ }): string;
60
66
  //# sourceMappingURL=manifest.d.ts.map
package/dist/manifest.js CHANGED
@@ -1,12 +1,12 @@
1
- import { arch, hostname, platform, release, totalmem, type } from "node:os";
2
- export function buildManifest(context, files) {
1
+ /** Combines file and host warnings using only the caller's clock for the export timestamp. */
2
+ export function buildManifest({ context, files, clock }) {
3
3
  const warnings = [...(context.warnings ?? [])];
4
4
  for (const file of files) {
5
5
  if (file.error)
6
6
  warnings.push(`${file.name}: ${file.error}`);
7
7
  }
8
8
  return {
9
- exportedAt: new Date().toISOString(),
9
+ exportedAt: new Date(clock.nowMs()).toISOString(),
10
10
  app: context.app,
11
11
  source: context.source,
12
12
  namespace: context.namespace,
@@ -22,23 +22,13 @@ export function buildManifest(context, files) {
22
22
  extra: context.extra,
23
23
  };
24
24
  }
25
- export function buildMachineInfo(username) {
26
- return {
27
- hostname: hostname(),
28
- platform: platform(),
29
- release: release(),
30
- arch: arch(),
31
- type: type(),
32
- totalMemoryBytes: totalmem(),
33
- nodeVersion: process.version,
34
- pid: process.pid,
35
- ppid: process.ppid,
36
- cwd: process.cwd(),
37
- username,
38
- };
25
+ /** Reads the injected machine snapshot and adds the caller's optional username. */
26
+ export function buildMachineInfo({ system }, { username } = {}) {
27
+ return { ...system.machineInfo({}), username };
39
28
  }
40
- export function diagnosticsFileName(prefix, now = new Date()) {
41
- const iso = now.toISOString().replace(/[:.]/g, "-").replace(/-\d{3}Z$/, "Z");
29
+ /** Uses an explicit date override or the supplied clock; never reads the ambient clock. */
30
+ export function diagnosticsFileName({ prefix, clock }, { now } = {}) {
31
+ const iso = (now ?? new Date(clock.nowMs())).toISOString().replace(/[:.]/g, "-").replace(/-\d{3}Z$/, "Z");
42
32
  return `${prefix}-${iso}.zip`;
43
33
  }
44
34
  //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,6 @@
1
+ import type { DiagnosticsPorts } from "./ports.js";
2
+ /** Explicit Node/JSZip adapter. Hosts opt into local filesystem and process access here.
3
+ * Tail reads retain bounded memory usage and always close the file descriptor.
4
+ */
5
+ export declare function createNodeDiagnosticsPorts(_required: Record<string, never>): DiagnosticsPorts;
6
+ //# sourceMappingURL=node-ports.d.ts.map
@@ -0,0 +1,57 @@
1
+ import { open, readFile, readdir, stat } from "node:fs/promises";
2
+ import { arch, hostname, platform, release, totalmem, type } from "node:os";
3
+ import JSZip from "jszip";
4
+ /** Explicit Node/JSZip adapter. Hosts opt into local filesystem and process access here.
5
+ * Tail reads retain bounded memory usage and always close the file descriptor.
6
+ */
7
+ export function createNodeDiagnosticsPorts(_required) {
8
+ return {
9
+ filesystem: {
10
+ async readFile({ absolutePath }, { tailBytes } = {}) {
11
+ if (tailBytes == null || tailBytes <= 0)
12
+ return await readFile(absolutePath);
13
+ const info = await stat(absolutePath);
14
+ if (info.size <= tailBytes)
15
+ return await readFile(absolutePath);
16
+ const fd = await open(absolutePath, "r");
17
+ try {
18
+ const buffer = Buffer.alloc(tailBytes);
19
+ const { bytesRead } = await fd.read(buffer, 0, tailBytes, info.size - tailBytes);
20
+ return buffer.subarray(0, bytesRead);
21
+ }
22
+ finally {
23
+ await fd.close();
24
+ }
25
+ },
26
+ async readDirectory({ absolutePath }) {
27
+ return (await readdir(absolutePath, { withFileTypes: true }))
28
+ .map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory() }));
29
+ },
30
+ async stat({ absolutePath }) {
31
+ const info = await stat(absolutePath);
32
+ return { isFile: info.isFile(), mtimeMs: info.mtimeMs };
33
+ },
34
+ },
35
+ clock: { nowMs: () => Date.now() },
36
+ system: {
37
+ platform: () => process.platform,
38
+ machineInfo: () => ({
39
+ hostname: hostname(), platform: platform(), release: release(), arch: arch(),
40
+ type: type(), totalMemoryBytes: totalmem(), nodeVersion: process.version,
41
+ pid: process.pid, ppid: process.ppid, cwd: process.cwd(),
42
+ }),
43
+ },
44
+ archiveFactory: {
45
+ create() {
46
+ const zip = new JSZip();
47
+ return {
48
+ file({ name, content }) { zip.file(name, content); },
49
+ async generate() {
50
+ return await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } });
51
+ },
52
+ };
53
+ },
54
+ },
55
+ };
56
+ }
57
+ //# sourceMappingURL=node-ports.js.map
@@ -0,0 +1,24 @@
1
+ export interface ObservabilityConfigDisabled {
2
+ enabled: false;
3
+ }
4
+ export interface ObservabilityConfigEnabled {
5
+ enabled: true;
6
+ serviceName: string;
7
+ tracerName: string;
8
+ endpoint: string;
9
+ }
10
+ export type ObservabilityConfig = ObservabilityConfigDisabled | ObservabilityConfigEnabled;
11
+ /** Resolves explicit OTLP settings. Traces endpoint wins; general endpoint gets /v1/traces.
12
+ * @param required Caller-owned service and tracer identity.
13
+ * @param options Explicit endpoints; absence disables telemetry.
14
+ * @returns Enabled configuration or the disabled variant. Never reads environment or globals.
15
+ * @throws TypeError when enabled identities are blank.
16
+ */
17
+ export declare function resolveObservabilityConfig({ serviceName, tracerName }: {
18
+ serviceName: string;
19
+ tracerName: string;
20
+ }, { endpoint, tracesEndpoint }?: {
21
+ endpoint?: string;
22
+ tracesEndpoint?: string;
23
+ }): ObservabilityConfig;
24
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,21 @@
1
+ /** Resolves explicit OTLP settings. Traces endpoint wins; general endpoint gets /v1/traces.
2
+ * @param required Caller-owned service and tracer identity.
3
+ * @param options Explicit endpoints; absence disables telemetry.
4
+ * @returns Enabled configuration or the disabled variant. Never reads environment or globals.
5
+ * @throws TypeError when enabled identities are blank.
6
+ */
7
+ export function resolveObservabilityConfig({ serviceName, tracerName }, { endpoint, tracesEndpoint } = {}) {
8
+ const traces = tracesEndpoint?.trim();
9
+ const base = endpoint?.trim();
10
+ // Endpoint presence is the opt-in; a host without collector configuration stays off by default.
11
+ if (!traces && !base)
12
+ return { enabled: false };
13
+ if (!serviceName.trim())
14
+ throw new TypeError('serviceName must be non-empty');
15
+ if (!tracerName.trim())
16
+ throw new TypeError('tracerName must be non-empty');
17
+ // A signal-specific endpoint already names its route; the general endpoint needs /v1/traces.
18
+ // Treating the general endpoint as complete would send traces to the collector's wrong route.
19
+ return { enabled: true, serviceName: serviceName.trim(), tracerName: tracerName.trim(), endpoint: traces || `${base.replace(/\/+$/, '')}/v1/traces` };
20
+ }
21
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,18 @@
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ import type { RequestIdGenerator, RequestLogPort, RequestMetricsPort, ObservabilityPort } from './ports.js';
3
+ export interface RequestHookOptions {
4
+ logger?: RequestLogPort;
5
+ metrics?: RequestMetricsPort;
6
+ tracing?: ObservabilityPort;
7
+ }
8
+ /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
9
+ * @param required Clock and request ID generator, scoped by the host.
10
+ * @param options Optional logging, metrics and tracing adapters.
11
+ * @returns Request tracking with exactly one completion event per request.
12
+ * @throws Hook errors propagate to the caller; adapters choose their own error policy.
13
+ */
14
+ export declare function createHookObservabilityPort({ clock, requestIdGenerator }: {
15
+ clock: Clock;
16
+ requestIdGenerator: RequestIdGenerator;
17
+ }, { logger, metrics, tracing }?: RequestHookOptions): ObservabilityPort;
18
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1,24 @@
1
+ /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
2
+ * @param required Clock and request ID generator, scoped by the host.
3
+ * @param options Optional logging, metrics and tracing adapters.
4
+ * @returns Request tracking with exactly one completion event per request.
5
+ * @throws Hook errors propagate to the caller; adapters choose their own error policy.
6
+ */
7
+ export function createHookObservabilityPort({ clock, requestIdGenerator }, { logger, metrics, tracing } = {}) {
8
+ return { trackRequest(input, options = {}) {
9
+ const requestId = options.requestId ?? requestIdGenerator.generate({});
10
+ const startedAt = clock.nowMs();
11
+ const tracker = tracing?.trackRequest(input, { requestId });
12
+ let ended = false;
13
+ return { requestId, end(outcome) {
14
+ if (ended)
15
+ return;
16
+ ended = true;
17
+ const event = { requestId, method: input.method, ...outcome, durationMs: Math.max(0, clock.nowMs() - startedAt) };
18
+ tracker?.end(outcome);
19
+ logger?.log(event);
20
+ metrics?.recordRequest(event);
21
+ } };
22
+ } };
23
+ }
24
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1,14 @@
1
+ import type { ObservabilityConfig } from './config.js';
2
+ import type { ExporterFactory, TracerProviderFactory, ObservabilityPort } from './ports.js';
3
+ export * from './config.js';
4
+ export * from './ports.js';
5
+ export * from './noop.js';
6
+ export * from './otel.js';
7
+ export * from './hooks.js';
8
+ /** Selects an adapter from explicit config; disabled telemetry never invokes either factory. */
9
+ export declare function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }: {
10
+ config: ObservabilityConfig;
11
+ exporterFactory: ExporterFactory;
12
+ tracerProviderFactory: TracerProviderFactory;
13
+ }): ObservabilityPort;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { createNoopObservabilityPort } from './noop.js';
2
+ import { createOtelObservabilityPort } from './otel.js';
3
+ export * from './config.js';
4
+ export * from './ports.js';
5
+ export * from './noop.js';
6
+ export * from './otel.js';
7
+ export * from './hooks.js';
8
+ /** Selects an adapter from explicit config; disabled telemetry never invokes either factory. */
9
+ export function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }) {
10
+ if (!config.enabled)
11
+ return createNoopObservabilityPort({});
12
+ return createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory });
13
+ }
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,4 @@
1
+ import type { ObservabilityPort } from './ports.js';
2
+ /** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
3
+ export declare function createNoopObservabilityPort(_required: Record<string, never>): ObservabilityPort;
4
+ //# sourceMappingURL=noop.d.ts.map
@@ -0,0 +1,6 @@
1
+ const NOOP_TRACKER = Object.freeze({ end() { } });
2
+ /** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
3
+ export function createNoopObservabilityPort(_required) {
4
+ return { trackRequest: () => NOOP_TRACKER };
5
+ }
6
+ //# sourceMappingURL=noop.js.map
@@ -0,0 +1,14 @@
1
+ import type { ObservabilityConfigEnabled } from './config.js';
2
+ import type { ExporterFactory, TracerProviderFactory, ObservabilityPort } from './ports.js';
3
+ export interface OtelAdapterDependencies {
4
+ config: ObservabilityConfigEnabled;
5
+ exporterFactory: ExporterFactory;
6
+ tracerProviderFactory: TracerProviderFactory;
7
+ }
8
+ /** Builds request spans through injected provider/exporter factories. Hosts wrap their SDK here.
9
+ * @param required Explicit config and structural factories.
10
+ * @returns One adapter whose request spans end once, with the final route name and status.
11
+ * @throws Provider/exporter errors propagate during setup. No globals or SDK imports are used.
12
+ */
13
+ export declare function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }: OtelAdapterDependencies): ObservabilityPort;
14
+ //# sourceMappingURL=otel.d.ts.map
@@ -0,0 +1,28 @@
1
+ /** Builds request spans through injected provider/exporter factories. Hosts wrap their SDK here.
2
+ * @param required Explicit config and structural factories.
3
+ * @returns One adapter whose request spans end once, with the final route name and status.
4
+ * @throws Provider/exporter errors propagate during setup. No globals or SDK imports are used.
5
+ */
6
+ export function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }) {
7
+ const exporter = exporterFactory.create({ endpoint: config.endpoint });
8
+ const provider = tracerProviderFactory.create({ serviceName: config.serviceName, exporter });
9
+ const tracer = provider.getTracer({ name: config.tracerName });
10
+ return { trackRequest(input) {
11
+ const span = tracer.startSpan({ name: input.method, kind: 'server', attributes: { 'http.method': input.method, 'http.target': input.path } });
12
+ let ended = false;
13
+ return { end(outcome) {
14
+ if (ended)
15
+ return;
16
+ ended = true;
17
+ // Routing finishes after startSpan, so open with a provisional name and assign the final
18
+ // pattern at end. The consumer port needs no separate rename operation to express that timing.
19
+ span.updateName({ name: `${input.method} ${outcome.routePattern}` });
20
+ span.setAttribute({ name: 'http.route', value: outcome.routePattern });
21
+ span.setAttribute({ name: 'http.status_code', value: outcome.statusCode });
22
+ if (outcome.statusCode >= 500)
23
+ span.setStatus({ code: 'error' });
24
+ span.end({});
25
+ } };
26
+ } };
27
+ }
28
+ //# sourceMappingURL=otel.js.map
@@ -0,0 +1,79 @@
1
+ /** Vendor-neutral inbound request lifecycle. Route patterns, rather than raw paths, label metrics. */
2
+ /**
3
+ * Consumers speak in request lifecycle terms rather than Span/Tracer SDK types. That permits
4
+ * replacing the instrumentation system itself, not merely its exporter backend. Add signals
5
+ * only against real instrumentation call sites; guessed DB/outbound/agent shapes would couple
6
+ * consumers to contracts whose lifecycle has not yet been established.
7
+ */
8
+ export interface RequestTrackingInput {
9
+ method: string;
10
+ path: string;
11
+ }
12
+ export interface RequestTrackingOptions {
13
+ requestId?: string;
14
+ }
15
+ /** The mount-aware pattern is available only after routing; raw paths are known at request start.
16
+ * Use a fixed 'unmatched' label for misses: attacker-controlled paths would make grouping unbounded. */
17
+ export interface RequestTrackingOutcome {
18
+ statusCode: number;
19
+ routePattern: string;
20
+ }
21
+ export interface RequestTracker {
22
+ readonly requestId?: string;
23
+ end(outcome: RequestTrackingOutcome): void;
24
+ }
25
+ export interface ObservabilityPort {
26
+ trackRequest(input: RequestTrackingInput, options?: RequestTrackingOptions): RequestTracker;
27
+ }
28
+ export interface RequestObservation extends RequestTrackingOutcome {
29
+ requestId: string;
30
+ method: string;
31
+ durationMs: number;
32
+ }
33
+ export interface RequestLogPort {
34
+ log(event: RequestObservation): void;
35
+ }
36
+ export interface RequestMetricsPort {
37
+ recordRequest(event: RequestObservation): void;
38
+ }
39
+ export interface RequestIdGenerator {
40
+ generate(required: Record<string, never>): string;
41
+ }
42
+ /** Structural SDK adapters are host-owned; no provider registration or ambient config is used. */
43
+ export interface TraceSpanPort {
44
+ updateName(required: {
45
+ name: string;
46
+ }): void;
47
+ setAttribute(required: {
48
+ name: string;
49
+ value: string | number;
50
+ }): void;
51
+ setStatus(required: {
52
+ code: 'error';
53
+ }): void;
54
+ end(required: Record<string, never>): void;
55
+ }
56
+ export interface TracerPort {
57
+ startSpan(required: {
58
+ name: string;
59
+ kind: 'server';
60
+ attributes: Record<string, string | number>;
61
+ }): TraceSpanPort;
62
+ }
63
+ export interface TracerProviderPort {
64
+ getTracer(required: {
65
+ name: string;
66
+ }): TracerPort;
67
+ }
68
+ export interface ExporterFactory {
69
+ create(required: {
70
+ endpoint: string;
71
+ }): unknown;
72
+ }
73
+ export interface TracerProviderFactory {
74
+ create(required: {
75
+ serviceName: string;
76
+ exporter: unknown;
77
+ }): TracerProviderPort;
78
+ }
79
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,45 @@
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ import type { MachineInfo } from "./types.js";
3
+ /** Host effects used by bundle collection. Core functions never read ambient host state. */
4
+ export interface DiagnosticsFilesystemPort {
5
+ /** Read the full file or a bounded trailing window without loading the full large file. */
6
+ readFile(required: {
7
+ absolutePath: string;
8
+ }, optional?: {
9
+ tailBytes?: number | undefined;
10
+ }): Promise<Buffer>;
11
+ readDirectory(required: {
12
+ absolutePath: string;
13
+ }): Promise<Array<{
14
+ name: string;
15
+ isDirectory: boolean;
16
+ }>>;
17
+ stat(required: {
18
+ absolutePath: string;
19
+ }): Promise<{
20
+ isFile: boolean;
21
+ mtimeMs: number;
22
+ }>;
23
+ }
24
+ export interface DiagnosticsSystemPort {
25
+ platform(required: Record<string, never>): string;
26
+ machineInfo(required: Record<string, never>): Omit<MachineInfo, "username">;
27
+ }
28
+ export interface DiagnosticsArchivePort {
29
+ file(required: {
30
+ name: string;
31
+ content: string;
32
+ }): void;
33
+ generate(required: Record<string, never>): Promise<Buffer>;
34
+ }
35
+ export interface DiagnosticsArchiveFactoryPort {
36
+ /** Every invocation returns a fresh archive so successive exports cannot share files. */
37
+ create(required: Record<string, never>): DiagnosticsArchivePort;
38
+ }
39
+ export interface DiagnosticsPorts {
40
+ filesystem: DiagnosticsFilesystemPort;
41
+ clock: Clock;
42
+ system: DiagnosticsSystemPort;
43
+ archiveFactory: DiagnosticsArchiveFactoryPort;
44
+ }
45
+ //# sourceMappingURL=ports.d.ts.map
package/dist/ports.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,8 @@
1
+ /** Credential-shape vocabulary for secret-only redaction; no I/O or host dependencies. */
2
+ export interface SecretPattern {
3
+ readonly name: string;
4
+ readonly pattern: RegExp;
5
+ }
6
+ export declare const PEM_PATTERN_NAME = "PEM private key block";
7
+ export declare const SECRET_PATTERNS: readonly SecretPattern[];
8
+ //# sourceMappingURL=secret-patterns.d.ts.map
@@ -0,0 +1,18 @@
1
+ /** Credential-shape vocabulary for secret-only redaction; no I/O or host dependencies. */
2
+ // Named once and reused (by SECRET_PATTERNS here and by the guard's ALLOWLIST) rather than repeated
3
+ // as a literal in multiple places.
4
+ export const PEM_PATTERN_NAME = "PEM private key block";
5
+ export const SECRET_PATTERNS = [
6
+ { name: "Google API key (AIza)", pattern: /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9_-])/ },
7
+ { name: "Anthropic API key (sk-ant-)", pattern: /(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{90,}/ },
8
+ { name: "generic sk- secret key (OpenAI-shaped)", pattern: /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{40,}/ },
9
+ { name: "GitHub personal access token (classic, ghp_)", pattern: /(?<!\w)ghp_\w{36}(?!\w)/ },
10
+ { name: "GitHub OAuth token (gho_)", pattern: /(?<!\w)gho_\w{36}(?!\w)/ },
11
+ { name: "GitHub fine-grained PAT", pattern: /(?<!\w)github_pat_\w{80,}/ },
12
+ { name: "npm access token", pattern: /(?<!\w)npm_\w{36}(?!\w)/ },
13
+ { name: "Slack token", pattern: /(?<![A-Za-z0-9-])xox[baprs]-[A-Za-z0-9-]{12,}/ },
14
+ { name: "AWS access key ID", pattern: /(?<![0-9A-Z])AKIA[0-9A-Z]{16}(?![0-9A-Z])/ },
15
+ { name: "Fastmail app password (fm2_)", pattern: /(?<![A-Za-z0-9+/=])fm2_[A-Za-z0-9+/=]{20,}/ },
16
+ { name: PEM_PATTERN_NAME, pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
17
+ ];
18
+ //# sourceMappingURL=secret-patterns.js.map
@@ -0,0 +1,44 @@
1
+ /** Secret-only error-display policy. Preserves paths, network addresses, emails, timestamps,
2
+ * tool IDs and ordinary prose. Ordered rules are idempotent; product formats come from policy. */
3
+ /** One (text in, text + count out) redaction pass. `redactions` is the number of values blanked —
4
+ * zero for text with nothing secret-shaped in it. */
5
+ export interface SecretRedaction {
6
+ readonly text: string;
7
+ readonly redactions: number;
8
+ }
9
+ /** One ordered rule: a global pattern and how to rebuild its replacement from the match's capture
10
+ * groups. Private — callers only ever see {@link redactSecretShapes}'s aggregate result. */
11
+ export interface RedactionRule {
12
+ readonly kind: string;
13
+ readonly pattern: RegExp;
14
+ readonly replacement: (required: {
15
+ match: readonly (string | undefined)[];
16
+ }) => string;
17
+ }
18
+ /**
19
+ * Blanks every secret-shaped VALUE in `text`, leaving everything else — including IPs, absolute
20
+ * paths, emails, tool ids, and ordinary prose — untouched.
21
+ *
22
+ * @param required - Text and the caller's redaction policy. The text is arbitrary error text. Never re-interpreted as anything other than plain text (no
23
+ * parsing, no partial JSON awareness).
24
+ * @returns The redacted text plus how many values were blanked. `redactions: 0` means nothing
25
+ * secret-shaped was found — the returned `text` is then reference-identical in content (though
26
+ * not necessarily the same string instance) to the input.
27
+ * @complexity O(r*n): each of the fixed, small rule count `r` makes one linear pass over the
28
+ * (at most `n`-length) text. Rules only ever shrink or hold text length steady, so the total work
29
+ * is bounded by `r` passes over the original length.
30
+ * @example
31
+ * redactSecretShapes({ text: "password=hunter2hunter2", policy: {} }); // { text: "password=[REDACTED:labeled_secret]", redactions: 1 }
32
+ * @overallScore 100
33
+ */
34
+ export interface RedactionPolicy {
35
+ /** Rules for caller-owned formats, applied after vendor/JWT rules and before bearer/labeled rules. Must be idempotent. */
36
+ readonly additionalRules?: readonly RedactionRule[];
37
+ }
38
+ /** Redacts credential values with a required policy; returns text and replacement count. */
39
+ export declare function redactSecretShapes({ text, policy }: {
40
+ text: string;
41
+ policy: RedactionPolicy;
42
+ }): SecretRedaction;
43
+ export { SECRET_SHAPE_PATTERNS as SECRET_PATTERNS, PEM_PATTERN_NAME, type SecretShapePattern as SecretPattern } from "@jini-ai/core";
44
+ //# sourceMappingURL=secrets-only.d.ts.map