@apnex/network-adapter 0.1.2 → 0.1.6

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 (86) hide show
  1. package/dist/build-info.json +6 -0
  2. package/dist/file-logger.d.ts +42 -0
  3. package/dist/file-logger.js +122 -0
  4. package/dist/file-logger.js.map +1 -0
  5. package/dist/index.d.ts +37 -13
  6. package/dist/index.js +42 -15
  7. package/dist/index.js.map +1 -1
  8. package/dist/kernel/adapter-config.d.ts +47 -0
  9. package/dist/kernel/adapter-config.js +90 -0
  10. package/dist/kernel/adapter-config.js.map +1 -0
  11. package/dist/kernel/agent-client.d.ts +25 -20
  12. package/dist/kernel/build-identity.d.ts +24 -0
  13. package/dist/kernel/build-identity.js +45 -0
  14. package/dist/kernel/build-identity.js.map +1 -0
  15. package/dist/kernel/event-router.d.ts +22 -1
  16. package/dist/kernel/event-router.js +45 -7
  17. package/dist/kernel/event-router.js.map +1 -1
  18. package/dist/kernel/handshake.d.ts +40 -4
  19. package/dist/kernel/handshake.js +46 -7
  20. package/dist/kernel/handshake.js.map +1 -1
  21. package/dist/kernel/harness-manifest.d.ts +51 -0
  22. package/dist/kernel/harness-manifest.js +96 -0
  23. package/dist/kernel/harness-manifest.js.map +1 -0
  24. package/dist/kernel/liveness-signal.d.ts +35 -0
  25. package/dist/kernel/liveness-signal.js +61 -0
  26. package/dist/kernel/liveness-signal.js.map +1 -0
  27. package/dist/kernel/liveness-watchdog.d.ts +78 -0
  28. package/dist/kernel/liveness-watchdog.js +115 -0
  29. package/dist/kernel/liveness-watchdog.js.map +1 -0
  30. package/dist/kernel/mcp-agent-client.d.ts +2 -2
  31. package/dist/kernel/mcp-agent-client.js +49 -3
  32. package/dist/kernel/mcp-agent-client.js.map +1 -1
  33. package/dist/kernel/poll-backstop.d.ts +134 -4
  34. package/dist/kernel/poll-backstop.js +254 -24
  35. package/dist/kernel/poll-backstop.js.map +1 -1
  36. package/dist/kernel/state-sync.d.ts +2 -13
  37. package/dist/kernel/state-sync.js.map +1 -1
  38. package/dist/notification-log.d.ts +8 -0
  39. package/dist/notification-log.js +10 -0
  40. package/dist/notification-log.js.map +1 -1
  41. package/dist/observability.d.ts +24 -0
  42. package/dist/observability.js +52 -0
  43. package/dist/observability.js.map +1 -0
  44. package/dist/prompt-format.js +82 -9
  45. package/dist/prompt-format.js.map +1 -1
  46. package/dist/tool-manager/catalog/health-revision.d.ts +43 -0
  47. package/dist/tool-manager/catalog/health-revision.js +61 -0
  48. package/dist/tool-manager/catalog/health-revision.js.map +1 -0
  49. package/dist/tool-manager/{tool-catalog-cache.d.ts → catalog/tool-catalog-cache.d.ts} +39 -19
  50. package/dist/tool-manager/{tool-catalog-cache.js → catalog/tool-catalog-cache.js} +53 -26
  51. package/dist/tool-manager/catalog/tool-catalog-cache.js.map +1 -0
  52. package/dist/tool-manager/catalog/tool-surface-reconciler.d.ts +93 -0
  53. package/dist/tool-manager/catalog/tool-surface-reconciler.js +101 -0
  54. package/dist/tool-manager/catalog/tool-surface-reconciler.js.map +1 -0
  55. package/dist/tool-manager/contracts.d.ts +91 -0
  56. package/dist/tool-manager/contracts.js +20 -0
  57. package/dist/tool-manager/contracts.js.map +1 -0
  58. package/dist/tool-manager/dispatch/dispatch.d.ts +77 -0
  59. package/dist/tool-manager/dispatch/dispatch.js +170 -0
  60. package/dist/tool-manager/dispatch/dispatch.js.map +1 -0
  61. package/dist/tool-manager/dispatch/tool-call-policy.d.ts +32 -0
  62. package/dist/tool-manager/dispatch/tool-call-policy.js +56 -0
  63. package/dist/tool-manager/dispatch/tool-call-policy.js.map +1 -0
  64. package/dist/tool-manager/{dispatcher.d.ts → orchestrator/dispatcher.d.ts} +110 -31
  65. package/dist/tool-manager/orchestrator/dispatcher.js +559 -0
  66. package/dist/tool-manager/orchestrator/dispatcher.js.map +1 -0
  67. package/dist/tool-manager/work-protocol/claimable-digest-tracker.d.ts +60 -0
  68. package/dist/tool-manager/work-protocol/claimable-digest-tracker.js +66 -0
  69. package/dist/tool-manager/work-protocol/claimable-digest-tracker.js.map +1 -0
  70. package/dist/tool-manager/work-protocol/work-lease-tracker.d.ts +70 -0
  71. package/dist/tool-manager/work-protocol/work-lease-tracker.js +146 -0
  72. package/dist/tool-manager/work-protocol/work-lease-tracker.js.map +1 -0
  73. package/dist/wire/mcp-transport.d.ts +1 -1
  74. package/dist/wire/mcp-transport.js +31 -7
  75. package/dist/wire/mcp-transport.js.map +1 -1
  76. package/dist/wire/slot-gate.d.ts +40 -0
  77. package/dist/wire/slot-gate.js +61 -0
  78. package/dist/wire/slot-gate.js.map +1 -0
  79. package/dist/wire/transport.d.ts +18 -0
  80. package/package.json +6 -3
  81. package/dist/kernel/instance.d.ts +0 -40
  82. package/dist/kernel/instance.js +0 -79
  83. package/dist/kernel/instance.js.map +0 -1
  84. package/dist/tool-manager/dispatcher.js +0 -379
  85. package/dist/tool-manager/dispatcher.js.map +0 -1
  86. package/dist/tool-manager/tool-catalog-cache.js.map +0 -1
