@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/CHANGELOG.md ADDED
@@ -0,0 +1,79 @@
1
+ # @jini-ai/diagnostics
2
+
3
+ ## 0.4.0 — 2026-10-02
4
+
5
+ ### BREAKING
6
+
7
+ - Observability clocks and conservative secret patterns come from core; evidence copy is neutral and adapters remain isolated.
8
+ - Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
9
+
10
+ ## Unreleased
11
+
12
+ - **BREAKING:** Remove local `ClockPort`/`DiagnosticsClockPort`; all clocks use `Clock.nowMs()` from `@jini-ai/core/primitives`. Add core as a package dependency.
13
+ - Share the eleven byte-pinned credential patterns with core while retaining all redaction/scanner export names and diagnostics-specific policy. Bundle text and JSON redaction also mask standalone provider credential shapes; ordinary IDs, hashes and paths stay readable.
14
+ - Off-origin evidence copy now says "the inspected origin".
15
+
16
+
17
+ - **BREAKING:** All 12 existing root functions now take a required-argument object and, when applicable, a separate optional-settings object. Filesystem, clock, machine snapshot and archive creation use injected ports. `createNodeDiagnosticsPorts({})` supplies the Node/JSZip adapter. Previous positional signatures have no compatibility wrappers; export names and the package version remain unchanged.
18
+ - Complete publication metadata for `./redaction/secrets-only`, `./observability`, `./web-evidence`, `./web-evidence/playwright` and `./domain-dns`, with per-entry runtime declarations. The first three subpaths are universal; the root, browser adapter and DNS checks require Node. Existing exports are retained.
19
+ - Add current API migration documentation and package-wide source-neutrality and export/barrel contract tests. Application-key redaction rules, telemetry SDK adapters, authorization and transport policy remain caller-owned. The earlier integration step required no new dependency; shared kernel adoption above adds core.
20
+
21
+ - Add secret-only redaction, explicitly configured observability, bounded browser evidence with an optional Playwright subpath, and public DNS/TLS checks. New APIs use required-argument and optional-argument objects with injected ports; existing root exports and version stay unchanged.
22
+
23
+ ## 0.1.2
24
+
25
+ ### Patch Changes
26
+
27
+ - Add top-level `main`/`types` fields alongside the existing `exports` map. A consumer on
28
+ TypeScript's classic `moduleResolution: "node"` (node10) — which ignores `package.json#exports`
29
+ entirely — could not resolve this package's types at all (`TS2307: Cannot find module`) even
30
+ after the previous exports-map fix restored `require()` at runtime; type resolution and runtime
31
+ resolution are separate algorithms. Verified against a real external consumer (whose
32
+ tsconfig uses this legacy resolution mode): adding these two fields, with its tsconfig completely
33
+ unchanged, made the error disappear. Also fixes absolute-path `require()` (distinct from a bare
34
+ specifier, which already worked) for the same reason — `main` was previously absent.
35
+
36
+ Purely additive: every modern resolver (Node's own runtime `exports` resolution, TypeScript's
37
+ `bundler`/`node16`/`nodenext`) prefers `exports` over `main`/`types` when both are present, so
38
+ this changes nothing for a consumer already on a modern resolver.
39
+
40
+ ## 0.1.1
41
+
42
+ ### Patch Changes
43
+
44
+ - Add a `"default"` export condition to every published package's `exports` map — every one of
45
+ them lacked it, which meant `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED` for any
46
+ CommonJS consumer (found via a real external integration attempt; Node needs `require(esm)`
47
+ support, i.e. Node >=22.12, for this to resolve).
48
+
49
+ `@jini-ai/agent-runtime`:
50
+
51
+ - **New**: `RuntimeBuildOptions.permissionMode` (`'bypass' | 'restricted'`) lets a caller opt a
52
+ run OUT of the auto-approve-every-permission-prompt flag every def with one
53
+ (`bypassPermissions` / `--yolo` / `--dangerously-skip-permissions`) previously pushed
54
+ unconditionally, with no way to turn it off. Omitting it keeps today's default (bypass)
55
+ behavior unchanged.
56
+ - **New**: `ClaudeStreamEvent`, `CopilotStreamEvent`, and `QoderEvent` are now real exported
57
+ discriminated unions instead of `Record<string, unknown>` — a real external consumer guessed a
58
+ nonexistent field name (`event.text` instead of the actual `event.delta`) against the old
59
+ untyped sink and silently lost every streamed token with no compile or runtime error.
60
+ - Fixed a doc/implementation mismatch in `claude-stream.ts`: the module doc claimed `tool_result`
61
+ events carry `{ tool_use_id, content, is_error }`; the actual emitted shape is
62
+ `{ toolUseId, content, isError }`.
63
+
64
+ `@jini-ai/daemon`: `AgentExecutorRunInput.permissionMode` forwards the new
65
+ `RuntimeBuildOptions.permissionMode` through to `buildArgs`, so a host can actually reach the new
66
+ opt-out from the daemon's real run-input surface, not just from `@jini-ai/agent-runtime` in
67
+ isolation.
68
+
69
+ `@jini-ai/agentic`: `setAtPointer` no longer throws on a malformed (e.g. missing leading `/`)
70
+ `updateDataModel` path — degrades to a no-op like its sibling `getAtPointer`, matching this
71
+ package's own "a bad binding must not crash the renderer" contract. That path is agent-authored
72
+ wire data with no error boundary above it in any host, so the uncaught throw could unmount an
73
+ entire chat UI from ~40 bytes of malformed input.
74
+
75
+ `@jini-ai/chat-react`: a local (client-resolved) A2UI button action is no longer a silent no-op —
76
+ `A2uiSurfaceCard` now surfaces the resolved value. New `ExtEventErrorBoundary` confines a
77
+ `kind: 'ext'` event group's renderer to its own card instead of letting a render/effect-phase
78
+ throw from agent-controlled content unmount the whole chat root (there was no error boundary
79
+ anywhere in this package or its hosts before this).
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # `@jini-ai/diagnostics`
2
+
3
+ > **Current API:** the root functions use required-argument objects, separate optional settings and injected host ports. See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/diagnostics/API.md) for all signatures, current examples and the five new subpaths. The descriptions and Usage example retained below document the earlier positional API; use the migration guide for the current source. Root export names and the version remain unchanged, but the old call signatures require migration.
4
+
5
+ Builds a redacted support bundle: collect a list of log sources off disk, strip anything
6
+ secret-shaped out of them, add a manifest describing the machine and the app that produced them, and
7
+ zip the whole thing. Meant for the "export diagnostics" button in a desktop app or the
8
+ `/api/diagnostics/export` route in a daemon — the two surfaces that otherwise reimplement the same
9
+ redaction pass and get it subtly different. Shared clocks and credential patterns come from `@jini-ai/core`; archive creation uses `jszip`.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @jini-ai/diagnostics
15
+ ```
16
+
17
+ No peer dependencies. `jszip` is a regular dependency (pure JS — no native compile), installed
18
+ automatically.
19
+
20
+ ## What you get
21
+
22
+ **The one-call export** — `buildDiagnosticsZip(input)` → `{ zip: Buffer, manifest, machineInfo }`.
23
+ `DiagnosticsExportInput` takes a `DiagnosticsContext`, the `LogSource[]` to collect, optional
24
+ `RedactionOptions`, and an optional `CrashReportLookup` that adds matching macOS crash reports to the
25
+ bundle. A source that fails to read becomes a placeholder file inside the zip rather than failing the
26
+ whole export.
27
+
28
+ **Redaction** — `redactText`, `redactJsonText`, and `redactJsonValue` (walks a parsed structure,
29
+ redacting secret-shaped keys and values), with `RedactionOptions` carrying an optional `username` to
30
+ scrub from paths. This is the part that must not be reimplemented per surface.
31
+
32
+ **Log-source collection** — `LogSource` (`{ name, absolutePath, kind: 'json' | 'text', tailBytes? }`),
33
+ `LogSourceKind`, `CollectedFile`, with `collectLogSource` (one) and `collectLogSources` (many), plus
34
+ `findMacOSCrashReports(lookup)`. Two higher-level builders turn domain concepts into sources:
35
+ `buildRunEventLogSources` and `buildAgentCliLogSources(options)` (coding-agent CLI logs, via
36
+ `AgentCliLogOptions`).
37
+
38
+ **Manifest** — `buildManifest`, `buildMachineInfo`, and `diagnosticsFileName(prefix, now?)`, with
39
+ `DiagnosticsManifest` / `DiagnosticsContext` / `DiagnosticsAppInfo` / `MachineInfo`.
40
+ `DiagnosticsContext` carries `app` plus a `source` naming which surface triggered the export
41
+ (`'daemon-http'`, `'desktop-ipc'`, …) and an optional `warnings` array, so "file logs are unavailable
42
+ in this launch mode" surfaces as a real note instead of fake missing-file entries.
43
+
44
+ **Transport constants** — `DIAGNOSTICS_EXPORT_PATH`, `DIAGNOSTICS_CONTENT_TYPE`, and
45
+ `DIAGNOSTICS_FILENAME_PREFIX`, so an HTTP route and its client agree on the endpoint and the
46
+ download filename without either hardcoding a string.
47
+
48
+ ## Usage
49
+
50
+ ```ts
51
+ import {
52
+ buildDiagnosticsZip,
53
+ DIAGNOSTICS_CONTENT_TYPE,
54
+ DIAGNOSTICS_FILENAME_PREFIX,
55
+ diagnosticsFileName,
56
+ redactText,
57
+ type LogSource,
58
+ } from '@jini-ai/diagnostics';
59
+
60
+ const sources: LogSource[] = [
61
+ { name: 'logs/daemon.log', absolutePath: '/var/log/example/daemon.log', kind: 'text' },
62
+ { name: 'logs/events.json', absolutePath: '/var/log/example/events.json', kind: 'json', tailBytes: 512_000 },
63
+ ];
64
+
65
+ const { zip, manifest } = await buildDiagnosticsZip({
66
+ context: {
67
+ app: { name: 'example', version: '1.2.3', packaged: true },
68
+ source: 'daemon-http',
69
+ endpoint: 'http://127.0.0.1:4173',
70
+ },
71
+ sources,
72
+ redaction: { username: 'alice' },
73
+ crashReports: { matchSubstrings: ['example'], withinDays: 7, maxReports: 20 },
74
+ });
75
+
76
+ // e.g. from an Express handler
77
+ res.setHeader('Content-Type', DIAGNOSTICS_CONTENT_TYPE);
78
+ res.setHeader(
79
+ 'Content-Disposition',
80
+ `attachment; filename="${diagnosticsFileName(DIAGNOSTICS_FILENAME_PREFIX)}"`,
81
+ );
82
+ res.end(zip);
83
+
84
+ // Or use the redactor on its own, before logging something.
85
+ const safe = redactText('Authorization: Bearer sk-live-abc123');
86
+ ```
87
+
88
+ ## What's swappable
89
+
90
+ None of the redaction rules — that is deliberate. `RedactionOptions` carries only a `username` to
91
+ scrub from paths; the secret-key and secret-value patterns are fixed, because a bundle that redacts
92
+ less than another surface's bundle is a leak, and a per-caller override is exactly how that drift
93
+ starts. What *is* yours: the `LogSource[]` (which files end up in a bundle is entirely your decision,
94
+ and `buildRunEventLogSources` / `buildAgentCliLogSources` are conveniences rather than a required
95
+ path) and every field of `DiagnosticsContext`. There are no DI tokens and no injected filesystem —
96
+ collection uses `node:fs` directly.
97
+
98
+ ## Runtime
99
+
100
+ `jini.runtime: "node"` — reads real files via `node:fs`, and `buildMachineInfo` reads `node:os`.
101
+ ESM only — ships `"type": "module"` with no CommonJS `require` build.
102
+
103
+ ## Provenance
104
+
105
+ See the archived provenance ledger for per-file provenance and scope decisions. Apache-2.0,
106
+ inherited from Open Design — see the repo `NOTICE`.
107
+
108
+ See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/diagnostics/API.md) for the additive redaction, observability, web-evidence and domain-dns subpaths and host adapter contracts.
109
+
110
+ ## Design decisions
111
+
112
+ - [Build evidence URLs from verified host configuration](docs/decisions/DR-001-trusted-evidence-addresses.md).
113
+
114
+ Bundle collection, inbound request hooks and web evidence share `Clock` from `@jini-ai/core/primitives` (`nowMs()` with no empty argument); the old package-local clock types are removed. Credential regexes come only from core's eleven-entry `SECRET_SHAPE_PATTERNS`; diagnostics keeps its own redaction policies and existing scanner/redactor export names. See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/diagnostics/API.md) for migration details.
@@ -1,3 +1,4 @@
1
+ import type { DiagnosticsFilesystemPort } from "./ports.js";
1
2
  import type { LogSource } from "./sources.js";
2
3
  /**
3
4
  * Collect the most-recent per-run event logs (`<runsDir>/<runId>/events.jsonl`).
@@ -7,13 +8,14 @@ import type { LogSource } from "./sources.js";
7
8
  * run failed / produced nothing". Shared so both an HTTP export and a desktop
8
9
  * IPC export bundle the same data.
9
10
  */
10
- export declare function buildRunEventLogSources(runsDir: string | null | undefined, options?: {
11
+ export declare function buildRunEventLogSources({ runsDir, filesystem }: {
12
+ runsDir: string | null | undefined;
13
+ filesystem: DiagnosticsFilesystemPort;
14
+ }, options?: {
11
15
  maxRuns?: number;
12
16
  tailBytes?: number;
13
17
  }): Promise<LogSource[]>;
14
18
  export interface AgentCliLogOptions {
15
- /** User home directory; CLI configs/logs live under here. */
16
- homeDir: string;
17
19
  /** Host application data dir; fallback location of an AMR-style OpenCode home. */
18
20
  dataDir?: string | null;
19
21
  /**
@@ -52,5 +54,8 @@ export interface AgentCliLogOptions {
52
54
  * or session transcripts — and the collected text still passes through the
53
55
  * bundle's redaction pass.
54
56
  */
55
- export declare function buildAgentCliLogSources(options: AgentCliLogOptions): Promise<LogSource[]>;
57
+ export declare function buildAgentCliLogSources({ homeDir, filesystem }: {
58
+ homeDir: string;
59
+ filesystem: DiagnosticsFilesystemPort;
60
+ }, options?: AgentCliLogOptions): Promise<LogSource[]>;
56
61
  //# sourceMappingURL=agent-logs.d.ts.map
@@ -1,4 +1,3 @@
1
- import { readdir, stat } from "node:fs/promises";
2
1
  import { join } from "node:path";
3
2
  const DEFAULT_RUN_EVENT_TAIL_BYTES = 2 * 1024 * 1024;
4
3
  const DEFAULT_MAX_RUN_EVENT_LOGS = 20;
@@ -8,10 +7,10 @@ const DEFAULT_MAX_RUN_EVENT_LOGS = 20;
8
7
  const DEFAULT_AGENT_LOG_TAIL_BYTES = 2 * 1024 * 1024;
9
8
  const DEFAULT_MAX_FILES_PER_AGENT = 3;
10
9
  const SAFE_DIR_ENTRY = /^[A-Za-z0-9._-]+$/u;
11
- async function statSafe(path) {
10
+ async function statSafe(path, filesystem) {
12
11
  try {
13
- const info = await stat(path);
14
- return { mtimeMs: info.mtimeMs, isFile: info.isFile() };
12
+ const info = await filesystem.stat({ absolutePath: path });
13
+ return { mtimeMs: info.mtimeMs, isFile: info.isFile };
15
14
  }
16
15
  catch {
17
16
  return null;
@@ -25,26 +24,26 @@ async function statSafe(path) {
25
24
  * run failed / produced nothing". Shared so both an HTTP export and a desktop
26
25
  * IPC export bundle the same data.
27
26
  */
28
- export async function buildRunEventLogSources(runsDir, options = {}) {
27
+ export async function buildRunEventLogSources({ runsDir, filesystem }, options = {}) {
29
28
  if (!runsDir)
30
29
  return [];
31
30
  const maxRuns = options.maxRuns ?? DEFAULT_MAX_RUN_EVENT_LOGS;
32
31
  const tailBytes = options.tailBytes ?? DEFAULT_RUN_EVENT_TAIL_BYTES;
33
32
  let entries;
34
33
  try {
35
- entries = await readdir(runsDir, { withFileTypes: true });
34
+ entries = await filesystem.readDirectory({ absolutePath: runsDir });
36
35
  }
37
36
  catch {
38
37
  return [];
39
38
  }
40
39
  const candidates = [];
41
40
  for (const entry of entries) {
42
- if (!entry.isDirectory())
41
+ if (!entry.isDirectory)
43
42
  continue;
44
43
  if (!SAFE_DIR_ENTRY.test(entry.name))
45
44
  continue;
46
45
  const absolutePath = join(runsDir, entry.name, "events.jsonl");
47
- const info = await statSafe(absolutePath);
46
+ const info = await statSafe(absolutePath, filesystem);
48
47
  if (!info || !info.isFile)
49
48
  continue;
50
49
  candidates.push({ runId: entry.name, absolutePath, mtimeMs: info.mtimeMs });
@@ -57,22 +56,22 @@ export async function buildRunEventLogSources(runsDir, options = {}) {
57
56
  tailBytes,
58
57
  }));
59
58
  }
60
- async function latestLogFilesIn(dir, max) {
59
+ async function latestLogFilesIn(dir, max, filesystem) {
61
60
  let names;
62
61
  try {
63
- names = await readdir(dir);
62
+ names = await filesystem.readDirectory({ absolutePath: dir });
64
63
  }
65
64
  catch {
66
65
  return [];
67
66
  }
68
67
  const candidates = [];
69
- for (const name of names) {
68
+ for (const { name } of names) {
70
69
  if (!name.endsWith(".log"))
71
70
  continue;
72
71
  if (!SAFE_DIR_ENTRY.test(name))
73
72
  continue;
74
73
  const absolutePath = join(dir, name);
75
- const info = await statSafe(absolutePath);
74
+ const info = await statSafe(absolutePath, filesystem);
76
75
  if (!info || !info.isFile)
77
76
  continue;
78
77
  candidates.push({ name, absolutePath, mtimeMs: info.mtimeMs });
@@ -92,8 +91,8 @@ async function latestLogFilesIn(dir, max) {
92
91
  * or session transcripts — and the collected text still passes through the
93
92
  * bundle's redaction pass.
94
93
  */
95
- export async function buildAgentCliLogSources(options) {
96
- const home = options.homeDir?.trim();
94
+ export async function buildAgentCliLogSources({ homeDir, filesystem }, options = {}) {
95
+ const home = homeDir?.trim();
97
96
  if (!home)
98
97
  return [];
99
98
  const maxFiles = options.maxFilesPerAgent ?? DEFAULT_MAX_FILES_PER_AGENT;
@@ -135,7 +134,7 @@ export async function buildAgentCliLogSources(options) {
135
134
  }
136
135
  const sources = [];
137
136
  for (const { agent, dir } of agentDirs) {
138
- const files = await latestLogFilesIn(dir, maxFiles);
137
+ const files = await latestLogFilesIn(dir, maxFiles, filesystem);
139
138
  for (const file of files) {
140
139
  sources.push({
141
140
  name: `agent-cli-logs/${agent}/${file.name}`,
@@ -0,0 +1,136 @@
1
+ /** Validation error independent of any tool framework. */
2
+ export declare class DomainDnsInputError extends Error {
3
+ constructor({ message }: {
4
+ message: string;
5
+ });
6
+ }
7
+ /** Public DNS only. The composition root supplies a resolver that cannot inspect internal DNS. */
8
+ export declare const DNS_TYPES: readonly ["A", "AAAA", "CNAME", "MX", "TXT", "NS"];
9
+ export type DnsRecordType = typeof DNS_TYPES[number];
10
+ export interface DnsQuery {
11
+ type: DnsRecordType;
12
+ status: "ok" | "not-found" | "no-data";
13
+ records: Array<{
14
+ value: string;
15
+ ttl: number;
16
+ }>;
17
+ }
18
+ export interface PublicDnsResolver {
19
+ query(input: {
20
+ domain: string;
21
+ type: DnsRecordType;
22
+ }): Promise<DnsQuery>;
23
+ }
24
+ export interface TlsStatus {
25
+ status: "verified" | "invalid" | "unavailable";
26
+ httpStatus: number | null;
27
+ }
28
+ export type DomainDnsOperation = 'lookup-dns' | 'check-dns' | 'tls-status';
29
+ export interface DomainDnsDependencies {
30
+ authorize(required: {
31
+ operation: DomainDnsOperation;
32
+ }): Promise<void>;
33
+ resolver: PublicDnsResolver;
34
+ /** Workspace-scoped saved publishing hostnames, not caller-supplied expectations. */
35
+ listExpectedHosts(required: Record<string, never>): Promise<string[]>;
36
+ probeTls(input: {
37
+ domain: string;
38
+ }): Promise<TlsStatus>;
39
+ }
40
+ /**
41
+ * Normalizes a public hostname before any effect.
42
+ * @param required Hostname text and the caller's error-message prefix.
43
+ * @returns Canonical ASCII hostname.
44
+ * @throws {DomainDnsInputError} For URLs, IPs, ports, invalid labels, or reserved/internal suffixes.
45
+ * @complexity O(length) time and space.
46
+ * @example readPublicDomain({ value: "EXAMPLE.COM.", errorPrefix: "DNS" }); // example.com
47
+ */
48
+ export declare function readPublicDomain({ value, errorPrefix }: {
49
+ value: unknown;
50
+ errorPrefix: string;
51
+ }): string;
52
+ /**
53
+ * Normalizes public DNS owner names, including ACME, DKIM, and DMARC underscores.
54
+ * @returns Canonical ASCII owner name; TLS and hosting inputs use readPublicDomain instead.
55
+ * @throws {DomainDnsInputError} For URLs, IPs, invalid labels, or reserved/internal suffixes.
56
+ * @complexity O(length) time and space.
57
+ * @example readPublicDnsName({ value: "_acme-challenge.example.com", errorPrefix: "DNS" });
58
+ */
59
+ export declare function readPublicDnsName({ value, errorPrefix }: {
60
+ value: unknown;
61
+ errorPrefix: string;
62
+ }): string;
63
+ /** Compares all advertised addresses, so one correct record cannot hide a wrong IPv6 route. O(r log r) time, O(r) space; at most five bounded DNS queries. */
64
+ declare function checkHost(deps: DomainDnsDependencies, domain: string, selected: unknown): Promise<{
65
+ domain: string;
66
+ status: "unknown";
67
+ expectedHost: null;
68
+ reason: string;
69
+ untrusted: true;
70
+ expectationSource?: never;
71
+ expected?: never;
72
+ observed?: never;
73
+ unexpected?: never;
74
+ missing?: never;
75
+ limitation?: never;
76
+ } | {
77
+ domain: string;
78
+ expectedHost: string;
79
+ status: "unknown" | "mismatch" | "matches-host-dns";
80
+ expectationSource: "host-dns";
81
+ expected: {
82
+ A: string[];
83
+ AAAA: string[];
84
+ };
85
+ observed: {
86
+ A: string[];
87
+ AAAA: string[];
88
+ CNAME: string[];
89
+ };
90
+ unexpected: {
91
+ A: string[];
92
+ AAAA: string[];
93
+ };
94
+ missing: {
95
+ A: string[];
96
+ AAAA: string[];
97
+ };
98
+ untrusted: true;
99
+ limitation: string;
100
+ reason?: never;
101
+ }>;
102
+ export interface DomainDnsChecks {
103
+ lookupDns(required: {
104
+ domain: unknown;
105
+ }, options?: {
106
+ types?: unknown;
107
+ }): Promise<{
108
+ domain: string;
109
+ resolver: 'public-dns';
110
+ untrusted: true;
111
+ queries: DnsQuery[];
112
+ }>;
113
+ checkDns(required: {
114
+ domain: unknown;
115
+ }, options?: {
116
+ expectedHost?: unknown;
117
+ }): Promise<Awaited<ReturnType<typeof checkHost>>>;
118
+ tlsStatus(required: {
119
+ domain: unknown;
120
+ }): Promise<TlsStatus & {
121
+ domain: string;
122
+ certificate: {
123
+ expiresAt: null;
124
+ issuer: null;
125
+ };
126
+ limitation: string;
127
+ }>;
128
+ }
129
+ /** Builds three bounded read operations without CMS/tool registration.
130
+ * @param deps Required public-network, hosting-source and authorization ports.
131
+ * @returns DNS lookup/comparison and TLS status checks. Validation precedes authorization and I/O.
132
+ * @throws DomainDnsInputError for invalid inputs; authorization and transport failures propagate.
133
+ */
134
+ export declare function createDomainDnsChecks(deps: DomainDnsDependencies): DomainDnsChecks;
135
+ export {};
136
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,117 @@
1
+ import { isIP } from "node:net";
2
+ import { domainToASCII } from "node:url";
3
+ /** Validation error independent of any tool framework. */
4
+ export class DomainDnsInputError extends Error {
5
+ constructor({ message }) { super(message); this.name = "DomainDnsInputError"; }
6
+ }
7
+ /** Public DNS only. The composition root supplies a resolver that cannot inspect internal DNS. */
8
+ export const DNS_TYPES = ["A", "AAAA", "CNAME", "MX", "TXT", "NS"];
9
+ /**
10
+ * Normalizes a public hostname before any effect.
11
+ * @param required Hostname text and the caller's error-message prefix.
12
+ * @returns Canonical ASCII hostname.
13
+ * @throws {DomainDnsInputError} For URLs, IPs, ports, invalid labels, or reserved/internal suffixes.
14
+ * @complexity O(length) time and space.
15
+ * @example readPublicDomain({ value: "EXAMPLE.COM.", errorPrefix: "DNS" }); // example.com
16
+ */
17
+ export function readPublicDomain({ value, errorPrefix }) {
18
+ return readPublicName(value, errorPrefix);
19
+ }
20
+ /**
21
+ * Normalizes public DNS owner names, including ACME, DKIM, and DMARC underscores.
22
+ * @returns Canonical ASCII owner name; TLS and hosting inputs use readPublicDomain instead.
23
+ * @throws {DomainDnsInputError} For URLs, IPs, invalid labels, or reserved/internal suffixes.
24
+ * @complexity O(length) time and space.
25
+ * @example readPublicDnsName({ value: "_acme-challenge.example.com", errorPrefix: "DNS" });
26
+ */
27
+ export function readPublicDnsName({ value, errorPrefix }) {
28
+ return readPublicName(value, errorPrefix, { allowUnderscores: true });
29
+ }
30
+ /** Shared normalization keeps URL/IP/internal-name refusals identical for both kinds of public name. */
31
+ function readPublicName(value, toolId, options = {}) {
32
+ const invalid = () => new DomainDnsInputError({ message: `${toolId}: pass a public DNS hostname such as 'example.com', without a URL, IP address, path, or port.` });
33
+ if (typeof value !== "string" || value.length > 254 || value.trim() !== value || /[/\\?#@:%\[\]\s]/u.test(value))
34
+ throw invalid();
35
+ const domain = domainToASCII(value.replace(/\.$/, "")).toLowerCase();
36
+ const labels = domain.split(".");
37
+ const labelPattern = options.allowUnderscores ? /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/ : /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
38
+ const validLabels = labels.every(label => labelPattern.test(label));
39
+ const validSuffix = /^[a-z][a-z0-9-]*$/.test(labels.at(-1));
40
+ const reservedName = /\.(?:local|localhost|internal|invalid|test|onion)$/.test(domain);
41
+ if (!domain || domain.length > 253 || isIP(domain) || labels.length < 2 || !validLabels || !validSuffix || reservedName)
42
+ throw invalid();
43
+ return domain;
44
+ }
45
+ /** Checks the bounded record type selection without silently dropping unknown/duplicate types. */
46
+ function readTypes(value) {
47
+ if (value === undefined)
48
+ return [...DNS_TYPES];
49
+ if (!Array.isArray(value) || value.length < 1 || value.length > 6 || new Set(value).size !== value.length || !value.every(type => DNS_TYPES.includes(type))) {
50
+ throw new DomainDnsInputError({ message: "domain_lookup_dns: types must be a non-empty list of distinct A, AAAA, CNAME, MX, TXT, or NS record types." });
51
+ }
52
+ return value;
53
+ }
54
+ /** Sequential bounded fan-out keeps a single tool call to at most six DNS requests. O(records). */
55
+ async function queryTypes(resolver, domain, types) {
56
+ const queries = [];
57
+ for (const type of types)
58
+ queries.push(await resolver.query({ domain, type }));
59
+ return queries;
60
+ }
61
+ /** Canonicalizes address spelling (including compressed IPv6) for set comparison. O(r log r) time and O(r) space for r records. */
62
+ function recordValues(queries, type) {
63
+ const records = queries.find(query => query.type === type)?.records ?? [];
64
+ return [...new Set(records.map(({ value }) => type === "AAAA" ? new URL(`https://[${value}]/`).hostname.slice(1, -1) : value.toLowerCase().replace(/\.$/, "")))].sort();
65
+ }
66
+ /** Set difference preserves the normalized record order. O(left + right) time and space. */
67
+ function difference(left, right) {
68
+ const expected = new Set(right);
69
+ return left.filter(value => !expected.has(value));
70
+ }
71
+ const UNKNOWN_REASON = "No independent hosting hostname is available.";
72
+ /** Compares all advertised addresses, so one correct record cannot hide a wrong IPv6 route. O(r log r) time, O(r) space; at most five bounded DNS queries. */
73
+ async function checkHost(deps, domain, selected) {
74
+ const hosts = [...new Set(await deps.listExpectedHosts({}))].filter(host => host !== domain).sort();
75
+ if (hosts.length === 0 && selected === undefined)
76
+ return { domain, status: "unknown", expectedHost: null, reason: UNKNOWN_REASON, untrusted: true };
77
+ const expectedHost = selected === undefined && hosts.length === 1 ? hosts[0] : selected;
78
+ if (typeof expectedHost !== "string" || !hosts.includes(expectedHost)) {
79
+ throw new DomainDnsInputError({ message: `domain_check_dns: choose expectedHost from the saved hosting hostnames: ${hosts.join(", ") || "(none)"}.` });
80
+ }
81
+ const actualQueries = await queryTypes(deps.resolver, domain, ["A", "AAAA", "CNAME"]);
82
+ const hostQueries = await queryTypes(deps.resolver, expectedHost, ["A", "AAAA"]);
83
+ const expected = { A: recordValues(hostQueries, "A"), AAAA: recordValues(hostQueries, "AAAA") };
84
+ const observed = { A: recordValues(actualQueries, "A"), AAAA: recordValues(actualQueries, "AAAA"), CNAME: recordValues(actualQueries, "CNAME") };
85
+ const unexpected = { A: difference(observed.A, expected.A), AAAA: difference(observed.AAAA, expected.AAAA) };
86
+ const missing = { A: difference(expected.A, observed.A), AAAA: difference(expected.AAAA, observed.AAAA) };
87
+ const hasExpected = expected.A.length + expected.AAAA.length > 0;
88
+ const differs = unexpected.A.length + unexpected.AAAA.length + missing.A.length + missing.AAAA.length > 0;
89
+ return { domain, expectedHost, status: !hasExpected ? "unknown" : differs ? "mismatch" : "matches-host-dns", expectationSource: "host-dns", expected, observed, unexpected, missing, untrusted: true, limitation: "Compares current public DNS, not provider-required records. Shared/CDN addresses do not prove that traffic reaches the correct app." };
90
+ }
91
+ /** Builds three bounded read operations without CMS/tool registration.
92
+ * @param deps Required public-network, hosting-source and authorization ports.
93
+ * @returns DNS lookup/comparison and TLS status checks. Validation precedes authorization and I/O.
94
+ * @throws DomainDnsInputError for invalid inputs; authorization and transport failures propagate.
95
+ */
96
+ export function createDomainDnsChecks(deps) {
97
+ return {
98
+ async lookupDns({ domain: value }, { types: selectedTypes } = {}) {
99
+ const domain = readPublicDnsName({ value, errorPrefix: 'domain_lookup_dns' });
100
+ const types = readTypes(selectedTypes);
101
+ await deps.authorize({ operation: 'lookup-dns' });
102
+ return { domain, resolver: 'public-dns', untrusted: true, queries: await queryTypes(deps.resolver, domain, types) };
103
+ },
104
+ async checkDns({ domain: value }, { expectedHost: selected } = {}) {
105
+ const domain = readPublicDomain({ value, errorPrefix: 'domain_check_dns' });
106
+ const expectedHost = selected === undefined ? undefined : readPublicDomain({ value: selected, errorPrefix: 'domain_check_dns' });
107
+ await deps.authorize({ operation: 'check-dns' });
108
+ return checkHost(deps, domain, expectedHost);
109
+ },
110
+ async tlsStatus({ domain: value }) {
111
+ const domain = readPublicDomain({ value, errorPrefix: 'domain_tls_status' });
112
+ await deps.authorize({ operation: 'tls-status' });
113
+ return { domain, ...await deps.probeTls({ domain }), certificate: { expiresAt: null, issuer: null }, limitation: 'Checks certificate trust, hostname, and validity through HTTPS. Certificate issuer and expiry date are not exposed by this client.' };
114
+ },
115
+ };
116
+ }
117
+ //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -4,14 +4,52 @@
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, type RedactionOptions, } from "./redaction.js";
13
- export { collectLogSource, collectLogSources, findMacOSCrashReports, type CollectedFile, type CrashReportLookup, type LogSource, type LogSourceKind, } from "./sources.js";
49
+ export { collectLogSource, collectLogSources, findMacOSCrashReports, type CollectedFile, type CrashReportLookup, type CrashReportOptions, type LogSource, type LogSourceKind, } from "./sources.js";
14
50
  export { buildManifest, buildMachineInfo, diagnosticsFileName, type DiagnosticsAppInfo, type DiagnosticsContext, type DiagnosticsManifest, type MachineInfo, } from "./manifest.js";
15
- export { buildDiagnosticsZip, type DiagnosticsExportInput, type DiagnosticsExportResult, } from "./zip.js";
51
+ export { buildDiagnosticsZip, type DiagnosticsExportInput, type DiagnosticsExportOptions, type DiagnosticsExportResult, } from "./zip.js";
16
52
  export { buildRunEventLogSources, buildAgentCliLogSources, type AgentCliLogOptions, } from "./agent-logs.js";
53
+ export { createNodeDiagnosticsPorts } from "./node-ports.js";
54
+ export type { DiagnosticsFilesystemPort, DiagnosticsSystemPort, DiagnosticsArchivePort, DiagnosticsArchiveFactoryPort, DiagnosticsPorts } from "./ports.js";
17
55
  //# sourceMappingURL=index.d.ts.map