@@ -0,0 +1,6 @@
1
+ {
2
+ "commitSha": "9f379e9",
3
+ "dirty": true,
4
+ "buildTime": "2026-07-03T01:44:42.475Z",
5
+ "branch": "main"
6
+ }
@@ -0,0 +1,42 @@
1
+ import type { ILogger, LogFields } from "./logger.js";
2
+ import { type LogLevel } from "./observability.js";
3
+ export interface FileLoggerOptions {
4
+ /** Text log file: timestamped human-readable lines. Required. */
5
+ textFile: string;
6
+ /**
7
+ * NDJSON structured-events file. When set, `appendEvent` + `logger` fan out
8
+ * here; when absent (opencode), `appendEvent` is a no-op.
9
+ */
10
+ eventsFile?: string;
11
+ /** Rotate textFile + eventsFile once either exceeds this many bytes. */
12
+ rotateBytes?: number;
13
+ /** Mirror every text line to process.stderr (claude: true; opencode: omit). */
14
+ mirrorToStderr?: boolean;
15
+ /**
16
+ * Suppress NDJSON events tagged with `fields.level` below this threshold
17
+ * (ADR-031 §3). Unlevelled events always emit. Default INFO.
18
+ */
19
+ logLevel?: LogLevel;
20
+ /** pid stamped into the NDJSON envelope. Default `process.pid`. */
21
+ pid?: number;
22
+ /** Fields pre-bound to every `logger` emission (root bind). */
23
+ bound?: LogFields;
24
+ /**
25
+ * Render a text-log line (including trailing newline) from a message.
26
+ * Default: `[<ISO with T/Z stripped>] <msg>\n` (claude's format). opencode
27
+ * injects `<raw ISO> <msg>\n`.
28
+ */
29
+ formatLine?: (msg: string) => string;
30
+ }
31
+ export interface FileLogger {
32
+ /** Append a human-readable line to textFile (+ optional stderr mirror). */
33
+ log(msg: string): void;
34
+ /**
35
+ * Append a structured NDJSON event (redacted, level-filtered). No-op when
36
+ * no `eventsFile` was configured.
37
+ */
38
+ appendEvent(event: string, fields: LogFields, message?: string): void;
39
+ /** Concrete ILogger fanning out to NDJSON events + the text log. */
40
+ logger: ILogger;
41
+ }
42
+ export declare function createFileLogger(opts: FileLoggerOptions): FileLogger;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * file-logger.ts — file-backed logging primitives shared by host shims.
3
+ *
4
+ * idea-355 SLICE-1 single-home: the claude shim's `FileBackedLogger` (NDJSON
5
+ * events + text-log + stderr fan-out, size-rotation, redaction, level-filter)
6
+ * and the opencode shim's simple text-append `log()` are two points on one
7
+ * spectrum. `createFileLogger` parameterizes both — a host supplies its file
8
+ * paths and which fan-out targets it wants, and gets back:
9
+ * - `log(msg)` — the human-readable text sink (claude: + stderr mirror)
10
+ * - `appendEvent` — the NDJSON structured-events writer (no-op when no
11
+ * `eventsFile`; opencode never sets one)
12
+ * - `logger` — a concrete `ILogger` fanning out to both of the above
13
+ *
14
+ * Behavior-preserving by construction: each host injects its exact line
15
+ * format via `formatLine`, so no cosmetic drift vs the pre-hoist shims.
16
+ *
17
+ * Filesystem side-effects only; no module-init config read (unit-test safe).
18
+ */
19
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
20
+ import { dirname } from "node:path";
21
+ import { redactFields, shouldEmitLevel } from "./observability.js";
22
+ function ensureDir(path) {
23
+ try {
24
+ mkdirSync(dirname(path), { recursive: true });
25
+ }
26
+ catch {
27
+ /* best-effort */
28
+ }
29
+ }
30
+ function rotateIfNeeded(file, rotateBytes) {
31
+ try {
32
+ const stat = statSync(file);
33
+ if (stat.size > rotateBytes) {
34
+ renameSync(file, `${file}.${Date.now()}`);
35
+ }
36
+ }
37
+ catch {
38
+ /* file doesn't exist yet, that's fine */
39
+ }
40
+ }
41
+ // The claude `FileBackedLogger`'s per-field renderer: each field prefixed with
42
+ // a leading space, joined with no separator. Kept verbatim so the rendered
43
+ // text-log lines are byte-identical to the pre-hoist shim.
44
+ function renderFields(fields) {
45
+ const parts = [];
46
+ for (const k of Object.keys(fields)) {
47
+ const v = fields[k];
48
+ parts.push(` ${k}=${Array.isArray(v) ? `[${v.join(",")}]` : String(v)}`);
49
+ }
50
+ return parts.join("");
51
+ }
52
+ const defaultFormatLine = (msg) => `[${new Date().toISOString().replace("T", " ").replace("Z", "")}] ${msg}\n`;
53
+ export function createFileLogger(opts) {
54
+ const formatLine = opts.formatLine ?? defaultFormatLine;
55
+ const logLevel = opts.logLevel ?? "INFO";
56
+ const pid = opts.pid ?? process.pid;
57
+ ensureDir(opts.textFile);
58
+ if (opts.eventsFile)
59
+ ensureDir(opts.eventsFile);
60
+ if (opts.rotateBytes) {
61
+ rotateIfNeeded(opts.textFile, opts.rotateBytes);
62
+ if (opts.eventsFile)
63
+ rotateIfNeeded(opts.eventsFile, opts.rotateBytes);
64
+ }
65
+ function log(msg) {
66
+ const line = formatLine(msg);
67
+ if (opts.mirrorToStderr)
68
+ process.stderr.write(line);
69
+ try {
70
+ appendFileSync(opts.textFile, line);
71
+ }
72
+ catch {
73
+ /* best-effort — never disturb the call loop */
74
+ }
75
+ }
76
+ function appendEvent(event, fields, message) {
77
+ if (!opts.eventsFile)
78
+ return;
79
+ // OIS_SHIM_LOG_LEVEL filter (ADR-031 §3): events tagged with `fields.level`
80
+ // below threshold are suppressed; unlevelled events always emit.
81
+ if (!shouldEmitLevel(fields.level, logLevel)) {
82
+ return;
83
+ }
84
+ const line = JSON.stringify({
85
+ ts: new Date().toISOString(),
86
+ event,
87
+ fields: redactFields(fields),
88
+ message: message ?? null,
89
+ pid,
90
+ }) + "\n";
91
+ try {
92
+ appendFileSync(opts.eventsFile, line);
93
+ }
94
+ catch {
95
+ /* best-effort */
96
+ }
97
+ }
98
+ // FileBackedLogger — concrete ILogger fanning out to: (1) NDJSON events file
99
+ // (structured fields preserved) and (2) text log + optional stderr (rendered
100
+ // friendly form). Bound fields apply to every emission; `child()` scopes a
101
+ // logger to a session / reconnect without threading context.
102
+ function makeLogger(bound) {
103
+ return {
104
+ log(event, fields, message) {
105
+ const merged = { ...bound, ...(fields ?? {}) };
106
+ appendEvent(event, merged, message);
107
+ if (message) {
108
+ log(`[${event}] ${message}`);
109
+ }
110
+ else {
111
+ const fieldsStr = renderFields(merged);
112
+ log(fieldsStr ? `[${event}]${fieldsStr}` : `[${event}]`);
113
+ }
114
+ },
115
+ child(fields) {
116
+ return makeLogger({ ...bound, ...fields });
117
+ },
118
+ };
119
+ }
120
+ return { log, appendEvent, logger: makeLogger(opts.bound ?? {}) };
121
+ }
122
+ //# sourceMappingURL=file-logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-logger.js","sourceRoot":"","sources":["../src/file-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAiB,MAAM,oBAAoB,CAAC;AAElF,SAAS,SAAS,CAAC,IAAY;IAC7B,IAAI,CAAC;QACH,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IAAC,MAAM,CAAC;QACP,iBAAiB;IACn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,CAAC,GAAG,IAAI,CAAC;QACZ,IAAI,CAAC;YACH,cAAc,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACxC,CAAC;QAAC,MAAM,CAAC;YACP,iBAAiB;QACnB,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,6EAA6E;IAC7E,2EAA2E;IAC3E,6DAA6D;IAC7D,SAAS,UAAU,CAAC,KAAgB;QAClC,OAAO;YACL,GAAG,CAAC,KAAa,EAAE,MAAkB,EAAE,OAAgB;gBACrD,MAAM,MAAM,GAAc,EAAE,GAAG,KAAK,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,EAAE,CAAC;gBAC1D,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;gBACpC,IAAI,OAAO,EAAE,CAAC;oBACZ,GAAG,CAAC,IAAI,KAAK,KAAK,OAAO,EAAE,CAAC,CAAC;gBAC/B,CAAC;qBAAM,CAAC;oBACN,MAAM,SAAS,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;oBACvC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC;gBAC3D,CAAC;YACH,CAAC;YACD,KAAK,CAAC,MAAiB;gBACrB,OAAO,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;YAC7C,CAAC;SACF,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;AACpE,CAAC"}
package/dist/index.d.ts CHANGED
@@ -2,28 +2,52 @@ export type { ITransport, TransportConfig, TransportMetrics, WireState, WireReco
2
2
  export { McpTransport } from "./wire/mcp-transport.js";
3
3
  export { McpAgentClient } from "./kernel/mcp-agent-client.js";
4
4
  export type { McpAgentClientOptions } from "./kernel/mcp-agent-client.js";
5
- export type { IAgentClient, AgentClientConfig, AgentClientCallbacks, AgentClientMetrics, AgentEvent, AgentHandshakeConfig, SessionState, SessionReconnectReason, } from "./kernel/agent-client.js";
6
- export type { HubEventType, HubEvent, EventDisposition, } from "./kernel/event-router.js";
7
- export { classifyEvent, parseHubEvent, createDedupFilter, } from "./kernel/event-router.js";
8
- export { loadOrCreateGlobalInstanceId } from "./kernel/instance.js";
9
- export type { LoadInstanceOptions } from "./kernel/instance.js";
10
- export { FATAL_CODES, parseHandshakeError, parseHandshakeResponse, buildHandshakePayload, performHandshake, makeStdioFatalHalt, } from "./kernel/handshake.js";
5
+ export type { IAgentClient, AgentClientConfig, AgentClientCallbacks, AgentClientMetrics, AgentHandshakeConfig, } from "./kernel/agent-client.js";
6
+ export type { AgentEvent, SessionState, SessionReconnectReason, DrainedPendingAction, } from "@apnex/message-router";
7
+ export type { HubEventType, HubEvent, EventDisposition, DrainedActionReconstruction, } from "./kernel/event-router.js";
8
+ export { classifyEvent, parseHubEvent, createDedupFilter, isPulseEvent, PULSE_KINDS, reconstructDrainedAction, } from "./kernel/event-router.js";
9
+ export { FATAL_CODES, parseHandshakeError, parseHandshakeResponse, buildHandshakePayload, performHandshake, makeStdioFatalHalt, readRequiredAgentName, } from "./kernel/handshake.js";
11
10
  export type { HandshakeClientMetadata, HandshakeAdvisoryTags, HandshakePayload, HandshakeResponse, HandshakeFatalError, HandshakeConfig, HandshakeContext, HandshakeResult, } from "./kernel/handshake.js";
11
+ export { parseLabels, loadConfig } from "./kernel/adapter-config.js";
12
+ export type { HubConfig, LoadConfigOptions } from "./kernel/adapter-config.js";
13
+ export { readPackageVersion, readBuildInfo, UNKNOWN_BUILD_INFO, } from "./kernel/build-identity.js";
14
+ export type { BuildInfo } from "./kernel/build-identity.js";
15
+ export { REDACT_KEYS, redactFields, LOG_LEVELS, parseLogLevel, shouldEmitLevel, } from "./observability.js";
16
+ export type { LogLevel } from "./observability.js";
17
+ export { createFileLogger } from "./file-logger.js";
18
+ export type { FileLogger, FileLoggerOptions } from "./file-logger.js";
12
19
  export { performStateSync } from "./kernel/state-sync.js";
13
- export type { StateSyncContext, DrainedPendingAction } from "./kernel/state-sync.js";
14
- export { PollBackstop, defaultCursorFile, readCursor, writeCursor, } from "./kernel/poll-backstop.js";
20
+ export type { StateSyncContext } from "./kernel/state-sync.js";
21
+ export { PollBackstop, defaultCursorFile, resolveRole, readCursor, writeCursor, jitter, JITTER_FRACTION, } from "./kernel/poll-backstop.js";
15
22
  export type { PollBackstopOptions } from "./kernel/poll-backstop.js";
16
23
  export { isEagerWarmupEnabled, parseClaimSessionResponse, formatSessionClaimedLogLine, } from "./kernel/session-claim.js";
17
24
  export type { ClaimSessionParsed } from "./kernel/session-claim.js";
18
- export { createSharedDispatcher, pendingKey, injectQueueItemId, } from "./tool-manager/dispatcher.js";
19
- export type { DispatcherClientInfo, DispatcherNotificationHooks, SharedDispatcherOptions, SharedDispatcher, } from "./tool-manager/dispatcher.js";
20
- export { CATALOG_SCHEMA_VERSION, cachePathFor, readCache, writeCache, isCacheValid, } from "./tool-manager/tool-catalog-cache.js";
21
- export type { ToolCatalog, CachedCatalog, } from "./tool-manager/tool-catalog-cache.js";
25
+ export { LivenessWatchdog } from "./kernel/liveness-watchdog.js";
26
+ export type { LivenessWatchdogOptions } from "./kernel/liveness-watchdog.js";
27
+ export { emitLivenessLostSignal, resolveSentinelPath, WEDGED_RESTART_EXIT_CODE, DEFAULT_LIVENESS_SENTINEL, } from "./kernel/liveness-signal.js";
28
+ export type { LivenessLostSignalPayload } from "./kernel/liveness-signal.js";
29
+ export { parseHarnessManifest, loadHarnessManifest, serverCapabilitiesFromManifest, } from "./kernel/harness-manifest.js";
30
+ export type { HarnessManifest, HarnessCapability } from "./kernel/harness-manifest.js";
31
+ export type { ToolDescriptor, ToolDispatchCallOptions, ToolDispatchResult, IToolDispatchAgent, IToolManager, } from "./tool-manager/contracts.js";
32
+ export { runToolDispatch } from "./tool-manager/dispatch/dispatch.js";
33
+ export type { ToolDispatchContext, McpToolCallResult, } from "./tool-manager/dispatch/dispatch.js";
34
+ export { createSharedDispatcher, pendingKey, injectQueueItemId, assertHostWiringComplete, } from "./tool-manager/orchestrator/dispatcher.js";
35
+ export type { DispatcherClientInfo, DispatcherNotificationHooks, SharedDispatcherOptions, SharedDispatcher, } from "./tool-manager/orchestrator/dispatcher.js";
36
+ export { CATALOG_SCHEMA_VERSION, cachePathFor, readCache, writeCache, isCacheValid, } from "./tool-manager/catalog/tool-catalog-cache.js";
37
+ export type { ToolCatalog, CachedCatalog, } from "./tool-manager/catalog/tool-catalog-cache.js";
38
+ export { ToolSurfaceReconciler } from "./tool-manager/catalog/tool-surface-reconciler.js";
39
+ export type { ToolSurfaceReconcilerDeps, ReconcileOutcome, } from "./tool-manager/catalog/tool-surface-reconciler.js";
40
+ export { makeFetchLiveToolSurfaceRevision } from "./tool-manager/catalog/health-revision.js";
41
+ export type { FetchLiveToolSurfaceRevisionOptions } from "./tool-manager/catalog/health-revision.js";
42
+ export { ClaimableDigestTracker } from "./tool-manager/work-protocol/claimable-digest-tracker.js";
43
+ export type { ClaimableDigestInput, ClaimableDigestDecision, } from "./tool-manager/work-protocol/claimable-digest-tracker.js";
44
+ export { WorkLeaseTracker } from "./tool-manager/work-protocol/work-lease-tracker.js";
45
+ export type { StallPrompt } from "./tool-manager/work-protocol/work-lease-tracker.js";
22
46
  export { HubReturnedError, isErrorEnvelope } from "./hub-error.js";
23
47
  export type { ILogger, LegacyStringLogger, LogField, LogFields } from "./logger.js";
24
48
  export { getActionText, buildPromptText, buildToastMessage, } from "./prompt-format.js";
25
49
  export type { PromptFormatConfig } from "./prompt-format.js";
26
- export { appendNotification } from "./notification-log.js";
50
+ export { appendNotification, buildPendingTaskNotification } from "./notification-log.js";
27
51
  export type { NotificationLogEntry, NotificationLogOptions, } from "./notification-log.js";
28
52
  export { CognitivePipeline, CognitiveTelemetry, CircuitBreaker, HubUnavailableError, WriteCallDedup, DedupTimeoutError, ToolResultCache, FlushAllOnWriteStrategy, ToolDescriptionEnricher, ErrorNormalizer, NormalizedError, ResponseSummarizer, summarizeResult, buildPaginationHint, } from "@apnex/cognitive-layer";
29
53
  export type { CognitiveMiddleware, ToolCallContext, ListToolsContext, ToolErrorContext, Tool as CognitiveTool, StandardPipelineConfig, CognitiveTelemetryConfig, TelemetryEvent, TelemetryEventKind, CircuitBreakerConfig, CircuitState, CircuitStateChange, WriteCallDedupConfig, ToolResultCacheConfig, InvalidationStrategy, InvalidationDirective, CacheKey, ToolDescriptionEnricherConfig, ToolHints, ErrorNormalizerConfig, ErrorRule, CascadeDriftRule, ResponseSummarizerConfig, } from "@apnex/cognitive-layer";
package/dist/index.js CHANGED
@@ -2,26 +2,53 @@
2
2
  export { McpTransport } from "./wire/mcp-transport.js";
3
3
  // ── Layer 1b: Kernel (handshake / session FSM / agent client) ──────
4
4
  export { McpAgentClient } from "./kernel/mcp-agent-client.js";
5
- export { classifyEvent, parseHubEvent, createDedupFilter, } from "./kernel/event-router.js";
6
- export { loadOrCreateGlobalInstanceId } from "./kernel/instance.js";
7
- export { FATAL_CODES, parseHandshakeError, parseHandshakeResponse, buildHandshakePayload, performHandshake, makeStdioFatalHalt, } from "./kernel/handshake.js";
5
+ export { classifyEvent, parseHubEvent, createDedupFilter, isPulseEvent, PULSE_KINDS, reconstructDrainedAction, } from "./kernel/event-router.js";
6
+ // idea-251 D-prime Phase 2: instance.ts deleted. Identity now flows from
7
+ // OIS_AGENT_NAME env handshake.name Hub-side fingerprint(name).
8
+ // Operators set OIS_AGENT_NAME in ~/.config/apnex-agents/{name}.env.
9
+ export { FATAL_CODES, parseHandshakeError, parseHandshakeResponse, buildHandshakePayload, performHandshake, makeStdioFatalHalt, readRequiredAgentName, } from "./kernel/handshake.js";
10
+ export { parseLabels, loadConfig } from "./kernel/adapter-config.js";
11
+ export { readPackageVersion, readBuildInfo, UNKNOWN_BUILD_INFO, } from "./kernel/build-identity.js";
12
+ export { REDACT_KEYS, redactFields, LOG_LEVELS, parseLogLevel, shouldEmitLevel, } from "./observability.js";
13
+ export { createFileLogger } from "./file-logger.js";
8
14
  export { performStateSync } from "./kernel/state-sync.js";
9
- export { PollBackstop, defaultCursorFile, readCursor, writeCursor, } from "./kernel/poll-backstop.js";
15
+ export { PollBackstop, defaultCursorFile, resolveRole, readCursor, writeCursor, jitter, JITTER_FRACTION, } from "./kernel/poll-backstop.js";
10
16
  export { isEagerWarmupEnabled, parseClaimSessionResponse, formatSessionClaimedLogLine, } from "./kernel/session-claim.js";
11
- // ── Layer 1c: tool-manager (Initialize/ListTools/CallTool factory) ──
12
- //
13
- // The MCP protocol tool-manager per Design v1.2 §4 naming discipline
14
- // (Director-ratified rename from "MCP-boundary dispatcher" 2026-04-26).
15
- // Distinct from the future Message-router (sovereign-package #6,
16
- // `@apnex/message-router`, M-Push-Foundation W4). Always qualify
17
- // ("tool-manager" or "Message-router") in new code; avoid bare
18
- // "dispatcher".
19
- export { createSharedDispatcher, pendingKey, injectQueueItemId, } from "./tool-manager/dispatcher.js";
20
- export { CATALOG_SCHEMA_VERSION, cachePathFor, readCache, writeCache, isCacheValid, } from "./tool-manager/tool-catalog-cache.js";
17
+ // ── L1.5 liveness watchdog + the kernel->supervisor exit-propagation seam
18
+ // (M-Adapter-Modernization P1c, Design §4). The watchdog detects the
19
+ // keepalives-flowing-but-session-dead wedge via a proactive session probe;
20
+ // on a bounded failure budget it emits the wedged-restart sentinel (the
21
+ // signal P1e's PID-1 supervisor consumes) and the shim self-exits.
22
+ export { LivenessWatchdog } from "./kernel/liveness-watchdog.js";
23
+ export { emitLivenessLostSignal, resolveSentinelPath, WEDGED_RESTART_EXIT_CODE, DEFAULT_LIVENESS_SENTINEL, } from "./kernel/liveness-signal.js";
24
+ // ── Harness manifest (M-Adapter-Modernization P1b) — the per-harness STANDARD
25
+ // config as a schema-validated, VERSIONED artifact. The claude shim is the
26
+ // first conformant instance; opencode/Phase-2 slot in as a second manifest
27
+ // against this SAME schema (not a parallel hand-rolled shape). Per-agent
28
+ // INSTANCE values stay in ENV — the manifest carries only env var NAMES.
29
+ export { parseHarnessManifest, loadHarnessManifest, serverCapabilitiesFromManifest, } from "./kernel/harness-manifest.js";
30
+ // Slice D (pi): the transport-neutral dispatch authority + its dependency
31
+ // context, exported through the facade so a NATIVE host binding (pi's
32
+ // tool-bridge) consumes the SAME per-call behavior wrapper the MCP CallTool
33
+ // handler uses — without importing an MCP server. This is the concrete payoff of
34
+ // the Slice-B extraction: one dispatch authority, many last-mile bindings.
35
+ export { runToolDispatch } from "./tool-manager/dispatch/dispatch.js";
36
+ // Slice C: dispatcher is the orchestrator (binding assembly); dispatch authority
37
+ // + OIS policy live under dispatch/; cache/reconcile/health under catalog/.
38
+ export { createSharedDispatcher, pendingKey, injectQueueItemId, assertHostWiringComplete, } from "./tool-manager/orchestrator/dispatcher.js";
39
+ export { CATALOG_SCHEMA_VERSION, cachePathFor, readCache, writeCache, isCacheValid, } from "./tool-manager/catalog/tool-catalog-cache.js";
40
+ export { ToolSurfaceReconciler } from "./tool-manager/catalog/tool-surface-reconciler.js";
41
+ // idea-355 SLICE-1T — the Hub /health toolSurfaceRevision fetcher, hoisted from
42
+ // the shims so both share ONE network mechanism (pure; the cache side-effect
43
+ // stays shim-side).
44
+ export { makeFetchLiveToolSurfaceRevision } from "./tool-manager/catalog/health-revision.js";
45
+ // idea-353 — queue wake/stall reconciliation primitives.
46
+ export { ClaimableDigestTracker } from "./tool-manager/work-protocol/claimable-digest-tracker.js";
47
+ export { WorkLeaseTracker } from "./tool-manager/work-protocol/work-lease-tracker.js";
21
48
  // ── Cross-cutting primitives (root) ─────────────────────────────────
22
49
  export { HubReturnedError, isErrorEnvelope } from "./hub-error.js";
23
50
  export { getActionText, buildPromptText, buildToastMessage, } from "./prompt-format.js";
24
- export { appendNotification } from "./notification-log.js";
51
+ export { appendNotification, buildPendingTaskNotification } from "./notification-log.js";
25
52
  // ── Cognitive layer re-exports (ADR-018) ────────────────────────────
26
53
  // The `cognitive` option on `McpAgentClient` accepts any
27
54
  // `@apnex/cognitive-layer` `CognitivePipeline`. Re-exporting the
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAYtE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAEvD,sEAAsE;AAEtE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAoB9D,OAAO,EACL,aAAa,EACb,aAAa,EACb,iBAAiB,GAClB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAGpE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAY/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG1D,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,UAAU,EACV,WAAW,GACZ,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,2BAA2B,CAAC;AAGnC,uEAAuE;AACvE,EAAE;AACF,qEAAqE;AACrE,wEAAwE;AACxE,iEAAiE;AACjE,iEAAiE;AACjE,+DAA+D;AAC/D,gBAAgB;AAEhB,OAAO,EACL,sBAAsB,EACtB,UAAU,EACV,iBAAiB,GAClB,MAAM,8BAA8B,CAAC;AAQtC,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,SAAS,EACT,UAAU,EACV,YAAY,GACb,MAAM,sCAAsC,CAAC;AAM9C,uEAAuE;AAEvE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAInE,OAAO,EACL,aAAa,EACb,eAAe,EACf,iBAAiB,GAClB,MAAM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Ae,EAAE,MAAM,gBAAgB,CAAC;AAInE,OAAO,EACL,aAAa,EACb,eAAe,EACf,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,kBAAkB,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAMzF,uEAAuE;AACvE,yDAAyD;AACzD,iEAAiE;AACjE,gEAAgE;AAChE,4DAA4D;AAE5D,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,uBAAuB,EACvB,uBAAuB,EACvB,eAAe,EACf,eAAe,EACf,kBAAkB,EAClB,eAAe,EACf,mBAAmB,GACpB,MAAM,wBAAwB,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Adapter configuration — the generic `.ois/adapter-config.json` + env loader.
3
+ *
4
+ * idea-355 SLICE-1 single-home: both shims hand-rolled a near-identical
5
+ * HubConfig + parseLabels + loadConfig. They diverged only in host specifics —
6
+ * the default hubUrl, whether `autoPrompt` is carried, the warn sink, and the
7
+ * missing-creds policy (claude `process.exit(1)`; opencode can't kill the TUI).
8
+ * Those host specifics are INJECTED here; the load mechanism lives once in the
9
+ * kernel so it can't drift (the M18-scar class). Credential VALIDATION stays in
10
+ * the shim (the last-mile abort).
11
+ */
12
+ export interface HubConfig {
13
+ hubUrl: string;
14
+ hubToken: string;
15
+ role: string;
16
+ /**
17
+ * Mission-19 routing labels. Stamped onto the Agent entity via the enriched
18
+ * register_role handshake; scoped dispatches filter by these. Read from
19
+ * adapter-config.json `labels` or the `OIS_HUB_LABELS` env var (JSON). Omit
20
+ * for broadcast.
21
+ */
22
+ labels?: Record<string, string>;
23
+ /** OpenCode-only: auto-prompt the host on actionable events. Claude omits it. */
24
+ autoPrompt?: boolean;
25
+ }
26
+ /**
27
+ * Parse a JSON-encoded label map (string→string only). Returns undefined for
28
+ * empty/absent/invalid input; warns via the injected sink on parse failure.
29
+ */
30
+ export declare function parseLabels(raw: string | undefined, source: string, warn?: (m: string) => void): Record<string, string> | undefined;
31
+ export interface LoadConfigOptions {
32
+ /** Parent dir of `.ois/` — WORK_DIR/cwd for claude, the host-supplied dir for opencode. */
33
+ directory: string;
34
+ /** Host defaults layered under file + env (e.g. opencode's relay hubUrl + autoPrompt:true). */
35
+ defaults?: Partial<HubConfig>;
36
+ /** Warn sink (claude console.error; opencode log()). */
37
+ warn?: (m: string) => void;
38
+ /** Read `autoPrompt` from file + `HUB_PLUGIN_AUTO_PROMPT` env (opencode only). */
39
+ readAutoPrompt?: boolean;
40
+ }
41
+ /**
42
+ * Load HubConfig from `<directory>/.ois/adapter-config.json` layered under env
43
+ * overrides (OIS_HUB_URL/OIS_HUB_TOKEN/OIS_HUB_ROLE/OIS_HUB_LABELS, plus
44
+ * HUB_PLUGIN_AUTO_PROMPT when readAutoPrompt). Precedence: defaults < file < env.
45
+ * Does NOT validate credentials — the caller (shim) does its host-specific abort.
46
+ */
47
+ export declare function loadConfig(opts: LoadConfigOptions): HubConfig;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Adapter configuration — the generic `.ois/adapter-config.json` + env loader.
3
+ *
4
+ * idea-355 SLICE-1 single-home: both shims hand-rolled a near-identical
5
+ * HubConfig + parseLabels + loadConfig. They diverged only in host specifics —
6
+ * the default hubUrl, whether `autoPrompt` is carried, the warn sink, and the
7
+ * missing-creds policy (claude `process.exit(1)`; opencode can't kill the TUI).
8
+ * Those host specifics are INJECTED here; the load mechanism lives once in the
9
+ * kernel so it can't drift (the M18-scar class). Credential VALIDATION stays in
10
+ * the shim (the last-mile abort).
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ /**
15
+ * Parse a JSON-encoded label map (string→string only). Returns undefined for
16
+ * empty/absent/invalid input; warns via the injected sink on parse failure.
17
+ */
18
+ export function parseLabels(raw, source, warn = () => { }) {
19
+ if (!raw)
20
+ return undefined;
21
+ try {
22
+ const parsed = JSON.parse(raw);
23
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
24
+ const out = {};
25
+ for (const [k, v] of Object.entries(parsed)) {
26
+ if (typeof v === "string")
27
+ out[k] = v;
28
+ }
29
+ return Object.keys(out).length > 0 ? out : undefined;
30
+ }
31
+ }
32
+ catch (err) {
33
+ warn(`WARNING: Failed to parse labels from ${source}: ${err}`);
34
+ }
35
+ return undefined;
36
+ }
37
+ /**
38
+ * Load HubConfig from `<directory>/.ois/adapter-config.json` layered under env
39
+ * overrides (OIS_HUB_URL/OIS_HUB_TOKEN/OIS_HUB_ROLE/OIS_HUB_LABELS, plus
40
+ * HUB_PLUGIN_AUTO_PROMPT when readAutoPrompt). Precedence: defaults < file < env.
41
+ * Does NOT validate credentials — the caller (shim) does its host-specific abort.
42
+ */
43
+ export function loadConfig(opts) {
44
+ const { directory, defaults = {}, warn = () => { }, readAutoPrompt = false } = opts;
45
+ const cfg = {
46
+ hubUrl: defaults.hubUrl ?? "",
47
+ hubToken: defaults.hubToken ?? "",
48
+ role: defaults.role ?? "engineer",
49
+ };
50
+ if (defaults.labels)
51
+ cfg.labels = defaults.labels;
52
+ if (defaults.autoPrompt !== undefined)
53
+ cfg.autoPrompt = defaults.autoPrompt;
54
+ try {
55
+ const raw = JSON.parse(readFileSync(join(directory, ".ois", "adapter-config.json"), "utf-8"));
56
+ if (typeof raw.hubUrl === "string")
57
+ cfg.hubUrl = raw.hubUrl;
58
+ if (typeof raw.hubToken === "string")
59
+ cfg.hubToken = raw.hubToken;
60
+ if (typeof raw.role === "string")
61
+ cfg.role = raw.role;
62
+ if (raw.labels && typeof raw.labels === "object") {
63
+ cfg.labels = raw.labels;
64
+ }
65
+ if (readAutoPrompt && typeof raw.autoPrompt === "boolean")
66
+ cfg.autoPrompt = raw.autoPrompt;
67
+ }
68
+ catch (err) {
69
+ // Silent on a missing file (the common case); warn on a real read/parse
70
+ // failure of a PRESENT file (preserves claude's prior behavior; opencode
71
+ // gains the diagnostic to its log).
72
+ if (err?.code !== "ENOENT") {
73
+ warn(`WARNING: Failed to read/parse ${join(directory, ".ois", "adapter-config.json")}: ${err}`);
74
+ }
75
+ }
76
+ if (process.env.OIS_HUB_URL)
77
+ cfg.hubUrl = process.env.OIS_HUB_URL;
78
+ if (process.env.OIS_HUB_TOKEN)
79
+ cfg.hubToken = process.env.OIS_HUB_TOKEN;
80
+ if (process.env.OIS_HUB_ROLE)
81
+ cfg.role = process.env.OIS_HUB_ROLE;
82
+ if (readAutoPrompt && process.env.HUB_PLUGIN_AUTO_PROMPT) {
83
+ cfg.autoPrompt = process.env.HUB_PLUGIN_AUTO_PROMPT.toLowerCase() !== "false";
84
+ }
85
+ const envLabels = parseLabels(process.env.OIS_HUB_LABELS, "OIS_HUB_LABELS env var", warn);
86
+ if (envLabels)
87
+ cfg.labels = envLabels;
88
+ return cfg;
89
+ }
90
+ //# sourceMappingURL=adapter-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter-config.js","sourceRoot":"","sources":["../../src/kernel/adapter-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAiBjC;;;GAGG;AACH,MAAM,UAAU,WAAW,CACzB,GAAuB,EACvB,MAAc,EACd,OAA4B,GAAG,EAAE,GAAE,CAAC;IAEpC,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAC3B,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACnE,MAAM,GAAG,GAA2B,EAAE,CAAC;YACvC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MA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K,OAAO,CAAC;IAChF,CAAC;IACD,MAAM,SAAS,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,wBAAwB,EAAE,IAAI,CAAC,CAAC;IAC1F,IAAI,SAAS;QAAE,GAAG,CAAC,MAAM,GAAG,SAAS,CAAC;IAEtC,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -43,9 +43,10 @@
43
43
  import type { ILogger, LegacyStringLogger } from "../logger.js";
44
44
  import type { ITransport } from "../wire/transport.js";
45
45
  import type { HandshakeFatalError, HandshakeResponse } from "./handshake.js";
46
- import type { DrainedPendingAction } from "./state-sync.js";
46
+ import type { AgentEvent, DrainedPendingAction, SessionReconnectReason, SessionState } from "@apnex/message-router";
47
+ export type { AgentEvent, SessionState, SessionReconnectReason };
47
48
  /**
48
- * Session FSM state exposed to shims.
49
+ * Session FSM the AgentClient drives `SessionState` through:
49
50
  *
50
51
  * disconnected → connecting → synchronizing → streaming
51
52
  * ↑ ↓
@@ -58,22 +59,6 @@ import type { DrainedPendingAction } from "./state-sync.js";
58
59
  * G4: Consecutive SSE failures trigger exponential backoff
59
60
  * G5: All reconnections carry a classified SessionReconnectReason
60
61
  */
61
- export type SessionState = "disconnected" | "connecting" | "synchronizing" | "streaming" | "reconnecting";
62
- /** Classifies why a session re-entered `reconnecting`. */
63
- export type SessionReconnectReason = "heartbeat_failed" | "sse_watchdog" | "sse_never_opened" | "session_invalid";
64
- /**
65
- * Classified hub event delivered to the shim. Mirrors the existing
66
- * `HubEvent` shape from `event-router.ts` but re-declared here so the
67
- * AgentClient surface can be consumed without importing the router.
68
- * Phase 3+ will unify these back to one source of truth.
69
- */
70
- export interface AgentEvent {
71
- readonly id?: number | string;
72
- readonly event: string;
73
- readonly data: Record<string, unknown>;
74
- readonly timestamp?: string;
75
- readonly targetRoles?: readonly string[];
76
- }
77
62
  /**
78
63
  * What a shim plugs into an AgentClient. All callbacks are optional —
79
64
  * a shim that doesn't care about, say, informational events can omit
@@ -90,11 +75,21 @@ export interface AgentClientCallbacks {
90
75
  * collapse to the bare register_role call.
91
76
  */
92
77
  export interface AgentHandshakeConfig {
93
- globalInstanceId: string;
78
+ /**
79
+ * idea-251 D-prime Phase 2: name IS identity. REQUIRED. Sourced from
80
+ * `OIS_AGENT_NAME` env var by the host shim. Drives agentId derivation
81
+ * `agent-{8-hex-of-sha256(name)}` on Hub side. globalInstanceId field
82
+ * RETIRED (was pre-D-prime fingerprint input).
83
+ */
84
+ name: string;
94
85
  proxyName: string;
95
86
  proxyVersion: string;
96
87
  transport: string;
97
88
  sdkVersion: string;
89
+ proxyCommitSha?: string;
90
+ proxyDirty?: boolean;
91
+ sdkCommitSha?: string;
92
+ sdkDirty?: boolean;
98
93
  getClientInfo: () => {
99
94
  name: string;
100
95
  version: string;
@@ -148,6 +143,16 @@ export interface AgentClientMetrics {
148
143
  readonly totalSessionInvalidRetries: number;
149
144
  readonly dedupDropCount: number;
150
145
  }
146
+ /**
147
+ * Per-call options for `IAgentClient.call`. bug-106: `internal: true` marks
148
+ * a machinery-originated call (poll-backstop catch-up, transport heartbeat)
149
+ * so the cognitive pipeline's LLM-facing result transforms (notably
150
+ * `ResponseSummarizer`) skip it — machinery needs the raw, full result.
151
+ */
152
+ export interface AgentCallOptions {
153
+ /** Mark this call internal-machinery — skip LLM-facing result transforms. */
154
+ internal?: boolean;
155
+ }
151
156
  export interface IAgentClient {
152
157
  /** Current session FSM state. */
153
158
  readonly state: SessionState;
@@ -169,7 +174,7 @@ export interface IAgentClient {
169
174
  * and retries exactly once on the fresh session before surfacing
170
175
  * the error.
171
176
  */
172
- call(method: string, params: Record<string, unknown>): Promise<unknown>;
177
+ call(method: string, params: Record<string, unknown>, opts?: AgentCallOptions): Promise<unknown>;
173
178
  /**
174
179
  * List the method surface currently advertised by the peer. The
175
180
  * AgentClient delegates to `ITransport.listMethods()` and may cache
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Adapter build-identity reads — package version + build-info (commit SHA /
3
+ * dirty / build time / branch), hoisted from the shims in idea-355 SLICE-1.
4
+ *
5
+ * `readPackageVersion` was duplicated verbatim in both shims (the mission-66 #40
6
+ * version-source-of-truth fix). `readBuildInfo` + `BuildInfo` were claude-only
7
+ * (the idea-256 build-identity wire). Single-home the READ mechanism here so it
8
+ * can't drift; each shim still resolves its host-specific package.json /
9
+ * build-info paths and derives its own version constants. (The
10
+ * bundle-vs-node_modules path nuance + the report-both/auto-bump scheme are
11
+ * SLICE-3's concern.)
12
+ */
13
+ /** Read the `version` field from a package.json; fallback on any failure. */
14
+ export declare function readPackageVersion(pkgJsonPath: string, fallback: string): string;
15
+ /** idea-256 build-identity: commit SHA / dirty / build time / branch. */
16
+ export interface BuildInfo {
17
+ commitSha: string;
18
+ dirty: boolean;
19
+ buildTime: string | null;
20
+ branch: string;
21
+ }
22
+ export declare const UNKNOWN_BUILD_INFO: BuildInfo;
23
+ /** Read a dist/build-info.json (written by scripts/build/write-build-info.js). */
24
+ export declare function readBuildInfo(buildInfoPath: string): BuildInfo;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Adapter build-identity reads — package version + build-info (commit SHA /
3
+ * dirty / build time / branch), hoisted from the shims in idea-355 SLICE-1.
4
+ *
5
+ * `readPackageVersion` was duplicated verbatim in both shims (the mission-66 #40
6
+ * version-source-of-truth fix). `readBuildInfo` + `BuildInfo` were claude-only
7
+ * (the idea-256 build-identity wire). Single-home the READ mechanism here so it
8
+ * can't drift; each shim still resolves its host-specific package.json /
9
+ * build-info paths and derives its own version constants. (The
10
+ * bundle-vs-node_modules path nuance + the report-both/auto-bump scheme are
11
+ * SLICE-3's concern.)
12
+ */
13
+ import { readFileSync } from "node:fs";
14
+ /** Read the `version` field from a package.json; fallback on any failure. */
15
+ export function readPackageVersion(pkgJsonPath, fallback) {
16
+ try {
17
+ const raw = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
18
+ return typeof raw.version === "string" ? raw.version : fallback;
19
+ }
20
+ catch {
21
+ return fallback;
22
+ }
23
+ }
24
+ export const UNKNOWN_BUILD_INFO = {
25
+ commitSha: "unknown",
26
+ dirty: false,
27
+ buildTime: null,
28
+ branch: "unknown",
29
+ };
30
+ /** Read a dist/build-info.json (written by scripts/build/write-build-info.js). */
31
+ export function readBuildInfo(buildInfoPath) {
32
+ try {
33
+ const raw = JSON.parse(readFileSync(buildInfoPath, "utf-8"));
34
+ return {
35
+ commitSha: typeof raw.commitSha === "string" ? raw.commitSha : "unknown",
36
+ dirty: !!raw.dirty,
37
+ buildTime: typeof raw.buildTime === "string" ? raw.buildTime : null,
38
+ branch: typeof raw.branch === "string" ? raw.branch : "unknown",
39
+ };
40
+ }
41
+ catch {
42
+ return UNKNOWN_BUILD_INFO;
43
+ }
44
+ }
45
+ //# sourceMappingURL=build-identity.js.map