dsh-harness-reflex 0.1.0 → 0.3.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 (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -1 +1 @@
1
- {"version":3,"file":"bridge.js","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,cAAc,EACd,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EACnB,wBAAwB,EACxB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,cAAc,EACf,MAAM,kCAAkC,CAAC;AAsB1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAA2B,MAAM,aAAa,CAAC;AAE3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AA2BjD;;;;;;;;;;GAUG;AACH,MAAM,WAAW;IACf,OAAO,CAAkB;IAEzB,YAAY,MAAuB;QACjC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED,6DAA6D;IAC7D,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,OAAO,CAAC,IAA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GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;gBACzC,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC;aAClD,CAAC,CAAC;QACL;YACE,OAAO,sBAAsB,EAAE,CAAC;IACpC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA4B,EAC5B,eAMI,EAAE;IAEN,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import {\n Calibrator,\n DecisionLedger,\n JevDecisionBackend,\n MockDecisionBackend,\n ReflexGateService,\n ReflexRouter,\n ReflexScreenService,\n SimpleJevDecisionBackend,\n StagnationDetector,\n ToolResultPruner,\n createSystemOneBackend,\n scoreStatement\n} from './vendor/harness-reflex/index.js';\nimport type {\n ActionStep,\n BackendHealth,\n CandidateItem,\n ChoiceResponse,\n DecisionBackend,\n GateResponse,\n PruneResponse,\n RouteResponse,\n ScreenResult,\n StagnationCheckResponse\n} from './vendor/harness-reflex/index.js';\n\nimport type {\n ReflexConfig,\n ResolvedInterventionsConfig,\n ResolvedReflexConfig,\n ResolvedRoutingConfig,\n ResolvedSystemOneConfig,\n ResolvedToolsConfig\n} from './config.js';\nimport { resolveApiKey, resolveConfig, volatileSnapshots } from './config.js';\nimport { EffortInterceptor, EffortStatusFeed, type ReflexEffortStatus } from './effort.js';\nimport type { InterventionEngine } from './interventions.js';\nimport { VirtualModelRouter } from './router.js';\n\n/** Payload of the `choice` operation, mirroring the stdio MCP surface. */\nexport type ReflexChoiceResult = ChoiceResponse & { calibratedConfidence?: number };\n\n/** Payload of the `prune` operation, mirroring the stdio MCP surface. */\nexport interface ReflexPruneResult {\n tokensSaved: number;\n reductionPercentage: string;\n shadow: boolean;\n processedOutput: string;\n}\n\n/** Payload of the ledger read, mirroring the stdio MCP `status_ledger` payload. */\nexport interface ReflexLedgerResult {\n summary: ReturnType<DecisionLedger['getSummary']>;\n recentEntries?: ReturnType<DecisionLedger['getEntries']>;\n /**\n * Health of the backend at read time, when it tracks one.\n *\n * `/reflex-ledger` prints a degraded notice from it. It is deliberately not\n * part of any model-facing tool payload: a health warning is a diagnostics\n * fact for the person reading the command, not context for the agent.\n */\n systemOneHealth?: BackendHealth;\n}\n\n/**\n * A decision backend whose implementation can be swapped while services keep\n * their reference to it.\n *\n * The five decision services are built once and close over their backend. A\n * config-only save can change `backend`/`systemOne.*`, and rebuilding those\n * services would drop their ledger/audit wiring; delegating through one stable\n * object swaps the transport instead, so the next decision reaches the new\n * endpoint/model while the services stay put. Health is the delegate's, so a\n * freshly built backend starts at `available: true, consecutiveFailures: 0`.\n */\nclass LiveBackend {\n #target: DecisionBackend;\n\n constructor(target: DecisionBackend) {\n this.#target = target;\n }\n\n /** Name of the backend implementation currently in force. */\n get name(): string {\n return this.#target.name;\n }\n\n /** Model id of the backend implementation currently in force. */\n get model(): string {\n return this.#target.model;\n }\n\n /** Replace the transport, releasing the previous one. */\n swap(next: DecisionBackend): void {\n const previous = this.#target;\n this.#target = next;\n const dispose = (previous as { dispose?: () => void }).dispose;\n if (typeof dispose === 'function') {\n try {\n dispose.call(previous);\n } catch {\n // A backend that cannot release its transport must not veto the swap.\n }\n }\n }\n\n choice(request: Parameters<DecisionBackend['choice']>[0]): ReturnType<DecisionBackend['choice']> {\n return this.#target.choice(request);\n }\n\n gate(request: Parameters<DecisionBackend['gate']>[0]): ReturnType<DecisionBackend['gate']> {\n return this.#target.gate(request);\n }\n\n prune(request: Parameters<DecisionBackend['prune']>[0]): ReturnType<DecisionBackend['prune']> {\n return this.#target.prune(request);\n }\n\n checkStagnation(request: Parameters<DecisionBackend['checkStagnation']>[0]): ReturnType<DecisionBackend['checkStagnation']> {\n return this.#target.checkStagnation(request);\n }\n\n route(request: Parameters<DecisionBackend['route']>[0]): ReturnType<DecisionBackend['route']> {\n return this.#target.route(request);\n }\n\n classifyClaims(request: Parameters<DecisionBackend['classifyClaims']>[0]): ReturnType<DecisionBackend['classifyClaims']> {\n return this.#target.classifyClaims(request);\n }\n\n /** Health of the backend currently in force (absent for in-process backends). */\n currentHealth(): BackendHealth | undefined {\n const health = (this.#target as Partial<DecisionBackend>).health;\n return typeof health === 'function' ? health.call(this.#target) : undefined;\n }\n}\n\n/**\n * In-process System One runtime shared by every reflex tool of one plugin\n * activation.\n *\n * The bridge owns the backend, the audit ledger, and the five decision services,\n * so a plugin reload builds a fresh runtime and drops the previous one whole —\n * no module-level singleton is mutated and nothing survives the activation.\n */\nexport class ReflexRuntime {\n readonly config: ResolvedReflexConfig;\n readonly backend: DecisionBackend;\n readonly ledger: DecisionLedger;\n readonly calibrator: Calibrator;\n readonly gateService: ReflexGateService;\n readonly pruneService: ToolResultPruner;\n readonly stagnationService: StagnationDetector;\n readonly routeService: ReflexRouter;\n readonly screenService: ReflexScreenService;\n /**\n * System 1 virtual→physical model router this activation routes through. It\n * owns the configured pools and writes one `model-route` ledger entry per\n * decision; the plugin installs it on the LLM runtime and dispatches through\n * it. With several live activations the process-wide route has one shared\n * router, and {@link adoptModelRouter} points this runtime at it.\n */\n #modelRouter: VirtualModelRouter;\n /**\n * Per-turn adaptive reasoning-effort policy. It writes one `effort-decision`\n * ledger entry per decided turn and publishes each decision to\n * {@link effortStatusFeed}.\n */\n readonly effort: EffortInterceptor;\n /** Status-bar surface of the adaptive effort decisions of this activation. */\n readonly effortStatusFeed: EffortStatusFeed;\n\n #disposed = false;\n #surface: readonly string[] = [];\n #interventions?: InterventionEngine;\n /**\n * The config the Host resolved for this activation, kept as it was passed in.\n *\n * With the Cordis loader this object holds schema-declared *volatile\n * references*: a config-only update mutates those references in place and\n * dispatches `loader/volatile-update` instead of remounting the plugin, so\n * this is the only handle that sees the new values. A programmatic caller\n * passes a plain object, in which case there is nothing to watch.\n */\n readonly #source: unknown;\n /** Snapshot identities of {@link #source} at the last applied refresh. */\n #mark: unknown[] = [];\n /** Re-entrancy guard: callbacks during one apply must not resolve again. */\n #refreshing = false;\n /** Whether {@link #source} actually exposes volatile references. */\n readonly #watchable: boolean;\n #warn: (message: string) => void;\n /**\n * The intervention policy currently in force.\n *\n * Kept even when the engine is inert (`mode: off`), so the panel reports the\n * authored block rather than the activation-time snapshot, and so turning a\n * capability back on can install its listeners without a remount.\n */\n #interventionsConfig: ResolvedInterventionsConfig;\n /** The prune threshold currently in force (top-level `pruneThreshold`). */\n #pruneThreshold: number;\n /**\n * The per-tool switches and deployment prefix currently in force.\n *\n * Kept here rather than read from {@link config} because a config-only save\n * never remounts the activation: the registry has to follow the committed\n * values, and the panel has to report the same ones.\n */\n #toolsConfig: ResolvedToolsConfig;\n #toolPrefix: string;\n /** Applies a freshly resolved intervention policy to the installed listeners. */\n #reconfigureInterventions?: (config: ResolvedInterventionsConfig, pruneThreshold: number) => void;\n /** Reads how many intervention listeners are currently attached. */\n #interventionListenerCount?: () => number;\n /** Reconciles the registered tool set with a freshly resolved config. */\n #reconfigureTools?: (config: ResolvedReflexConfig) => void;\n /** Reads how many tools this activation currently has registered. */\n #toolRegistrationCount?: () => number;\n /** Reads how many `tools.register` calls this activation has made in total. */\n #toolRegistrationEvents?: () => number;\n /** Full schema resolutions performed by this activation (diagnostics/measurement). */\n #configResolves = 0;\n\n /** The stable delegate all decision services dispatch through. */\n readonly #liveBackend: LiveBackend;\n /** Whether this runtime owns the backend and may rebuild it on a config save. */\n readonly #backendSwappable: boolean;\n /** Identity of the backend configuration currently in force. */\n #backendSignature: string;\n /** System One connection settings currently in force (panel/diagnostics). */\n #systemOneConfig: ResolvedSystemOneConfig;\n /** Backend selector currently in force (panel/diagnostics). */\n #backendSelector: ResolvedReflexConfig['backend'];\n /** Ledger sink currently in force. */\n #ledgerPath?: string;\n /** Routing policy currently in force (provider lifecycle is reconciled live). */\n #routingConfig: ResolvedRoutingConfig;\n /** Applies routing lifecycle changes (enable/disable, provider rename) live. */\n #reconfigureRouting?: (routing: ResolvedRoutingConfig) => void;\n /** Reads how many provider registrations this activation made in total. */\n #routingRegistrationEvents?: () => number;\n /** Backend rebuilds performed by this activation (diagnostics/measurement). */\n #backendRebuilds = 0;\n /** Ledger sink switches performed by this activation. */\n #ledgerSwitches = 0;\n\n /**\n * @param config - resolved plugin configuration.\n * @param dependencies - test seams for the ledger, backend, and routing clock,\n * plus the raw config (whose volatile references carry live updates) and a\n * diagnostic sink.\n */\n constructor(\n config: ResolvedReflexConfig,\n dependencies: {\n backend?: DecisionBackend;\n ledger?: DecisionLedger;\n now?: () => number;\n configSource?: unknown;\n warn?: (message: string) => void;\n } = {}\n ) {\n this.config = config;\n // One stable delegate: the services below close over it, and a config save\n // swaps the transport inside it instead of rebuilding them.\n this.#liveBackend = new LiveBackend(dependencies.backend ?? createBackend(config));\n this.#backendSwappable = dependencies.backend === undefined;\n this.#backendSignature = backendSignature(config);\n this.backend = this.#liveBackend as unknown as DecisionBackend;\n this.ledger = dependencies.ledger ?? new DecisionLedger(config.ledgerPath ?? null);\n this.#systemOneConfig = config.systemOne;\n this.#backendSelector = config.backend;\n this.#ledgerPath = config.ledgerPath;\n this.#routingConfig = config.routing;\n this.calibrator = config.calibrationPath ? new Calibrator(config.calibrationPath) : new Calibrator();\n this.gateService = new ReflexGateService(this.backend, this.ledger, this.calibrator);\n this.pruneService = new ToolResultPruner(this.backend, this.ledger, config.pruneThreshold);\n this.stagnationService = new StagnationDetector(this.backend, this.ledger);\n this.routeService = new ReflexRouter(this.backend, this.ledger);\n this.screenService = new ReflexScreenService(this.backend, this.ledger);\n this.#source = dependencies.configSource;\n this.#warn = dependencies.warn ?? (() => {});\n this.#interventionsConfig = config.interventions;\n this.#pruneThreshold = config.pruneThreshold;\n this.#toolsConfig = config.tools;\n this.#toolPrefix = config.toolPrefix;\n const initialMark = dependencies.configSource === undefined ? [] : volatileSnapshots(dependencies.configSource);\n this.#mark = initialMark;\n this.#watchable = initialMark.length > 0;\n this.#modelRouter = new VirtualModelRouter({\n virtualProvider: config.routing.virtualProvider,\n models: config.routing.models,\n backendName: this.backend.name,\n ledger: this.ledger,\n route: (goal, candidates, topK, input) =>\n this.routeService.selectBest(goal, candidates, topK, { record: false, ...(input ?? {}) }),\n ...(config.routing.fallback ? { fallback: config.routing.fallback } : {}),\n ...(dependencies.now ? { now: dependencies.now } : {}),\n // The loader commits a config-only update without remounting the plugin;\n // this is how every routing decision and panel read sees the new policy.\n refresh: () => { this.refreshIfChanged(); }\n });\n this.effortStatusFeed = new EffortStatusFeed();\n this.effort = new EffortInterceptor({\n ...(config.effort.setting === undefined ? {} : { setting: config.effort.setting }),\n enabled: config.effort.enabled,\n fallback: config.effort.fallback,\n minConfidence: config.effort.minConfidence,\n decide: (request) => this.backend.choice(request),\n backendName: this.backend.name,\n ledger: this.ledger,\n feed: this.effortStatusFeed,\n ...(dependencies.now ? { now: dependencies.now } : {})\n });\n }\n\n /** Name of the active decision backend, for diagnostics and tests. */\n get backendName(): string {\n return this.backend.name;\n }\n\n /** The routing policy this activation routes through (live). */\n get modelRouter(): VirtualModelRouter {\n return this.#modelRouter;\n }\n\n /**\n * Route through the process-wide router another activation registered.\n *\n * A reload can leave one provider registration shared by two activations. The\n * shared router is where the live pools and fallback live, so this runtime must\n * read (and refresh) that one — a private copy would show the panel, and route\n * requests, on a policy nobody applies.\n * @param router - the shared router the virtual provider dispatches through.\n */\n adoptModelRouter(router: VirtualModelRouter): void {\n this.#modelRouter = router;\n }\n\n /**\n * Health of the backend's gateway conversation, or `undefined` for a backend\n * that answers every call in-process.\n *\n * Read by the settings panel and `/reflex-ledger`; never passed to a model.\n * @returns a copy of the counters.\n */\n systemOneHealth(): BackendHealth | undefined {\n return this.#liveBackend.currentHealth();\n }\n\n /**\n * Multi-class choice, with the deployment's calibration curve applied to the\n * winning confidence when one is loaded.\n * @param request - question, options, and optional context.\n * @returns the choice response plus the calibrated confidence, when available.\n */\n async choice(request: { question: string; options: string[]; context?: string }): Promise<ReflexChoiceResult> {\n this.#assertLive();\n const started = performance.now();\n const result = await this.backend.choice(request);\n\n let calibratedConfidence: number | undefined;\n if (this.calibrator.isLoaded()) {\n calibratedConfidence = this.calibrator.calibrate(result.confidence).calibrated;\n }\n\n this.ledger.record({\n type: 'choice',\n backend: this.backend.name,\n latencyMs: Math.round(performance.now() - started),\n details: { action: 'choice', options: request.options.length }\n });\n\n return { ...result, calibratedConfidence };\n }\n\n /**\n * Continuous 0.0 – 1.0 scoring projected from one choice call.\n * @param request - statement, rubric, and optional context.\n * @returns the score response recorded in the ledger.\n */\n async score(request: { statement: string; criteria?: string; context?: string }): Promise<Awaited<ReturnType<typeof scoreStatement>>> {\n this.#assertLive();\n const result = await scoreStatement(this.backend, request);\n\n this.ledger.record({\n type: 'choice',\n backend: this.backend.name,\n latencyMs: result.latencyMs,\n details: { action: 'score', score: result.score }\n });\n\n return result;\n }\n\n /**\n * Rank candidate skills/tools against a goal.\n * @param request - goal, candidates, and how many to return.\n * @returns the ranked candidates.\n */\n async route(request: { goal: string; candidates: CandidateItem[]; topK?: number }): Promise<RouteResponse> {\n this.#assertLive();\n return this.routeService.selectBest(request.goal, request.candidates, request.topK ?? 3);\n }\n\n /**\n * Screen untrusted content for prompt injection and instruction hijacking.\n * @param request - content, its source, and whether to force deep screening.\n * @returns the screening verdict and a sanitized fence when unsafe.\n */\n async screen(request: {\n content: string;\n source?: 'tool_output' | 'web_page' | 'user_input' | 'file_content';\n strict?: boolean;\n }): Promise<ScreenResult> {\n this.#assertLive();\n return this.screenService.screen(request);\n }\n\n /**\n * Fail-closed verification of assertions against evidence.\n * @param request - assertions, evidence, and optional strictness.\n * @returns one outcome per assertion plus the overall verdict.\n */\n async gate(request: {\n assertions: Array<{ statement: string; criteria?: string }>;\n evidence: string;\n strictness?: 'high' | 'normal' | 'lenient';\n }): Promise<GateResponse> {\n this.#assertLive();\n return this.gateService.verify(request.assertions, request.evidence, { strictness: request.strictness });\n }\n\n /**\n * Prune bulky output, preserving the lines the intent depends on.\n *\n * Programmatic seam for the pruning capability: the automatic intervention\n * layer drives {@link pruneService} directly, and this entry point stays for\n * in-process callers (tests, diagnostics, an embedding Host).\n * @param request - raw output, lookup intent, and shadow-mode flag.\n * @returns the compacted payload and the measured token savings.\n */\n async prune(request: { rawOutput: string; intent?: string; shadowMode?: boolean }): Promise<ReflexPruneResult> {\n this.#assertLive();\n const result: PruneResponse = await this.pruneService.prune(request.rawOutput, {\n intent: request.intent,\n shadowMode: request.shadowMode\n });\n\n return {\n tokensSaved: result.estimatedTokensSaved,\n reductionPercentage: `${result.reductionPercentage}%`,\n shadow: result.shadow,\n processedOutput: result.processedOutput\n };\n }\n\n /**\n * Record one action and check whether the run is stagnating.\n *\n * `history` exists for callers that bring their own run: a resumed session, a\n * delegated agent, or a caller that did not record its steps through this\n * tool. Supplied steps are treated as earlier than the ones recorded here, so\n * a caller can hand over a whole run and still add the action it just took.\n *\n * Programmatic seam for the stagnation capability: the automatic intervention\n * layer drives {@link stagnationService} directly, and this entry point stays\n * for in-process callers.\n *\n * @param request - the action just taken, the overall goal, and any prior steps.\n * @returns the stagnation verdict and corrective suggestion.\n */\n async detectStagnation(request: {\n goal?: string;\n recentAction?: ActionStep;\n history?: readonly ActionStep[];\n }): Promise<StagnationCheckResponse> {\n this.#assertLive();\n if (request.recentAction) this.stagnationService.recordAction(request.recentAction);\n return this.stagnationService.check(request.goal, request.history);\n }\n\n /**\n * Read the decision ledger.\n *\n * Programmatic seam behind `/reflex-ledger`: the Host command formats this\n * same read for a person, and an embedding Host can call it directly. Nothing\n * in the tool surface depends on it.\n * @param request - whether to attach the ten most recent entries.\n * @returns the aggregate summary and, on request, recent entries.\n */\n statusLedger(request: { includeEntries?: boolean } = {}): ReflexLedgerResult {\n this.#assertLive();\n const summary = this.ledger.getSummary();\n const health = this.systemOneHealth();\n const base: ReflexLedgerResult = health === undefined ? { summary } : { summary, systemOneHealth: health };\n if (!request.includeEntries) return base;\n return { ...base, recentEntries: this.ledger.getEntries().slice(-10) };\n }\n\n /**\n * Publish the reflex tool names this activation currently owns, so a Host\n * observer can mirror the live surface.\n * @param names - the registered tool names.\n */\n noteToolSurface(names: readonly string[]): void {\n this.#surface = [...names];\n }\n\n /** The reflex tool names of this activation. */\n get toolSurface(): readonly string[] {\n return this.#surface;\n }\n\n /**\n * The latest adaptive effort decision this activation published.\n * @param agentId - agent to read; omitted reads the most recent of any agent.\n * @returns the status, or `undefined` before the first decided turn.\n */\n effortStatus(agentId?: string): ReflexEffortStatus | undefined {\n return this.effortStatusFeed.latest(agentId);\n }\n\n /**\n * The status-bar line of the latest adaptive effort decision.\n * @param agentId - agent to read; omitted reads the most recent of any agent.\n * @returns the rendered line, or `undefined` before the first decided turn.\n */\n effortStatusLine(agentId?: string): string | undefined {\n return this.effortStatusFeed.statusLine(agentId);\n }\n\n /**\n * Attach the automatic-intervention engine of this activation.\n *\n * Set by the plugin lifecycle right after the listeners are installed, so the\n * panel and the tests read the same engine the hooks drive. Absent when every\n * capability is `off`: nothing is installed, and nothing is reported.\n *\n * The optional reconfiguration seam is what makes a config-only save live: the\n * installer owns the listeners (which hooks exist depends on the capability\n * modes), so swapping thresholds or turning a capability on/off has to go\n * through it rather than through the engine alone.\n * @param engine - the engine behind this activation's listeners.\n * @param reconfigure - applies a new resolved policy to the listeners.\n * @param listenerCount - reads how many listeners are currently attached.\n */\n attachInterventions(\n engine: InterventionEngine | undefined,\n reconfigure?: (config: ResolvedInterventionsConfig, pruneThreshold: number) => void,\n listenerCount?: () => number\n ): void {\n this.#interventions = engine;\n this.#reconfigureInterventions = reconfigure;\n this.#interventionListenerCount = listenerCount;\n }\n\n /**\n * How many intervention listeners this activation currently has attached.\n *\n * `0` is the honest answer of an `off` deployment: the capability is absent,\n * not a listener that checks a flag on every hook.\n */\n get interventionListenerCount(): number {\n return this.#interventionListenerCount?.() ?? 0;\n }\n\n /** The automatic-intervention engine, when this activation installed one. */\n get interventions(): InterventionEngine | undefined {\n return this.#interventions;\n }\n\n /**\n * Attach the tool-surface reconciler of this activation.\n *\n * Set by the plugin lifecycle right after the tools are registered. The\n * registry lives on the Host context, not on this runtime, so a config-only\n * save has to call back out to the installer that owns the registrations. The\n * seam is also what lets the tests prove idempotence: an unchanged save must\n * not unregister and re-register anything.\n * @param reconfigure - reconciles the registered set with a new resolved config.\n * @param registrationCount - reads how many tools are currently registered.\n * @param registrationEvents - reads how many registrations happened in total.\n */\n attachToolSurface(\n reconfigure?: (config: ResolvedReflexConfig) => void,\n registrationCount?: () => number,\n registrationEvents?: () => number\n ): void {\n this.#reconfigureTools = reconfigure;\n this.#toolRegistrationCount = registrationCount;\n this.#toolRegistrationEvents = registrationEvents;\n }\n\n /**\n * Attach the routing-lifecycle reconciler of this activation.\n *\n * The provider registration lives on the LLM runtime, not on this runtime, so\n * enabling/disabling the route or renaming the virtual provider on a\n * config-only save has to call back out to the installer that owns it.\n * @param reconfigure - applies the routing lifecycle of a freshly resolved config.\n * @param registrationEvents - reads how many provider registrations happened.\n */\n attachRouting(\n reconfigure?: (routing: ResolvedRoutingConfig) => void,\n registrationEvents?: () => number\n ): void {\n this.#reconfigureRouting = reconfigure;\n this.#routingRegistrationEvents = registrationEvents;\n }\n\n /** Provider registrations this activation made (monotonic; diagnostics). */\n get routingRegistrationEvents(): number {\n return this.#routingRegistrationEvents?.() ?? 0;\n }\n\n /** Backend rebuilds this activation performed (0 when a seam supplied one). */\n get backendRebuilds(): number {\n return this.#backendRebuilds;\n }\n\n /** Ledger sink switches this activation performed. */\n get ledgerSwitches(): number {\n return this.#ledgerSwitches;\n }\n\n /** The number of reflex tools this activation currently has registered. */\n get toolRegistrationCount(): number {\n return this.#toolRegistrationCount?.() ?? 0;\n }\n\n /**\n * How many `tools.register` calls this activation has made since it loaded.\n *\n * Monotonic on purpose: an idempotent save leaves it unchanged, which is the\n * measurement a test can assert without spying on the registry.\n */\n get toolRegistrationEvents(): number {\n return this.#toolRegistrationEvents?.() ?? 0;\n }\n\n /**\n * The configuration the panel and diagnostics must report: the values\n * currently in force for every block this slice has made live.\n *\n * The panel promise is \"show what is in force\", not \"show what was written at\n * startup\". `effort`, `interventions`, `pruneThreshold`, `tools` and\n * `toolPrefix` are read from their live fields; blocks whose live path is a\n * separate slice (backend, ledger sink, route lifecycle) keep reporting their\n * activation values until that slice lands.\n */\n get effectiveConfig(): ResolvedReflexConfig {\n const models = this.modelRouter.models;\n const fallback = this.modelRouter.fallback;\n return {\n ...this.config,\n backend: this.#backendSelector,\n ledgerPath: this.#ledgerPath,\n toolPrefix: this.#toolPrefix,\n tools: this.#toolsConfig,\n systemOne: this.#systemOneConfig,\n routing: {\n enabled: this.#routingConfig.enabled,\n maxTaskChars: this.#routingConfig.maxTaskChars,\n // The router is the live source of the provider name and the pools: a\n // rename is applied there first, and every surface must agree with it.\n virtualProvider: this.modelRouter.virtualProvider,\n models,\n ...(fallback === undefined ? {} : { fallback })\n },\n effort: { ...this.effort.policy },\n interventions: this.#interventionsConfig,\n pruneThreshold: this.#pruneThreshold\n };\n }\n\n /**\n * Full schema resolutions this activation performed.\n *\n * Incremented only by {@link refresh}; the request/step/tool hot paths never\n * resolve the schema, which is the measurement this counter makes provable.\n */\n get configResolveCount(): number {\n return this.#configResolves;\n }\n\n /** Whether the owning plugin activation has been disposed. */\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /**\n * Re-read this activation's live policy from its config.\n *\n * Called when the Host reports a config commit (`loader/volatile-update`) and\n * lazily once per `agent/pre-step`. The schema runs here — once per actual\n * commit — and nowhere on the request/tool hot paths.\n *\n * Applied without a remount:\n * - routing pools and fallback (replaced in the router);\n * - the whole adaptive-effort policy (switch, marker, fallback, confidence\n * floor), read live by the request interception and the selector surface;\n * - the intervention thresholds and capability modes, with the listeners\n * added or removed according to the effective modes;\n * - the per-tool switches and the deployment prefix, with the registry\n * reconciled by the installer through {@link attachToolSurface}. The\n * reconciler is idempotent: a commit that changes neither the enabled\n * suffixes nor the prefix unregisters and re-registers nothing;\n * - the decision backend and its connection settings, rebuilt only on a\n * transport-relevant change (health starts fresh on the new backend);\n * - the ledger sink, migrated in place so no recorded entry is lost;\n * - the routing lifecycle (enabled switch, virtual-provider rename) through\n * {@link attachRouting}, and the task budget read per step.\n * @returns whether a new policy was applied.\n */\n refresh(): boolean {\n if (this.#source === undefined || this.#disposed || this.#refreshing) return false;\n this.#refreshing = true;\n try {\n let resolved: ResolvedReflexConfig;\n try {\n resolved = resolveConfig(this.#source as ReflexConfig);\n } catch (error) {\n this.#warn(\n `dsh-reflex: the updated configuration cannot be applied (${(error as Error).message}); keeping the previous live values`\n );\n return false;\n }\n this.#configResolves += 1;\n\n // Backend and connection: rebuild only when something that shapes the\n // transport changed. A same-value commit touches nothing (idempotence), and\n // the services keep dispatching through the same delegate.\n const nextSignature = backendSignature(resolved);\n if (this.#backendSwappable && nextSignature !== this.#backendSignature) {\n this.#liveBackend.swap(createBackend(resolved));\n this.#backendSignature = nextSignature;\n this.#backendRebuilds += 1;\n }\n this.#systemOneConfig = resolved.systemOne;\n this.#backendSelector = resolved.backend;\n\n // Ledger sink: move the JSONL target in place, migrating the in-memory\n // history into the new file so entries recorded before the switch survive.\n if (resolved.ledgerPath !== this.#ledgerPath) {\n const switched = (this.ledger as { switchLogPath?: (path?: string | null) => boolean }).switchLogPath?.(\n resolved.ledgerPath ?? null\n );\n this.#ledgerPath = resolved.ledgerPath;\n if (switched) this.#ledgerSwitches += 1;\n }\n\n // The prune threshold is read live by the direct prune seam as well as by\n // the intervention engine's projection.\n this.pruneService.setMinCharsThreshold(resolved.pruneThreshold);\n\n this.#modelRouter.updatePolicy({\n models: resolved.routing.models,\n ...(resolved.routing.fallback ? { fallback: resolved.routing.fallback } : {})\n });\n this.#routingConfig = resolved.routing;\n this.effort.updatePolicy({\n enabled: resolved.effort.enabled,\n ...(resolved.effort.setting === undefined ? {} : { setting: resolved.effort.setting }),\n fallback: resolved.effort.fallback,\n minConfidence: resolved.effort.minConfidence\n });\n this.#interventionsConfig = resolved.interventions;\n this.#pruneThreshold = resolved.pruneThreshold;\n // The tool block is applied before the intervention reconfigure so the\n // callback can derive the renamed `ownTools` set from this runtime's live\n // values rather than from the activation-time snapshot.\n this.#toolsConfig = resolved.tools;\n this.#toolPrefix = resolved.toolPrefix;\n this.#reconfigureInterventions?.(resolved.interventions, resolved.pruneThreshold);\n this.#reconfigureTools?.(resolved);\n // Routing lifecycle last: enabling/disabling the route and renaming the\n // provider may recreate the shared router, and the panel/tool surfaces read\n // the routing block after the pools have been replaced.\n this.#reconfigureRouting?.(resolved.routing);\n this.#mark = volatileSnapshots(this.#source);\n return true;\n } finally {\n this.#refreshing = false;\n }\n }\n\n /**\n * Refresh only when the loader actually committed a new config value.\n *\n * The volatile references hand out a new snapshot object on every commit, so\n * an identity comparison over them is O(config blocks) and never runs the\n * schema again for an unchanged config.\n * @returns whether a new policy was applied.\n */\n refreshIfChanged(): boolean {\n if (!this.#watchable || this.#source === undefined || this.#disposed || this.#refreshing) return false;\n const next = volatileSnapshots(this.#source);\n const previous = this.#mark;\n const unchanged =\n next.length === previous.length && next.every((snapshot, index) => snapshot === previous[index]);\n if (unchanged) return false;\n return this.refresh();\n }\n\n /** Release the runtime. Called from the plugin's `ctx.effect` cleanup. */\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n // No residue on unload: the per-agent detection state, the reduction memo,\n // and the accounts of the intervention engine are dropped with the runtime,\n // exactly like the effort feed and the ledger.\n this.#interventions?.reset();\n this.#interventions = undefined;\n this.#reconfigureRouting = undefined;\n this.effortStatusFeed.clear();\n this.ledger.clear();\n }\n\n #assertLive(): void {\n if (this.#disposed) throw new Error('reflex runtime has been disposed');\n }\n}\n\n/**\n * Identity of the configuration that shapes the decision transport.\n *\n * A config-only save re-resolves the whole document; rebuilding the backend for\n * a change that cannot affect it would reset health and drop the connection for\n * no reason. This signature lets {@link ReflexRuntime.refresh} rebuild exactly\n * when the transport's identity changed.\n * @param config - resolved plugin configuration.\n * @returns a stable string of the transport-relevant fields.\n */\nfunction backendSignature(config: ResolvedReflexConfig): string {\n const { backend, systemOne, interventions } = config;\n return JSON.stringify([\n backend,\n systemOne.baseUrl ?? '',\n systemOne.model ?? '',\n systemOne.apiKeyEnv ?? '',\n systemOne.timeoutMs ?? null,\n interventions.pruneJudgeMinChars\n ]);\n}\n\n/**\n * Build the backend a plugin activation should use.\n *\n * The connection block of the resolved config overrides the environment for\n * this plugin instance only: the backend implementations already fall back to\n * the environment for every omitted option, so an explicitly configured\n * deployment and an env-configured one behave the same when the block is empty.\n * @param config - resolved plugin configuration.\n * @param env - environment the API-key indirection reads; defaults to `process.env`.\n * @returns the forced backend, or one chosen from the environment for `auto`.\n */\nexport function createBackend(\n config: ResolvedReflexConfig,\n env: Record<string, string | undefined> = process.env\n): DecisionBackend {\n const { backend, baseUrl, model, timeoutMs } = config.systemOne;\n const apiKey = resolveApiKey(config.systemOne, env);\n switch (backend) {\n case 'mock':\n return new MockDecisionBackend();\n case 'jev':\n return new JevDecisionBackend({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n ...(model === undefined ? {} : { model }),\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n // The resolved config wins over SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS: the\n // backend only reads the environment when no explicit value is given.\n pruneJudgeMinChars: config.interventions.pruneJudgeMinChars\n });\n case 'vllm':\n return new SimpleJevDecisionBackend({\n ...(baseUrl === undefined ? {} : { vllmBaseUrl: baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n ...(model === undefined ? {} : { model }),\n ...(timeoutMs === undefined ? {} : { timeoutMs })\n });\n default:\n return createSystemOneBackend();\n }\n}\n\n/**\n * Build a runtime for one plugin activation.\n * @param config - resolved plugin configuration.\n * @param dependencies - test seams for the ledger, backend, and routing clock.\n * @returns the runtime the tools close over.\n */\nexport function createReflexRuntime(\n config: ResolvedReflexConfig,\n dependencies: {\n backend?: DecisionBackend;\n ledger?: DecisionLedger;\n now?: () => number;\n configSource?: unknown;\n warn?: (message: string) => void;\n } = {}\n): ReflexRuntime {\n return new ReflexRuntime(config, dependencies);\n}\n"]}
1
+ {"version":3,"file":"bridge.js","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAIrD,OAAO,EACL,UAAU,EACV,cAAc,EACd,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EACnB,wBAAwB,EACxB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACf,MAAM,kCAAkC,CAAC;AAsB1C,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,aAAa,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACjI,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAA2B,MAAM,aAAa,CAAC;AAI3F,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EACpB,4BAA4B,EAK7B,MAAM,kBAAkB,CAAC;AAyC1B;;;;;;;;;;GAUG;AACH,MAAM,WAAW;IACf,OAAO,CAAkB;IAEzB,YAAY,MAAuB;QACjC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED,6DAA6D;IAC7D,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;IAED,iEAAiE;IACjE,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;IAC5B,CAAC;IAED,yDAAyD;IACzD,IAAI,CAAC,IAAqB;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC;QAC9B,IAAI,CAAC,OAAO,GAA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E,KAAK,EAAE,CAAC;gBACzC,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC;aAClD,CAAC,CAAC;IACP,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA4B,EAC5B,eAMI,EAAE;IAEN,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { Agent } from '@deepseek-ai/dsh-agent';\n\nimport {\n Calibrator,\n DecisionLedger,\n JevDecisionBackend,\n MockDecisionBackend,\n ReflexGateService,\n ReflexRouter,\n ReflexScreenService,\n SimpleJevDecisionBackend,\n StagnationDetector,\n ToolResultPruner,\n scoreStatement\n} from './vendor/harness-reflex/index.js';\nimport type {\n ActionStep,\n BackendHealth,\n CandidateItem,\n ChoiceResponse,\n DecisionBackend,\n GateResponse,\n PruneResponse,\n RouteResponse,\n ScreenResult,\n StagnationCheckResponse\n} from './vendor/harness-reflex/index.js';\n\nimport type {\n ReflexConfig,\n ResolvedInterventionsConfig,\n ResolvedReflexConfig,\n ResolvedRoutingConfig,\n ResolvedSystemOneConfig,\n ResolvedToolsConfig\n} from './config.js';\nimport { connectionImplementation, resolveApiKeyWithSource, resolvedKeyOf, resolveConfig, volatileSnapshots } from './config.js';\nimport { EffortInterceptor, EffortStatusFeed, type ReflexEffortStatus } from './effort.js';\nimport type { DelegatedEffortInheritance } from './effort-delegation.js';\nimport type { DelegationHealth } from './delegation-health.js';\nimport type { InterventionEngine } from './interventions.js';\nimport { UnconfiguredBackend } from './unconfigured-backend.js';\nimport { VirtualModelRouter } from './router.js';\nimport {\n attributionOf,\n callIdentity,\n classifyEvidence,\n ledgerAttribution,\n MOCK_CONNECTION_NAME,\n UNCONFIGURED_CONNECTION_NAME,\n type Attribution,\n type CallIdentity,\n type CallSource,\n type SourceEvidence\n} from './attribution.js';\n\n/**\n * What one dispatch observed about itself.\n *\n * `identity` is taken *before* the call is awaited (see {@link callIdentity}),\n * so a profile switch during an in-flight call cannot restate it; `source` is\n * filled once the call settles. The pair travels together into the tool payload\n * and the ledger entry, which is what keeps the two surfaces agreeing.\n */\ninterface DispatchOutcome {\n readonly identity: CallIdentity;\n readonly source: CallSource;\n readonly detail?: string;\n}\n\n/** Payload of the `choice` operation, mirroring the stdio MCP surface. */\nexport type ReflexChoiceResult = ChoiceResponse & { calibratedConfidence?: number } & Attribution;\n\n/** Payload of the `prune` operation, mirroring the stdio MCP surface. */\nexport interface ReflexPruneResult extends Attribution {\n tokensSaved: number;\n reductionPercentage: string;\n shadow: boolean;\n processedOutput: string;\n}\n\n/** Payload of the ledger read, mirroring the stdio MCP `status_ledger` payload. */\nexport interface ReflexLedgerResult {\n summary: ReturnType<DecisionLedger['getSummary']>;\n recentEntries?: ReturnType<DecisionLedger['getEntries']>;\n /**\n * Health of the backend at read time, when it tracks one.\n *\n * `/reflex-ledger` prints a degraded notice from it. It is deliberately not\n * part of any model-facing tool payload: a health warning is a diagnostics\n * fact for the person reading the command, not context for the agent.\n */\n systemOneHealth?: BackendHealth;\n}\n\n/**\n * A decision backend whose implementation can be swapped while services keep\n * their reference to it.\n *\n * The five decision services are built once and close over their backend. A\n * config-only save can change `backend`/`systemOne.*`, and rebuilding those\n * services would drop their ledger/audit wiring; delegating through one stable\n * object swaps the transport instead, so the next decision reaches the new\n * endpoint/model while the services stay put. Health is the delegate's, so a\n * freshly built backend starts at `available: true, consecutiveFailures: 0`.\n */\nclass LiveBackend {\n #target: DecisionBackend;\n\n constructor(target: DecisionBackend) {\n this.#target = target;\n }\n\n /** Name of the backend implementation currently in force. */\n get name(): string {\n return this.#target.name;\n }\n\n /** Model id of the backend implementation currently in force. */\n get model(): string {\n return this.#target.model;\n }\n\n /** Replace the transport, releasing the previous one. */\n swap(next: DecisionBackend): void {\n const previous = this.#target;\n this.#target = next;\n const dispose = (previous as { dispose?: () => void }).dispose;\n if (typeof dispose === 'function') {\n try {\n dispose.call(previous);\n } catch {\n // A backend that cannot release its transport must not veto the swap.\n }\n }\n }\n\n choice(request: Parameters<DecisionBackend['choice']>[0]): ReturnType<DecisionBackend['choice']> {\n return this.#target.choice(request);\n }\n\n gate(request: Parameters<DecisionBackend['gate']>[0]): ReturnType<DecisionBackend['gate']> {\n return this.#target.gate(request);\n }\n\n prune(request: Parameters<DecisionBackend['prune']>[0]): ReturnType<DecisionBackend['prune']> {\n return this.#target.prune(request);\n }\n\n checkStagnation(request: Parameters<DecisionBackend['checkStagnation']>[0]): ReturnType<DecisionBackend['checkStagnation']> {\n return this.#target.checkStagnation(request);\n }\n\n route(request: Parameters<DecisionBackend['route']>[0]): ReturnType<DecisionBackend['route']> {\n return this.#target.route(request);\n }\n\n classifyClaims(request: Parameters<DecisionBackend['classifyClaims']>[0]): ReturnType<DecisionBackend['classifyClaims']> {\n return this.#target.classifyClaims(request);\n }\n\n /** Health of the backend currently in force (absent for in-process backends). */\n currentHealth(): BackendHealth | undefined {\n const health = (this.#target as Partial<DecisionBackend>).health;\n return typeof health === 'function' ? health.call(this.#target) : undefined;\n }\n}\n\n/**\n * The slice of {@link DecisionLedger} a decision service uses.\n *\n * Declared structurally so this decorator never pretends to be the ledger: the\n * services only ever call `record`, and the runtime keeps the real ledger for\n * every other read.\n */\ntype LedgerSink = Pick<DecisionLedger, 'record'>;\n\n/**\n * One call's held ledger entry: what the service built, plus its identity.\n *\n * Held rather than written, because the *source* of an answer is not knowable\n * until the answer settles (see {@link AttributedLedger}).\n */\ninterface HeldEntry {\n readonly entry: Parameters<DecisionLedger['record']>[0];\n readonly identity: CallIdentity;\n}\n\n/**\n * One already-attributed call, for callers that drive a decision service\n * themselves instead of going through {@link ReflexRuntime.choice} and friends.\n *\n * `ledger` is the call's private buffer; `settle` appends it once the source is\n * known and returns the attribution to put on the caller's own payload.\n */\nexport interface CallRing {\n /** The ledger ring this call's service entries are buffered in. */\n readonly ledger: LedgerSink;\n /**\n * Close the ring: append its entries with the final source.\n * @param outcome - the settled source.\n * @returns the attribution for the caller's payload.\n */\n settle(outcome: { source: CallSource; detail?: string }): Attribution;\n}\n\n/**\n * The attributed, append-only ledger sink every decision service writes through.\n *\n * ## Why a decorator rather than fields on the entry (g-068)\n *\n * `ReflexGateService`, `ReflexRouter`, `ToolResultPruner` and the rest write\n * their *own* ledger entry while they run, and that entry is the one a reader\n * sees. `DecisionLedger` is shared with the root stdio MCP package, whose\n * contract g-068 must not touch, so this layer keeps the provenance inside the\n * entry's existing open `details` bag instead of adding fields to it.\n *\n * ## Per-call isolation (the att-001 review's BLOCK-1)\n *\n * The first attempt kept **one** \"current stamp\" field and cleared it in a\n * `finally`. Two overlapping calls then destroyed each other's attribution: the\n * fast call's clear wiped the slow call's stamp, the slow call's service entry\n * was written unattributed, and its payload still said `local-fallback`. The\n * ledger and the payload disagreed about the same call, which is the exact\n * falsehood this goal exists to remove. There is no single shared field any\n * more: {@link open} returns a *token*, a service's entry is held in a buffer\n * **owned by that token**, and nothing a concurrent call does can reach it.\n *\n * ## Written once, finished, never rewritten (BLOCK-2)\n *\n * A service writes its entry *before* the answer settles, when `source` is still\n * unknown. Stamp-then-rewrite-the-last-JSONL-line was the first attempt's answer\n * to that, and it was wrong twice over: it rewrote a line that might belong to\n * another call, and rewriting a whole file is an append-only violation that can\n * truncate a sink another writer is appending to. Here the service's entry is\n * **buffered** on its token; when the call settles, {@link finish} appends that\n * one entry exactly once — identity *and* source together, already final. An\n * unregistered token (a call that threw before settling) falls back to the\n * buffered group in {@link flush}, so no entry is ever lost. The JSONL file is\n * therefore only ever appended to: no line is rewritten and no line is moved.\n *\n * ## Why attribution can honestly be `unknown`\n *\n * A call whose outcome cannot be proven must say so rather than claim `remote`.\n * Two paths reach that state and both end up here: a backend that exposes no\n * failure record at all (the vLLM logits backend) and a call whose service entry\n * was written after the call had already settled ({@link AttributedLedger.report}\n * explains how). See {@link classifyEvidence}.\n */\nexport class AttributedLedger {\n /** Open calls: the identity each token was opened with, and the entries it holds. */\n readonly #openCalls = new Map<number, { identity: CallIdentity; held: HeldEntry[] }>();\n /** Call tokens in dispatch order; settled calls are removed as they finish. */\n readonly #settleOrder: number[] = [];\n /** Entries a service wrote while no call was open, if any. */\n #unattributed: Array<Parameters<DecisionLedger['record']>[0]> = [];\n #nextToken = 0;\n /** Set when a call settled while its own entry was still unaccounted for. */\n #aCallLandedLate = false;\n\n /**\n * @param target - the activation's real ledger sink.\n */\n constructor(private readonly target: LedgerSink) {}\n\n /**\n * Open one call's ledger context.\n * @param identity - the identity taken at dispatch, before the call is awaited.\n * @returns the token to settle the call with, and the sink its services write through.\n */\n open(identity: CallIdentity): { token: number; ledger: LedgerSink } {\n const token = this.#nextToken;\n this.#nextToken += 1;\n this.#openCalls.set(token, { identity, held: [] });\n this.#settleOrder.push(token);\n return { token, ledger: this.#sinkFor(token) };\n }\n\n /**\n * The sink one call's services write through.\n *\n * A token that is no longer open (only a service writing *after* its own call\n * settled can hit this) buffers into the shared group that {@link flush}\n * settles as `unknown`, rather than being dropped.\n * @param token - the call's token.\n * @returns the sink to hand a decision service.\n */\n #sinkFor(token: number): LedgerSink {\n return {\n record: (entry) => {\n const call = this.#openCalls.get(token);\n if (call !== undefined) {\n // Buffered, not written: the same object is appended once the call\n // settles, so the entry a reader sees is final the first time.\n call.held.push({ entry, identity: call.identity });\n } else {\n this.#unattributed.push(entry);\n }\n // The service owns this return value only to log it; the entry it will\n // actually be read from is the one appended at settlement.\n return { ...entry, id: '', timestamp: '' } as ReturnType<DecisionLedger['record']>;\n }\n };\n }\n\n /**\n * The sink a service writes through when no call is in force.\n *\n * A service driven directly — the automatic-intervention engine, a\n * programmatic caller, a test — has no dispatch context to attribute it to.\n * Its entry is appended **immediately** (dropping it would lose an audited\n * judgment) with the source the service itself reported when it reported one\n * (a `systemOneSource`-style field on the entry), and `unknown` otherwise. It is\n * never left to read as a remote success.\n * @param token - the identity-less call id, for logging only.\n * @returns the unattributed sink.\n */\n unattributedSink(): LedgerSink {\n return {\n record: (entry) => {\n // A service may have been given its provenance by a caller that knew it\n // (the intervention engine attributes the call itself). Honour that;\n // otherwise say plainly that nothing proves where the answer came from.\n const claimed = typeof entry.details?.systemOneSource === 'string';\n this.target.record({\n ...entry,\n details: {\n ...entry.details,\n ...(claimed\n ? {}\n : ledgerAttribution({\n connectionName: 'unknown',\n requestedModel: null,\n source: 'unknown',\n detail: 'the entry was written outside the call it belongs to'\n }))\n }\n } as typeof entry);\n return { ...entry, id: '', timestamp: '' } as ReturnType<DecisionLedger['record']>;\n }\n };\n }\n\n /** Close one token's context, returning what it held. */\n #close(token: number): HeldEntry[] {\n const call = this.#openCalls.get(token);\n this.#openCalls.delete(token);\n const at = this.#settleOrder.indexOf(token);\n if (at !== -1) this.#settleOrder.splice(at, 1);\n return call?.held ?? [];\n }\n\n /**\n * Append what one call held, once, with the final source.\n *\n * The source is written into `details` here — the last moment it is knowable\n * and the only moment anything is persisted — so no line is ever rewritten.\n * @param token - the call's token.\n * @param outcome - the settled outcome, source included.\n * @returns how many entries this call appended.\n */\n finish(token: number, outcome: DispatchOutcome): number {\n const held = this.#close(token);\n const fields = ledgerAttribution(attributionOf(outcome.identity, outcome));\n for (const item of held) {\n this.target.record({ ...item.entry, details: { ...item.entry.details, ...fields } } as typeof item.entry);\n }\n // A service that wrote only after its call settled left its entry in the\n // shared group, where it cannot be told apart from another call's. Flag the\n // settlement so the runtime can withdraw the claim it would otherwise make.\n if (held.length === 0 && this.#unattributed.length > 0) this.#aCallLandedLate = true;\n return held.length;\n }\n\n /**\n * Append what one call held, with a source that could not be verified.\n * @param token - the call's token.\n * @returns how many entries this call appended.\n */\n finishUnknown(token: number): number {\n const held = this.#close(token);\n const fields = ledgerAttribution({\n connectionName: 'unknown',\n requestedModel: null,\n source: 'unknown',\n detail: 'the call did not settle, so where its answer came from is unproven'\n });\n for (const item of held) {\n this.target.record({\n ...item.entry,\n details: { ...item.entry.details, ...fields, systemOneConnection: item.identity.connectionName, systemOneModel: item.identity.requestedModel }\n } as typeof item.entry);\n }\n return held.length;\n }\n\n /**\n * Append entries that were written while no call was open.\n *\n * They cannot be attributed to a call, so they are marked `unknown` rather\n * than left to read as a remote success.\n * @returns whether any entry was appended.\n */\n flush(): boolean {\n const pending = this.#unattributed;\n this.#unattributed = [];\n for (const entry of pending) {\n const already = typeof entry.details?.systemOneSource === 'string';\n this.target.record({\n ...entry,\n details: {\n ...entry.details,\n ...(already\n ? {}\n : ledgerAttribution({\n connectionName: 'unknown',\n requestedModel: null,\n source: 'unknown',\n detail: 'the entry was written outside the call it belongs to'\n }))\n }\n } as typeof entry);\n }\n return pending.length > 0;\n }\n\n /**\n * Take, once, whether a settled call could not be tied to its own entry.\n * @returns `true` when the last settlement landed late.\n */\n takeLateCall(): boolean {\n const late = this.#aCallLandedLate;\n this.#aCallLandedLate = false;\n return late;\n }\n}\n\n/**\n * In-process System One runtime shared by every reflex tool of one plugin\n * activation.\n *\n * The bridge owns the backend, the audit ledger, and the five decision services,\n * so a plugin reload builds a fresh runtime and drops the previous one whole —\n * no module-level singleton is mutated and nothing survives the activation.\n */\nexport class ReflexRuntime {\n readonly config: ResolvedReflexConfig;\n readonly backend: DecisionBackend;\n readonly ledger: DecisionLedger;\n readonly calibrator: Calibrator;\n readonly gateService: ReflexGateService;\n readonly pruneService: ToolResultPruner;\n readonly stagnationService: StagnationDetector;\n readonly routeService: ReflexRouter;\n readonly screenService: ReflexScreenService;\n /**\n * System 1 virtual→physical model router this activation routes through. It\n * owns the configured pools and writes one `model-route` ledger entry per\n * decision; the plugin installs it on the LLM runtime and dispatches through\n * it. With several live activations the process-wide route has one shared\n * router, and {@link adoptModelRouter} points this runtime at it.\n */\n #modelRouter: VirtualModelRouter;\n /**\n * Per-turn adaptive reasoning-effort policy. It writes one `effort-decision`\n * ledger entry per decided turn and publishes each decision to\n * {@link effortStatusFeed}.\n */\n readonly effort: EffortInterceptor;\n /** Status-bar surface of the adaptive effort decisions of this activation. */\n readonly effortStatusFeed: EffortStatusFeed;\n /**\n * Delegated-agent effort inheritance, when this activation installed one.\n *\n * A delegated agent cannot decide its own effort, so the marker is replaced on\n * its `model/selection` before the step reads it. Held here so the panel and\n * diagnostics can report how often that happened.\n */\n #effortInheritance?: DelegatedEffortInheritance;\n\n #disposed = false;\n #surface: readonly string[] = [];\n /** Reads the live delegation capability; set by the plugin lifecycle. */\n #delegationHealth?: () => DelegationHealth;\n /** Records the agent scope the delegation capability is read in. */\n #noteDelegationScope?: (agent: Agent) => void;\n #interventions?: InterventionEngine;\n /**\n * The config the Host resolved for this activation, kept as it was passed in.\n *\n * With the Cordis loader this object holds schema-declared *volatile\n * references*: a config-only update mutates those references in place and\n * dispatches `loader/volatile-update` instead of remounting the plugin, so\n * this is the only handle that sees the new values. A programmatic caller\n * passes a plain object, in which case there is nothing to watch.\n */\n readonly #source: unknown;\n /** Snapshot identities of {@link #source} at the last applied refresh. */\n #mark: unknown[] = [];\n /** Re-entrancy guard: callbacks during one apply must not resolve again. */\n #refreshing = false;\n /** Whether {@link #source} actually exposes volatile references. */\n readonly #watchable: boolean;\n #warn: (message: string) => void;\n /**\n * The intervention policy currently in force.\n *\n * Kept even when the engine is inert (`mode: off`), so the panel reports the\n * authored block rather than the activation-time snapshot, and so turning a\n * capability back on can install its listeners without a remount.\n */\n #interventionsConfig: ResolvedInterventionsConfig;\n /** The prune threshold currently in force (top-level `pruneThreshold`). */\n #pruneThreshold: number;\n /**\n * The per-tool switches and deployment prefix currently in force.\n *\n * Kept here rather than read from {@link config} because a config-only save\n * never remounts the activation: the registry has to follow the committed\n * values, and the panel has to report the same ones.\n */\n #toolsConfig: ResolvedToolsConfig;\n #toolPrefix: string;\n /**\n * The delegation consent currently in force.\n *\n * A config-only save commits this without remounting the activation, and both\n * the registry and the panel must follow it: reading the startup snapshot here\n * would keep registering (or withholding) `reflex_delegate` after the user\n * ticked the switch.\n */\n #delegationConfig: ResolvedReflexConfig['delegation'];\n /** Applies a freshly resolved intervention policy to the installed listeners. */\n #reconfigureInterventions?: (config: ResolvedInterventionsConfig, pruneThreshold: number) => void;\n /** Reads how many intervention listeners are currently attached. */\n #interventionListenerCount?: () => number;\n /** Reconciles the registered tool set with a freshly resolved config. */\n #reconfigureTools?: (config: ResolvedReflexConfig) => void;\n /** Re-reads the Host delegation capability and reconciles the surface. */\n #refreshDelegation?: () => void;\n /** Reads how many tools this activation currently has registered. */\n #toolRegistrationCount?: () => number;\n /** Reads how many `tools.register` calls this activation has made in total. */\n #toolRegistrationEvents?: () => number;\n /** Full schema resolutions performed by this activation (diagnostics/measurement). */\n #configResolves = 0;\n\n /** The stable delegate all decision services dispatch through. */\n readonly #liveBackend: LiveBackend;\n /**\n * Ledger the whole activation writes through, so an entry a service owns\n * carries the provenance of the call that produced it and is appended once\n * (see {@link AttributedLedger}).\n */\n readonly #attributed: AttributedLedger;\n /**\n * Per-call sinks handed to the shared decision services.\n *\n * The decision services are long-lived and write their own ledger entry, but\n * the call they are serving is per-dispatch. Each dispatch runs its services\n * inside its own {@link #callScope}, so the sink below resolves to *that*\n * call's buffer. This is why no shared \"current stamp\" field exists: a\n * concurrent call cannot see, let alone clear, another call's context.\n */\n readonly tracking: { gate: LedgerSink; prune: LedgerSink; stagnation: LedgerSink; route: LedgerSink; screen: LedgerSink } = {\n gate: { record: (entry) => this.#recordForCurrentCall(entry) },\n prune: { record: (entry) => this.#recordForCurrentCall(entry) },\n stagnation: { record: (entry) => this.#recordForCurrentCall(entry) },\n route: { record: (entry) => this.#recordForCurrentCall(entry) },\n screen: { record: (entry) => this.#recordForCurrentCall(entry) }\n };\n\n /** The dispatch context in force, so a service's `record` finds its own call. */\n readonly #callScope = new AsyncLocalStorage<{ sink: LedgerSink }>();\n\n /**\n * Route one service entry to the call whose context is in force.\n *\n * Falls back to the unattributed group (settled as `unknown`, never dropped)\n * when a service writes outside any dispatch — that only happens for a\n * programmatic caller driving a service directly.\n * @param entry - the entry the service built.\n * @returns the record result the service expects.\n */\n #recordForCurrentCall(entry: Parameters<DecisionLedger['record']>[0]): ReturnType<DecisionLedger['record']> {\n return (this.#callScope.getStore()?.sink ?? this.#attributed.unattributedSink()).record(entry);\n }\n\n /**\n * Hand a decision service an already-attributed payload.\n *\n * The automatic intervention layer ({@link InterventionEngine}) drives the\n * same services directly at Host hook points, so those calls never reach\n * {@link #dispatch}. They still spend a System One judgment, and the goal\n * requires every such call to be attributed — an entry the ledger cannot name\n * is exactly the opacity g-068 removes.\n *\n * The returned ring is the call's own ledger token: the caller wraps the\n * service call in {@link runInCall}, then reports the outcome through\n * `settle` when the answer arrives, which is when the source first exists.\n * @returns the ring for the call about to be made.\n */\n openCall(): CallRing {\n const identity = this.currentCallIdentity();\n const { token, ledger } = this.#attributed.open(identity);\n return {\n ledger,\n settle: (outcome) => this.#settleCall(token, identity, outcome)\n };\n }\n\n /**\n * Run one call inside its own ledger ring.\n * @param ring - the ring from {@link openCall}.\n * @param run - the work to run with that ring in force.\n * @returns whatever `run` returns.\n */\n runInCall<T>(ring: CallRing, run: () => Promise<T>): Promise<T> {\n return this.#callScope.run({ sink: ring.ledger }, run);\n }\n /** Whether this runtime owns the backend and may rebuild it on a config save. */\n readonly #backendSwappable: boolean;\n /** Identity of the backend configuration currently in force. */\n #backendSignature: string;\n /** System One connection settings currently in force (panel/diagnostics). */\n #systemOneConfig: ResolvedSystemOneConfig;\n /** Backend selector currently in force (panel/diagnostics). */\n #backendSelector: ResolvedReflexConfig['backend'];\n /** Ledger sink currently in force. */\n #ledgerPath?: string;\n /** Routing policy currently in force (provider lifecycle is reconciled live). */\n #routingConfig: ResolvedRoutingConfig;\n /** Applies routing lifecycle changes (enable/disable, provider rename) live. */\n #reconfigureRouting?: (routing: ResolvedRoutingConfig) => void;\n /** Reads how many provider registrations this activation made in total. */\n #routingRegistrationEvents?: () => number;\n /** Backend rebuilds performed by this activation (diagnostics/measurement). */\n #backendRebuilds = 0;\n /** Ledger sink switches performed by this activation. */\n #ledgerSwitches = 0;\n\n /**\n * @param config - resolved plugin configuration.\n * @param dependencies - test seams for the ledger, backend, and routing clock,\n * plus the raw config (whose volatile references carry live updates) and a\n * diagnostic sink.\n */\n constructor(\n config: ResolvedReflexConfig,\n dependencies: {\n backend?: DecisionBackend;\n ledger?: DecisionLedger;\n now?: () => number;\n configSource?: unknown;\n warn?: (message: string) => void;\n } = {}\n ) {\n this.config = config;\n // One stable delegate: the services below close over it, and a config save\n // swaps the transport inside it instead of rebuilding them.\n this.#liveBackend = new LiveBackend(dependencies.backend ?? createBackend(config));\n this.#backendSwappable = dependencies.backend === undefined;\n this.#backendSignature = backendSignature(config);\n this.backend = this.#liveBackend as unknown as DecisionBackend;\n this.ledger = dependencies.ledger ?? new DecisionLedger(config.ledgerPath ?? null);\n this.#systemOneConfig = config.systemOne;\n this.#backendSelector = config.backend;\n this.#ledgerPath = config.ledgerPath;\n this.#routingConfig = config.routing;\n this.calibrator = config.calibrationPath ? new Calibrator(config.calibrationPath) : new Calibrator();\n // Services that write their own ledger entry go through the attributed\n // ledger, so the entry they own carries the same provenance the payload\n // reports — with a source that is only written once it is knowable.\n this.#attributed = new AttributedLedger(this.ledger);\n // The services are typed against the whole ledger but only ever call\n // `record`; the cast keeps that one-method contract honest while the\n // attributed sink does the bookkeeping behind it.\n const sinkOf = (sink: LedgerSink): DecisionLedger => sink as unknown as DecisionLedger;\n this.gateService = new ReflexGateService(this.backend, sinkOf(this.tracking.gate), this.calibrator);\n this.pruneService = new ToolResultPruner(this.backend, sinkOf(this.tracking.prune), config.pruneThreshold);\n this.stagnationService = new StagnationDetector(this.backend, sinkOf(this.tracking.stagnation));\n this.routeService = new ReflexRouter(this.backend, sinkOf(this.tracking.route));\n this.screenService = new ReflexScreenService(this.backend, sinkOf(this.tracking.screen));\n this.#source = dependencies.configSource;\n this.#warn = dependencies.warn ?? (() => {});\n this.#interventionsConfig = config.interventions;\n this.#pruneThreshold = config.pruneThreshold;\n this.#toolsConfig = config.tools;\n this.#toolPrefix = config.toolPrefix;\n this.#delegationConfig = config.delegation;\n const initialMark = dependencies.configSource === undefined ? [] : volatileSnapshots(dependencies.configSource);\n this.#mark = initialMark;\n this.#watchable = initialMark.length > 0;\n this.#modelRouter = new VirtualModelRouter({\n virtualProvider: config.routing.virtualProvider,\n models: config.routing.models,\n backendName: this.backend.name,\n ledger: this.ledger,\n route: (goal, candidates, topK, input) =>\n this.routeService.selectBest(goal, candidates, topK, { record: false, ...(input ?? {}) }),\n ...(config.routing.fallback ? { fallback: config.routing.fallback } : {}),\n ...(dependencies.now ? { now: dependencies.now } : {}),\n // The loader commits a config-only update without remounting the plugin;\n // this is how every routing decision and panel read sees the new policy.\n refresh: () => { this.refreshIfChanged(); }\n });\n this.effortStatusFeed = new EffortStatusFeed();\n this.effort = new EffortInterceptor({\n ...(config.effort.setting === undefined ? {} : { setting: config.effort.setting }),\n enabled: config.effort.enabled,\n fallback: config.effort.fallback,\n minConfidence: config.effort.minConfidence,\n decide: (request) => this.backend.choice(request),\n backendName: this.backend.name,\n ledger: this.ledger,\n feed: this.effortStatusFeed,\n ...(dependencies.now ? { now: dependencies.now } : {})\n });\n }\n\n /** Name of the active decision backend, for diagnostics and tests. */\n get backendName(): string {\n return this.backend.name;\n }\n\n /** The routing policy this activation routes through (live). */\n get modelRouter(): VirtualModelRouter {\n return this.#modelRouter;\n }\n\n /**\n * Route through the process-wide router another activation registered.\n *\n * A reload can leave one provider registration shared by two activations. The\n * shared router is where the live pools and fallback live, so this runtime must\n * read (and refresh) that one — a private copy would show the panel, and route\n * requests, on a policy nobody applies.\n * @param router - the shared router the virtual provider dispatches through.\n */\n adoptModelRouter(router: VirtualModelRouter): void {\n this.#modelRouter = router;\n }\n\n /**\n * Health of the backend's gateway conversation, or `undefined` for a backend\n * that answers every call in-process.\n *\n * Read by the settings panel and `/reflex-ledger`; never passed to a model.\n * @returns a copy of the counters.\n */\n systemOneHealth(): BackendHealth | undefined {\n return this.#liveBackend.currentHealth();\n }\n\n /**\n * The connection identity a call dispatched *now* would carry.\n *\n * Public so the panel and a test can ask the same question the dispatch path\n * asks, without going through a call. It reads the live resolved connection\n * block, never the activation-time snapshot, so a config-only commit is\n * reflected immediately (and a profile switch cannot lag one call behind).\n * @returns the identity to snapshot into the next call.\n */\n currentCallIdentity(): CallIdentity {\n return callIdentity(this.#systemOneConfig, this.#backendSelector);\n }\n\n /**\n * Take the identity, run one call, and classify where its answer came from —\n * the single place provenance is decided.\n *\n * The identity is snapshotted **before** `run()` is called, so the call keeps\n * the connection it was dispatched under even if the backend is swapped while\n * it is in flight. A thrown call is captured rather than rethrown here: some\n * services answer locally after a remote failure (prune, stagnation), others\n * refuse (choice, score, route, screen), and the caller decides.\n *\n * ## Per-call rings, not one shared stamp\n *\n * Every call runs inside its own {@link CallRing}, so a service that writes\n * its own entry buffers it on *this* call and never on a neighbour's. Two\n * overlapping calls therefore cannot borrow, erase or overwrite each other's\n * attribution, which one shared \"current stamp\" field made trivially possible.\n *\n * ## Absorbed failures, and the honest `unknown`\n *\n * Not every remote failure arrives as a rejection. `ReflexGateService` turns a\n * gateway failure into a fail-closed `escalate` verdict and *returns* it, so\n * `run()` resolves normally. Where the backend publishes a failure record\n * (JEV), a failure count that rose across the call proves the request was\n * rejected and absorbed. Where it publishes none (the vLLM logits backend) no\n * evidence proves anything, and the call reports `unknown` rather than\n * claiming `remote` — see {@link classifyEvidence}.\n * @param run - the call to make.\n * @param options - how to read the outcome (`answered`, `localFallback`).\n * @returns the value, or the failure with the classified outcome.\n */\n async #dispatch<T>(\n run: () => Promise<T>,\n options: { answered(value: T): boolean; localFallback?: (value: T) => boolean }\n ): Promise<{ result?: T; outcome: DispatchOutcome; failure?: string }> {\n this.#assertLive();\n const identity = this.currentCallIdentity();\n // A connection with no active profile, and the in-process mock, send\n // nothing. Naming them apart is the whole point, so it is read from the\n // identity rather than inferred from an empty health record.\n const localOnly =\n identity.connectionName === UNCONFIGURED_CONNECTION_NAME || identity.connectionName === MOCK_CONNECTION_NAME;\n const before = this.#liveBackend.currentHealth();\n const ring = this.#attributed.open(identity);\n let result: T | undefined;\n let failure: string | undefined;\n try {\n result = await this.#callScope.run({ sink: ring.ledger }, run);\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n const after = this.#liveBackend.currentHealth();\n const evidence: SourceEvidence = {\n answered: failure === undefined && result !== undefined && options.answered(result as T),\n ...(failure === undefined ? {} : { failure }),\n localFallback: failure === undefined && options.localFallback?.(result as T) === true,\n localOnly,\n healthReadable: after !== undefined,\n ...(before === undefined ? {} : { failuresBefore: before.consecutiveFailures }),\n ...(after === undefined ? {} : { failuresAfter: after.consecutiveFailures }),\n ...(after?.lastFailureReason === undefined ? {} : { lastFailureReason: after.lastFailureReason })\n };\n const classified = classifyEvidence(evidence);\n // Appended exactly once, already final: identity *and* source together. No\n // line is ever rewritten, so the JSONL sink stays append-only.\n this.#attributed.finish(ring.token, { identity, ...classified });\n this.#attributed.flush();\n // A service that wrote only after this call settled left its entry in the\n // shared group, so nothing proves that entry is this call's. The ledger line\n // says `unknown`; the payload must agree with it rather than disagree.\n const outcome: DispatchOutcome = this.#attributed.takeLateCall()\n ? { identity, ...classifyEvidence({ ...evidence, entryArrivedLate: true }) }\n : { identity, ...classified };\n return { ...(result === undefined ? {} : { result }), outcome, ...(failure === undefined ? {} : { failure }) };\n }\n\n /**\n * Run one outbound decision inside a full attributed call.\n *\n * The seam the automatic-intervention engine uses: it opens a ring, runs the\n * service inside it, classifies the outcome from the same evidence the tools\n * use, settles the ring (append-only, once) and hands back both the value and\n * the attribution so the caller can put it on its own payload.\n * @param run - the decision to make.\n * @param options - how to read the outcome.\n * @returns the value and its attribution.\n */\n async attribute<T>(\n run: () => Promise<T>,\n options: { answered(value: T): boolean; localFallback?: (value: T) => boolean }\n ): Promise<{ result: T; attribution: Attribution }> {\n const { result, outcome, failure } = await this.#dispatch(run, options);\n if (failure !== undefined || result === undefined) {\n throw new Error(failure ?? 'the System One connection produced no answer');\n }\n return { result, attribution: attributionOf(outcome.identity, outcome) };\n }\n\n /**\n * Close one `openCall` ring: append its entries with the final source.\n *\n * The automatic-intervention layer calls this once its service answered, so\n * a decision made at a Host hook point is attributed exactly like one made\n * through a tool.\n * @param token - the ring's token.\n * @param identity - the identity the ring was opened with.\n * @param outcome - the settled source.\n * @returns the attribution for the caller's payload.\n */\n #settleCall(token: number, identity: CallIdentity, outcome: { source: CallSource; detail?: string }): Attribution {\n this.#attributed.finish(token, { identity, ...outcome });\n this.#attributed.flush();\n return attributionOf(identity, outcome);\n }\n\n /**\n * Append the attribution to one ledger entry's `details`.\n *\n * The four provenance facts ride in `details` rather than as new top-level\n * `LedgerEntry` fields, because `DecisionLedger` is shared with the root stdio\n * MCP package: adding keys there would be a contract change to a surface g-068\n * must leave alone. `details` is already the entry's open bag, and a JSONL\n * reader greps it all the same.\n * @param outcome - the dispatch outcome.\n * @returns the flat provenance fields to merge into `details`.\n */\n #provenance(outcome: DispatchOutcome): Record<string, unknown> {\n return { ...ledgerAttribution(attributionOf(outcome.identity, outcome)) };\n }\n\n /**\n * Multi-class choice, with the deployment's calibration curve applied to the\n * winning confidence when one is loaded.\n * @param request - question, options, and optional context.\n * @returns the choice response plus the calibrated confidence and the\n * attribution (connection, requested model, source), when available.\n * @throws Error when the connection produced no answer: a choice tool must not\n * invent a distribution, and the ledger still records the rejected attempt.\n */\n async choice(request: { question: string; options: string[]; context?: string }): Promise<ReflexChoiceResult> {\n const started = performance.now();\n const { result, outcome, failure } = await this.#dispatch(() => this.backend.choice(request), {\n answered: (value) => value !== undefined\n });\n const record = (): void => {\n this.ledger.record({\n type: 'choice',\n backend: this.backend.name,\n latencyMs: Math.round(performance.now() - started),\n details: { action: 'choice', options: request.options.length, ...this.#provenance(outcome) }\n });\n };\n\n if (result === undefined) {\n record();\n throw new Error(failure ?? 'the System One connection produced no answer');\n }\n\n let calibratedConfidence: number | undefined;\n if (this.calibrator.isLoaded()) {\n calibratedConfidence = this.calibrator.calibrate(result.confidence).calibrated;\n }\n record();\n return { ...result, calibratedConfidence, ...attributionOf(outcome.identity, outcome) };\n }\n\n /**\n * Continuous 0.0 – 1.0 scoring projected from one choice call.\n * @param request - statement, rubric, and optional context.\n * @returns the score response, recorded in the ledger with its attribution.\n */\n async score(request: {\n statement: string;\n criteria?: string;\n context?: string;\n }): Promise<Awaited<ReturnType<typeof scoreStatement>> & Attribution> {\n const started = performance.now();\n const { result, outcome, failure } = await this.#dispatch(() => scoreStatement(this.backend, request), {\n answered: (value) => value !== undefined\n });\n this.ledger.record({\n type: 'choice',\n backend: this.backend.name,\n latencyMs: result?.latencyMs ?? Math.round(performance.now() - started),\n details: { action: 'score', ...(result === undefined ? {} : { score: result.score }), ...this.#provenance(outcome) }\n });\n if (result === undefined) throw new Error(failure ?? 'the System One connection produced no answer');\n return { ...result, ...attributionOf(outcome.identity, outcome) };\n }\n\n /**\n * Rank candidate skills/tools against a goal.\n * @param request - goal, candidates, and how many to return.\n * @returns the ranked candidates with their attribution.\n */\n async route(request: { goal: string; candidates: CandidateItem[]; topK?: number }): Promise<RouteResponse & Attribution> {\n const { result, outcome, failure } = await this.#dispatch(\n () => this.routeService.selectBest(request.goal, request.candidates, request.topK ?? 3),\n { answered: (value) => value !== undefined }\n );\n if (result === undefined) throw new Error(failure ?? 'the System One connection produced no answer');\n return { ...result, ...attributionOf(outcome.identity, outcome) };\n }\n\n /**\n * Screen untrusted content for prompt injection and instruction hijacking.\n * @param request - content, its source, and whether to force deep screening.\n * @returns the screening verdict and a sanitized fence when unsafe.\n */\n async screen(request: {\n content: string;\n source?: 'tool_output' | 'web_page' | 'user_input' | 'file_content';\n strict?: boolean;\n }): Promise<ScreenResult & Attribution> {\n const { result, outcome, failure } = await this.#dispatch(() => this.screenService.screen(request), {\n answered: (value) => value !== undefined\n });\n if (result === undefined) throw new Error(failure ?? 'the System One connection produced no answer');\n return { ...result, ...attributionOf(outcome.identity, outcome) };\n }\n\n /**\n * Fail-closed verification of assertions against evidence.\n *\n * A remote rejection is *not* rethrown: the gate's contract is a verdict, and\n * every assertion escalates. What changes is the honesty of that verdict —\n * the attribution says `rejected` and carries the reason, so a local\n * fail-closed escalation can no longer be read as a System One judgement.\n * @param request - assertions, evidence, and optional strictness.\n * @returns one outcome per assertion plus the overall verdict and attribution.\n */\n async gate(request: {\n assertions: Array<{ statement: string; criteria?: string }>;\n evidence: string;\n strictness?: 'high' | 'normal' | 'lenient';\n }): Promise<GateResponse & Attribution> {\n const { result, outcome, failure } = await this.#dispatch(\n () => this.gateService.verify(request.assertions, request.evidence, { strictness: request.strictness }),\n { answered: (value) => value !== undefined }\n );\n if (result === undefined) throw new Error(failure ?? 'the System One connection produced no answer');\n // The service absorbs a gateway rejection into a fail-closed verdict, so a\n // thrown call is impossible there; the *reason* it absorbed must still reach\n // the reader. The service's own explanation already carries it, and this\n // layer adds the source so the verdict is not read as a remote judgement.\n return { ...result, ...attributionOf(outcome.identity, outcome) };\n }\n\n\n /**\n * Prune bulky output, preserving the lines the intent depends on.\n *\n * Programmatic seam for the pruning capability: the automatic intervention\n * layer drives {@link pruneService} directly, and this entry point stays for\n * in-process callers (tests, diagnostics, an embedding Host).\n * @param request - raw output, lookup intent, and shadow-mode flag.\n * @returns the compacted payload and the measured token savings.\n */\n async prune(request: { rawOutput: string; intent?: string; shadowMode?: boolean }): Promise<ReflexPruneResult & Attribution> {\n const { result, outcome, failure } = await this.#dispatch(\n () =>\n this.pruneService.prune(request.rawOutput, {\n intent: request.intent,\n shadowMode: request.shadowMode\n }),\n {\n answered: (value) => value !== undefined,\n // Prune is the one capability that answers locally on purpose. `judgePath`\n // is its own account of which path produced the text: `local` sent no\n // request at all (the payload is below the judge threshold), and\n // `fallback` means the segmented request was tried and failed. Either is\n // a local answer and must never be rendered as a System One judgement.\n localFallback: (value) => {\n const path = (value as PruneResponse).judgePath;\n return path === 'fallback' || path === 'local';\n }\n }\n );\n\n if (result === undefined) throw new Error(failure ?? 'the System One connection produced no answer');\n // A gateway failure that prune absorbed as a local fallback is still a\n // rejection: `judgePath: 'fallback'` and the health record agree, and the\n // reason the fallback happened is the more useful of the two to report.\n const reason = (result as PruneResponse).fallbackReason ?? outcome.detail;\n return {\n tokensSaved: result.estimatedTokensSaved,\n reductionPercentage: `${result.reductionPercentage}%`,\n shadow: result.shadow,\n processedOutput: result.processedOutput,\n ...attributionOf(outcome.identity, { ...outcome, ...(reason === undefined ? {} : { detail: reason }) })\n };\n }\n\n /**\n * Record one action and check whether the run is stagnating.\n *\n * `history` exists for callers that bring their own run: a resumed session, a\n * delegated agent, or a caller that did not record its steps through this\n * tool. Supplied steps are treated as earlier than the ones recorded here, so\n * a caller can hand over a whole run and still add the action it just took.\n *\n * Programmatic seam for the stagnation capability: the automatic intervention\n * layer drives {@link stagnationService} directly, and this entry point stays\n * for in-process callers.\n *\n * @param request - the action just taken, the overall goal, and any prior steps.\n * @returns the stagnation verdict and corrective suggestion.\n */\n async detectStagnation(request: {\n goal?: string;\n recentAction?: ActionStep;\n history?: readonly ActionStep[];\n }): Promise<StagnationCheckResponse> {\n this.#assertLive();\n if (request.recentAction) this.stagnationService.recordAction(request.recentAction);\n // Dispatched like every other decision: the service writes its own entry,\n // and the ring's append-only settlement is what attributes it.\n const { result, outcome, failure } = await this.#dispatch(\n () => this.stagnationService.check(request.goal, request.history),\n { answered: (value) => value !== undefined }\n );\n if (result === undefined) throw new Error(failure ?? 'the System One connection produced no answer');\n return result;\n }\n\n /**\n * Read the decision ledger.\n *\n * Programmatic seam behind `/reflex-ledger`: the Host command formats this\n * same read for a person, and an embedding Host can call it directly. Nothing\n * in the tool surface depends on it.\n * @param request - whether to attach the ten most recent entries.\n * @returns the aggregate summary and, on request, recent entries.\n */\n statusLedger(request: { includeEntries?: boolean } = {}): ReflexLedgerResult {\n this.#assertLive();\n const summary = this.ledger.getSummary();\n const health = this.systemOneHealth();\n const base: ReflexLedgerResult = health === undefined ? { summary } : { summary, systemOneHealth: health };\n if (!request.includeEntries) return base;\n return { ...base, recentEntries: this.ledger.getEntries().slice(-10) };\n }\n\n /**\n * Publish the reflex tool names this activation currently owns, so a Host\n * observer can mirror the live surface.\n * @param names - the registered tool names.\n */\n noteToolSurface(names: readonly string[]): void {\n this.#surface = [...names];\n }\n\n /** The reflex tool names of this activation. */\n get toolSurface(): readonly string[] {\n return this.#surface;\n }\n\n /**\n * The latest adaptive effort decision this activation published.\n * @param agentId - agent to read; omitted reads the most recent of any agent.\n * @returns the status, or `undefined` before the first decided turn.\n */\n effortStatus(agentId?: string): ReflexEffortStatus | undefined {\n return this.effortStatusFeed.latest(agentId);\n }\n\n /**\n * The status-bar line of the latest adaptive effort decision.\n * @param agentId - agent to read; omitted reads the most recent of any agent.\n * @returns the rendered line, or `undefined` before the first decided turn.\n */\n effortStatusLine(agentId?: string): string | undefined {\n return this.effortStatusFeed.statusLine(agentId);\n }\n\n /**\n * Attach the automatic-intervention engine of this activation.\n *\n * Set by the plugin lifecycle right after the listeners are installed, so the\n * panel and the tests read the same engine the hooks drive. Absent when every\n * capability is `off`: nothing is installed, and nothing is reported.\n *\n * The optional reconfiguration seam is what makes a config-only save live: the\n * installer owns the listeners (which hooks exist depends on the capability\n * modes), so swapping thresholds or turning a capability on/off has to go\n * through it rather than through the engine alone.\n * @param engine - the engine behind this activation's listeners.\n * @param reconfigure - applies a new resolved policy to the listeners.\n * @param listenerCount - reads how many listeners are currently attached.\n */\n attachInterventions(\n engine: InterventionEngine | undefined,\n reconfigure?: (config: ResolvedInterventionsConfig, pruneThreshold: number) => void,\n listenerCount?: () => number\n ): void {\n this.#interventions = engine;\n this.#reconfigureInterventions = reconfigure;\n this.#interventionListenerCount = listenerCount;\n }\n\n /**\n * How many intervention listeners this activation currently has attached.\n *\n * `0` is the honest answer of an `off` deployment: the capability is absent,\n * not a listener that checks a flag on every hook.\n */\n get interventionListenerCount(): number {\n return this.#interventionListenerCount?.() ?? 0;\n }\n\n /** The automatic-intervention engine, when this activation installed one. */\n get interventions(): InterventionEngine | undefined {\n return this.#interventions;\n }\n\n /**\n * Attach the tool-surface reconciler of this activation.\n *\n * Set by the plugin lifecycle right after the tools are registered. The\n * registry lives on the Host context, not on this runtime, so a config-only\n * save has to call back out to the installer that owns the registrations. The\n * seam is also what lets the tests prove idempotence: an unchanged save must\n * not unregister and re-register anything.\n * @param reconfigure - reconciles the registered set with a new resolved config.\n * @param registrationCount - reads how many tools are currently registered.\n * @param registrationEvents - reads how many registrations happened in total.\n */\n attachToolSurface(\n reconfigure?: (config: ResolvedReflexConfig) => void,\n registrationCount?: () => number,\n registrationEvents?: () => number\n ): void {\n this.#reconfigureTools = reconfigure;\n this.#toolRegistrationCount = registrationCount;\n this.#toolRegistrationEvents = registrationEvents;\n }\n\n /**\n * Attach the routing-lifecycle reconciler of this activation.\n *\n * The provider registration lives on the LLM runtime, not on this runtime, so\n * enabling/disabling the route or renaming the virtual provider on a\n * config-only save has to call back out to the installer that owns it.\n * @param reconfigure - applies the routing lifecycle of a freshly resolved config.\n * @param registrationEvents - reads how many provider registrations happened.\n */\n attachRouting(\n reconfigure?: (routing: ResolvedRoutingConfig) => void,\n registrationEvents?: () => number\n ): void {\n this.#reconfigureRouting = reconfigure;\n this.#routingRegistrationEvents = registrationEvents;\n }\n\n /**\n * Attach the live delegation-capability read of this activation.\n *\n * Set by the plugin lifecycle right after the tool surface, so the panel can\n * explain what the Host actually publishes instead of silently omitting it.\n * The runtime does not own the registry: it only reports what the Host says.\n * @param read - returns the current reading.\n * @param refresh - re-checks the registry and reconciles the tool surface.\n */\n attachDelegationHealth(read?: () => DelegationHealth, refresh?: () => void): void {\n this.#delegationHealth = read;\n this.#refreshDelegation = refresh;\n }\n\n /**\n * Attach the hook that records the agent scope the capability is read in.\n *\n * `dsh-tools` is scoped, and a preset-hosted delegation tool is invisible from\n * the global view. The lifecycle owns the reading, so it also owns the scope:\n * this only lets a caller that *does* have an `Agent` (the panel poll, a\n * session-aware caller) tell it which scope to read as. Never decides\n * registration — that is configuration's job.\n * @param note - receives the scope to read the delegation capability in.\n */\n attachDelegationScope(note?: (agent: Agent) => void): void {\n this.#noteDelegationScope = note;\n }\n\n /**\n * Record the scope future delegation reads should use.\n * @param agent - the calling agent, or a preset to read as.\n */\n noteDelegationScope(agent: Agent): void {\n this.#noteDelegationScope?.(agent);\n }\n\n /** Re-check the Host delegation capability in the recorded scope. */\n checkDelegationHealth(): DelegationHealth | undefined {\n this.#refreshDelegation?.();\n return this.#delegationHealth?.();\n }\n\n /** The current delegation-capability reading, when the lifecycle attached one. */\n get delegationHealth(): DelegationHealth | undefined {\n return this.#delegationHealth?.();\n }\n\n /**\n * Attach the delegated-agent effort inheritance of this activation.\n * @param inheritance - the installed listener, or undefined to detach.\n */\n attachEffortInheritance(inheritance: DelegatedEffortInheritance | undefined): void {\n this.#effortInheritance = inheritance;\n }\n\n /**\n * How many delegated selections this activation rewrote to a concrete level.\n *\n * Monotonic: it counts the marker replacements, not the steps that used them.\n */\n get effortInheritanceRewrites(): number {\n return this.#effortInheritance?.rewrites ?? 0;\n }\n\n /** Provider registrations this activation made (monotonic; diagnostics). */\n get routingRegistrationEvents(): number {\n return this.#routingRegistrationEvents?.() ?? 0;\n }\n\n /** Backend rebuilds this activation performed (0 when a seam supplied one). */\n get backendRebuilds(): number {\n return this.#backendRebuilds;\n }\n\n /** Ledger sink switches this activation performed. */\n get ledgerSwitches(): number {\n return this.#ledgerSwitches;\n }\n\n /** The number of reflex tools this activation currently has registered. */\n get toolRegistrationCount(): number {\n return this.#toolRegistrationCount?.() ?? 0;\n }\n\n /**\n * How many `tools.register` calls this activation has made since it loaded.\n *\n * Monotonic on purpose: an idempotent save leaves it unchanged, which is the\n * measurement a test can assert without spying on the registry.\n */\n get toolRegistrationEvents(): number {\n return this.#toolRegistrationEvents?.() ?? 0;\n }\n\n /**\n * The configuration the panel and diagnostics must report: the values\n * currently in force for every block this slice has made live.\n *\n * The panel promise is \"show what is in force\", not \"show what was written at\n * startup\". `effort`, `interventions`, `pruneThreshold`, `tools` and\n * `toolPrefix` are read from their live fields; blocks whose live path is a\n * separate slice (backend, ledger sink, route lifecycle) keep reporting their\n * activation values until that slice lands.\n */\n get effectiveConfig(): ResolvedReflexConfig {\n const models = this.modelRouter.models;\n const fallback = this.modelRouter.fallback;\n return {\n ...this.config,\n backend: this.#backendSelector,\n ledgerPath: this.#ledgerPath,\n toolPrefix: this.#toolPrefix,\n tools: this.#toolsConfig,\n systemOne: this.#systemOneConfig,\n routing: {\n enabled: this.#routingConfig.enabled,\n maxTaskChars: this.#routingConfig.maxTaskChars,\n // The router is the live source of the provider name and the pools: a\n // rename is applied there first, and every surface must agree with it.\n virtualProvider: this.modelRouter.virtualProvider,\n models,\n ...(fallback === undefined ? {} : { fallback })\n },\n effort: { ...this.effort.policy },\n // The delegation consent is a deployment switch, written by the panel and\n // re-resolved on every commit; a cached activation value would keep showing\n // \"off\" after the user ticked it.\n delegation: this.#delegationConfig,\n interventions: this.#interventionsConfig,\n pruneThreshold: this.#pruneThreshold\n };\n }\n\n /**\n * Full schema resolutions this activation performed.\n *\n * Incremented only by {@link refresh}; the request/step/tool hot paths never\n * resolve the schema, which is the measurement this counter makes provable.\n */\n get configResolveCount(): number {\n return this.#configResolves;\n }\n\n /** Whether the owning plugin activation has been disposed. */\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /**\n * Re-read this activation's live policy from its config.\n *\n * Called when the Host reports a config commit (`loader/volatile-update`) and\n * lazily once per `agent/pre-step`. The schema runs here — once per actual\n * commit — and nowhere on the request/tool hot paths.\n *\n * Applied without a remount:\n * - routing pools and fallback (replaced in the router);\n * - the whole adaptive-effort policy (switch, marker, fallback, confidence\n * floor), read live by the request interception and the selector surface;\n * - the intervention thresholds and capability modes, with the listeners\n * added or removed according to the effective modes;\n * - the per-tool switches and the deployment prefix, with the registry\n * reconciled by the installer through {@link attachToolSurface}. The\n * reconciler is idempotent: a commit that changes neither the enabled\n * suffixes nor the prefix unregisters and re-registers nothing;\n * - the decision backend and its connection settings, rebuilt only on a\n * transport-relevant change (health starts fresh on the new backend);\n * - the ledger sink, migrated in place so no recorded entry is lost;\n * - the routing lifecycle (enabled switch, virtual-provider rename) through\n * {@link attachRouting}, and the task budget read per step.\n * @returns whether a new policy was applied.\n */\n refresh(): boolean {\n if (this.#source === undefined || this.#disposed || this.#refreshing) return false;\n this.#refreshing = true;\n try {\n let resolved: ResolvedReflexConfig;\n try {\n resolved = resolveConfig(this.#source as ReflexConfig);\n } catch (error) {\n this.#warn(\n `dsh-reflex: the updated configuration cannot be applied (${(error as Error).message}); keeping the previous live values`\n );\n return false;\n }\n this.#configResolves += 1;\n\n // Backend and connection: rebuild only when something that shapes the\n // transport changed. A same-value commit touches nothing (idempotence), and\n // the services keep dispatching through the same delegate.\n const nextSignature = backendSignature(resolved);\n if (this.#backendSwappable && nextSignature !== this.#backendSignature) {\n this.#liveBackend.swap(createBackend(resolved));\n this.#backendSignature = nextSignature;\n this.#backendRebuilds += 1;\n }\n this.#systemOneConfig = resolved.systemOne;\n this.#backendSelector = resolved.backend;\n\n // Ledger sink: move the JSONL target in place, migrating the in-memory\n // history into the new file so entries recorded before the switch survive.\n if (resolved.ledgerPath !== this.#ledgerPath) {\n const switched = (this.ledger as { switchLogPath?: (path?: string | null) => boolean }).switchLogPath?.(\n resolved.ledgerPath ?? null\n );\n this.#ledgerPath = resolved.ledgerPath;\n if (switched) this.#ledgerSwitches += 1;\n }\n\n // The prune threshold is read live by the direct prune seam as well as by\n // the intervention engine's projection.\n this.pruneService.setMinCharsThreshold(resolved.pruneThreshold);\n\n this.#modelRouter.updatePolicy({\n models: resolved.routing.models,\n ...(resolved.routing.fallback ? { fallback: resolved.routing.fallback } : {})\n });\n this.#routingConfig = resolved.routing;\n this.effort.updatePolicy({\n enabled: resolved.effort.enabled,\n ...(resolved.effort.setting === undefined ? {} : { setting: resolved.effort.setting }),\n fallback: resolved.effort.fallback,\n minConfidence: resolved.effort.minConfidence\n });\n this.#interventionsConfig = resolved.interventions;\n this.#pruneThreshold = resolved.pruneThreshold;\n // The tool block is applied before the intervention reconfigure so the\n // callback can derive the renamed `ownTools` set from this runtime's live\n // values rather than from the activation-time snapshot.\n this.#toolsConfig = resolved.tools;\n this.#toolPrefix = resolved.toolPrefix;\n this.#delegationConfig = resolved.delegation;\n this.#reconfigureInterventions?.(resolved.interventions, resolved.pruneThreshold);\n this.#reconfigureTools?.(resolved);\n // Routing lifecycle last: enabling/disabling the route and renaming the\n // provider may recreate the shared router, and the panel/tool surfaces read\n // the routing block after the pools have been replaced.\n this.#reconfigureRouting?.(resolved.routing);\n this.#mark = volatileSnapshots(this.#source);\n return true;\n } finally {\n this.#refreshing = false;\n }\n }\n\n /**\n * Refresh only when the loader actually committed a new config value.\n *\n * The volatile references hand out a new snapshot object on every commit, so\n * an identity comparison over them is O(config blocks) and never runs the\n * schema again for an unchanged config.\n * @returns whether a new policy was applied.\n */\n refreshIfChanged(): boolean {\n if (!this.#watchable || this.#source === undefined || this.#disposed || this.#refreshing) return false;\n const next = volatileSnapshots(this.#source);\n const previous = this.#mark;\n const unchanged =\n next.length === previous.length && next.every((snapshot, index) => snapshot === previous[index]);\n if (unchanged) return false;\n return this.refresh();\n }\n\n /** Release the runtime. Called from the plugin's `ctx.effect` cleanup. */\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n // No residue on unload: the per-agent detection state, the reduction memo,\n // and the accounts of the intervention engine are dropped with the runtime,\n // exactly like the effort feed and the ledger.\n this.#interventions?.reset();\n this.#interventions = undefined;\n this.#reconfigureRouting = undefined;\n this.effortStatusFeed.clear();\n this.ledger.clear();\n }\n\n #assertLive(): void {\n if (this.#disposed) throw new Error('reflex runtime has been disposed');\n }\n}\n\n/**\n * Identity of the configuration that shapes the decision transport.\n *\n * A config-only save re-resolves the whole document; rebuilding the backend for\n * a change that cannot affect it would reset health and drop the connection for\n * no reason. This signature lets {@link ReflexRuntime.refresh} rebuild exactly\n * when the transport's identity changed.\n * @param config - resolved plugin configuration.\n * @returns a stable string of the transport-relevant fields.\n */\nfunction backendSignature(config: ResolvedReflexConfig): string {\n const { backend, systemOne, interventions } = config;\n return JSON.stringify([\n backend,\n // g-066: the resolved connection fields, which are the *active profile's*\n // (plus the \"unconfigured\" reason, so activating or losing a profile\n // rebuilds). They are listed here rather than left to the per-profile rows\n // below because a resolved field is the one the transport is built from.\n systemOne.unconfigured ?? '',\n systemOne.baseUrl ?? '',\n systemOne.model ?? '',\n systemOne.apiKeyEnv ?? '',\n systemOne.timeoutMs ?? null,\n // g-057: switching the active profile (or editing any profile's connection\n // facts) must rebuild the backend, otherwise the panel would report a new\n // profile as active while the running transport still served the old one.\n // The *keys* are represented by presence only: a signature is a diagnostic\n // value, and a rotated key must not change what an edited profile is\n // observed to be — but a profile that gained or lost a key must.\n systemOne.active ?? '',\n Object.entries(systemOne.profiles ?? {}).map(([name, profile]) => [\n name,\n profile.baseUrl ?? '',\n // The model *list* and the selection, not the resolved model: a save that\n // only changes which listed model is selected must rebuild the transport,\n // and so must one that adds a model the selection could point at.\n (profile.modelIds ?? []).join('\\u0000'),\n profile.selectedModel ?? '',\n profile.apiKeyEnv ?? '',\n profile.timeoutMs ?? null,\n profile.backend ?? '',\n profile.apiKey === undefined ? '' : 'set'\n ]),\n interventions.pruneJudgeMinChars\n ]);\n}\n\n/**\n * Build the backend a plugin activation should use.\n *\n * ## Nothing connects without an active profile (g-066)\n *\n * The connection fields come from the active profile only, so when\n * {@link ResolvedSystemOneConfig.unconfigured} is set there is nothing to build\n * and this function **refuses**. Building a backend anyway is exactly the old\n * fallback: with no profile resolved, the vendored factory would choose `jev`\n * because `JEV_API_KEY` happens to be exported, and the plugin would make a\n * request nobody configured. Returning the mock backend instead was the other\n * candidate and was rejected as well: \"unconfigured\" must not look like \"answered\n * locally with heuristics\" in the ledger or the panel.\n *\n * The replacement is {@link UnconfiguredBackend}: the same deterministic local\n * heuristics, under a name that says what is wrong, plus a health record that\n * reports the missing connection instead of staying silent. `backend` may still\n * be `mock` **explicitly**, which is a deployment choosing the in-process\n * implementation on purpose — the two must remain distinguishable.\n *\n * The connection block of the resolved config overrides the environment for\n * this plugin instance only: the backend implementations already fall back to\n * the environment for every omitted option, so an explicitly configured\n * deployment and an env-configured one behave the same when the block is empty.\n *\n * The key is the exception worth naming: it is resolved **here**, through\n * {@link resolveApiKeyWithSource}, and handed to the backend explicitly. The\n * backends keep their own environment reads for the fields they own (base URL,\n * model), but a key that only arrived through their fallback would be invisible\n * to {@link resolveApiKeyWithSource} — and therefore to the panel, which is how\n * \"the panel says the env var is empty while the backend works\" was possible.\n * One chain, one answer for both.\n *\n * Every construction here also passes `apiKeyResolved: true` (g-059). That flag\n * makes \"the chain resolved no key\" *final*: without it both backends would\n * re-read `SYSTEM_ONE_API_KEY` / `JEV_API_KEY` (and the logits backend would\n * invent `dummy`) whenever the key was omitted, so a block naming an empty\n * variable would show as missing on the panel while its requests still\n * authenticated — the divergence this file exists to close, pointing the other\n * way. The flag defaults to `false` in the vendored backends, so every other\n * construction (tests, probes, a bare import) keeps the historical chain.\n * @param config - resolved plugin configuration.\n * @param env - environment the API-key chain reads; defaults to `process.env`.\n * @returns the forced backend, the local-only one when nothing is configured, or\n * one chosen from the environment for `auto`.\n */\nexport function createBackend(\n config: ResolvedReflexConfig,\n env: Record<string, string | undefined> = process.env\n): DecisionBackend {\n const { backend, baseUrl, model, timeoutMs } = config.systemOne;\n // An explicitly chosen `mock` is a decision, not a connection: it answers\n // in-process and reads nothing. It therefore outranks the \"no active profile\"\n // rule — which exists to stop *network* connections nobody configured, and\n // which would otherwise make `backend: 'mock'` impossible to ask for without\n // also authoring a profile that the mock never uses.\n if (backend === 'mock') return new MockDecisionBackend();\n // No active profile — or an active profile whose model cannot be sent — no\n // connection (g-066 att-002). Checked before the key chain and before the\n // provider selector below, because both of them read the environment:\n // reaching either would be the implicit request this removes.\n //\n // The model reasons are here for a reason the review found the hard way: a\n // transport built for a broken selection still sends *something*, because\n // every implementation fills an absent `model` with `|| DEFAULT_MODEL`. The\n // only place that fallback can be kept from firing is \"no transport at all\",\n // and `UnconfiguredBackend` issues no request.\n if (config.systemOne.unconfigured !== undefined) {\n return new UnconfiguredBackend(config.systemOne.unconfigured);\n }\n const apiKey = resolvedKeyOf(resolveApiKeyWithSource(config.systemOne, env));\n // `auto` is resolved by the *one* function the connection test asks as well\n // (g-067 att-002), so the runtime and the \"Test\" button can never describe two\n // different transports for the same connection. Before this, `auto` here was\n // a delegation to the vendored factory and `auto` there was a hard-coded Jev:\n // with `SYSTEM_ONE_BACKEND=vllm` exported, the button went green on the\n // official URL while this function built a request carrying the very same\n // resolved key to a vLLM endpoint. The factory is still what `auto` *means* —\n // `connectionImplementation` reads the same precedence it does — it is just no\n // longer consulted twice.\n const implementation = backend === 'auto' ? connectionImplementation('auto', env) : backend;\n switch (implementation) {\n case 'mock':\n // The environment's `auto` answer is the in-process mock: it opens no\n // socket, so nothing configured (or resolved) leaves this process.\n return new MockDecisionBackend();\n case 'jev':\n return new JevDecisionBackend({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n // The chain above is the whole chain: no second read behind its back.\n apiKeyResolved: true,\n ...(model === undefined ? {} : { model }),\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n // The resolved config wins over SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS: the\n // backend only reads the environment when no explicit value is given.\n pruneJudgeMinChars: config.interventions.pruneJudgeMinChars\n });\n default:\n // `vllm`, and `auto` when the environment selected the logits backend.\n return new SimpleJevDecisionBackend({\n ...(baseUrl === undefined ? {} : { vllmBaseUrl: baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n // Same for the logits backend, whose `dummy` fallback would otherwise\n // turn \"no key\" into a header nobody configured.\n apiKeyResolved: true,\n ...(model === undefined ? {} : { model }),\n ...(timeoutMs === undefined ? {} : { timeoutMs })\n });\n }\n}\n\n/**\n * Build a runtime for one plugin activation.\n * @param config - resolved plugin configuration.\n * @param dependencies - test seams for the ledger, backend, and routing clock.\n * @returns the runtime the tools close over.\n */\nexport function createReflexRuntime(\n config: ResolvedReflexConfig,\n dependencies: {\n backend?: DecisionBackend;\n ledger?: DecisionLedger;\n now?: () => number;\n configSource?: unknown;\n warn?: (message: string) => void;\n } = {}\n): ReflexRuntime {\n return new ReflexRuntime(config, dependencies);\n}\n"]}
@@ -241,7 +241,10 @@ ${body}
241
241
  */
242
242
  export function readSources(directory) {
243
243
  const names = readdirSync(directory)
244
- .filter((name) => name.endsWith('.js'))
244
+ // Tests are not browser modules. A `*.test.js` here would have to `require`
245
+ // `node:assert` / `node:test`, which no client bundle may do — and nothing
246
+ // imports them, so including one could only ever fail the build.
247
+ .filter((name) => name.endsWith('.js') && !name.endsWith('.test.js'))
245
248
  .sort();
246
249
  if (names.length === 0) {
247
250
  throw new Error(`client-bundle: no compiled modules in ${directory} — run the client TypeScript build first`);
@@ -1 +1 @@
1
- {"version":3,"file":"client-bundle.js","sourceRoot":"","sources":["../src/client-bundle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAI,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,iBAAiB,CAAsB,CAAC,IAAI,CAAC;AAE7G,2DAA2D;AAC3D,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB,CAAC,OAAO,CAAC,CAAC;AAE1D,uDAAuD;AACvD,MAAM,CAAC,MAAM,oBAAoB,GAAG,WAAW,CAA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M,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACjG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/**\n * Bundler for the browser half of this plugin.\n *\n * DSH serves a client plugin as **one** artifact: `dsh.client` names an\n * `exports[\"./client\"]` entry, and the host hands that file's\n * `__ModuleLoader__.load({ id, factory })` call a `require` that resolves\n * *package ids and platform seed words only*. A plugin's own internal modules\n * therefore cannot be reached with `require(\"./x\")` at runtime — the dynamic\n * form (`require.async`) would need separately served chunks — so the artifact\n * has to be self-contained.\n *\n * This step produces exactly that, and refuses to guess while doing it:\n *\n * - The browser sources are compiled to CommonJS by `tsconfig.client.json`, so\n * no source rewriting happens here. The bundler only *wraps* what `tsc` emits,\n * which is why it can be this small: `require(\"./panel\")` in the emitted code\n * is already the call shape a local factory registry answers.\n * - Every non-relative specifier must appear in {@link ALLOWED_SEEDS}, and every\n * relative one must name a bundled module. Anything else fails the build\n * instead of the page: at runtime an unresolvable specifier throws inside the\n * module table and the plugin never activates.\n * - `verifyClientPackage` cross-checks the artifact against the manifest, so\n * `dsh.client.external`, `exports[\"./client\"]`, and `files` cannot drift away\n * from what the bundle actually needs.\n *\n * @module dsh-reflex/client-bundle\n */\nimport { readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * `__ModuleLoader__` id of the bundle: the npm package name.\n *\n * The DSH client loader keys every bundle by its **package name**\n * (`dsh-client-modules/lib/index.js:546` reads `fiber.entry.options.name`, and\n * `lib/client.js:874` rejects an artifact whose `__ModuleLoader__.load({id})`\n * does not match), so hardcoding a second copy here goes stale the moment the\n * package name changes. Reading the manifest keeps one source of truth.\n *\n * This is not the Cordis plugin id (`export const name = 'dsh-reflex'`), the\n * `/dsh-reflex/api/*` route prefix, or the `data-reflex-*` attributes — those\n * stay stable across a package rename.\n */\nexport const CLIENT_BUNDLE_ID = (createRequire(import.meta.url)('../package.json') as { name: string }).name;\n\n/** Bundled module key the factory block executes first. */\nexport const CLIENT_ENTRY_KEY = 'index';\n\n/**\n * Module specifiers the bundle may require from the platform.\n *\n * The shell's seed table is the only source of shared modules for a client\n * bundle, and `react` is the one entry this plugin needs. Growing this list is a\n * deliberate act: every addition must be a documented seed word, or the require\n * throws at materialization time in the browser.\n */\nexport const ALLOWED_SEEDS: readonly string[] = ['react'];\n\n/** Package-relative path of the committed artifact. */\nexport const BUNDLE_RELATIVE_PATH = 'client.js';\n\n/** Directory the browser sources are compiled into. */\nexport const CLIENT_OUT_DIR = 'dist-client';\n\n/** One compiled module on its way into the bundle. */\nexport interface BundleSource {\n /** Module key: the file's basename without its extension. */\n key: string;\n /** Compiled CommonJS body. */\n code: string;\n}\n\n/** Result of wrapping a set of compiled modules into one artifact. */\nexport interface BuiltBundle {\n /** The artifact text. */\n code: string;\n /** Module keys in emission order. */\n keys: string[];\n /** Non-relative specifiers the bundle requires, sorted. */\n externals: string[];\n /** Relative specifiers and the keys they resolved to. */\n localEdges: { spec: string; key: string }[];\n}\n\n/** One lexical token of a compiled module, comments excluded. */\nexport interface Token {\n kind: 'name' | 'string' | 'punct';\n /** Identifier text, string contents with escapes intact, or one punctuation character. */\n value: string;\n}\n\n/**\n * Tokenize JavaScript well enough to recognize `require(...)` calls.\n *\n * A regex over the raw text is not sufficient here: this package's prose\n * *discusses* `require` calls, and its doc comments and string literals both\n * contain parentheses, quotes and slashes. Tokenizing removes comments, keeps\n * string literals as single tokens (so a specifier is unambiguous), and drops\n * everything else into names and punctuation. Template literals are taken\n * whole — no bundled module interpolates a `require` call into one, and the\n * scanner is a build gate, not a parser.\n *\n * @param code - compiled CommonJS source.\n * @returns tokens in source order.\n */\nexport function tokenize(code: string): Token[] {\n const tokens: Token[] = [];\n let index = 0;\n while (index < code.length) {\n const char = code[index] as string;\n const next = code[index + 1];\n if (char === '/' && next === '/') {\n const end = code.indexOf('\\n', index);\n index = end === -1 ? code.length : end;\n continue;\n }\n if (char === '/' && next === '*') {\n const end = code.indexOf('*/', index + 2);\n index = end === -1 ? code.length : end + 2;\n continue;\n }\n if (char === '\"' || char === \"'\" || char === '`') {\n const quote = char;\n let value = '';\n index += 1;\n while (index < code.length) {\n const inner = code[index] as string;\n index += 1;\n if (inner === '\\\\') {\n value += inner + ((code[index] as string) ?? '');\n index += 1;\n continue;\n }\n if (inner === quote) break;\n value += inner;\n }\n tokens.push({ kind: 'string', value });\n continue;\n }\n if (/[A-Za-z_$]/.test(char)) {\n let value = char;\n index += 1;\n while (index < code.length && /[A-Za-z0-9_$]/.test(code[index] as string)) {\n value += code[index] as string;\n index += 1;\n }\n tokens.push({ kind: 'name', value });\n continue;\n }\n if (/\\s/.test(char)) {\n index += 1;\n continue;\n }\n tokens.push({ kind: 'punct', value: char });\n index += 1;\n }\n return tokens;\n}\n\n/**\n * Collect every module specifier a compiled module requires.\n * @param code - compiled CommonJS source.\n * @returns specifiers in source order, without duplicates.\n */\nexport function collectRequires(code: string): string[] {\n const tokens = tokenize(code);\n const found: string[] = [];\n for (let index = 0; index + 3 < tokens.length; index += 1) {\n if ((tokens[index] as Token).value !== 'require' || (tokens[index] as Token).kind !== 'name') continue;\n if ((tokens[index + 1] as Token).value !== '(') continue;\n const spec = tokens[index + 2] as Token;\n if (spec.kind !== 'string' || (tokens[index + 3] as Token).value !== ')') continue;\n if (!found.includes(spec.value)) found.push(spec.value);\n }\n return found;\n}\n\n/** Resolve one relative specifier to a bundled module key. */\nfunction keyOf(spec: string): string {\n return spec.replace(/^\\.\\//, '');\n}\n\n/**\n * Wrap compiled modules into one `__ModuleLoader__.load` artifact.\n *\n * @param sources - compiled modules, entry included.\n * @param options - bundle id, entry key, and the platform specifiers allowed.\n * @returns the artifact plus the edges it was built from.\n * @throws Error when the entry is absent, a relative specifier has no module, or a non-relative one is not an allowed seed.\n */\nexport function buildBundle(\n sources: readonly BundleSource[],\n options: { id?: string; entry?: string; allowedSeeds?: readonly string[] } = {}\n): BuiltBundle {\n const id = options.id ?? CLIENT_BUNDLE_ID;\n const entry = options.entry ?? CLIENT_ENTRY_KEY;\n const allowedSeeds = options.allowedSeeds ?? ALLOWED_SEEDS;\n const byKey = new Map<string, string>();\n for (const source of sources) {\n if (byKey.has(source.key)) throw new Error(`client-bundle: duplicate module key \"${source.key}\"`);\n byKey.set(source.key, source.code);\n }\n if (!byKey.has(entry)) throw new Error(`client-bundle: the module set has no entry module \"${entry}\"`);\n\n const externals = new Set<string>();\n const localEdges: { spec: string; key: string }[] = [];\n for (const source of sources) {\n for (const spec of collectRequires(source.code)) {\n if (!spec.startsWith('./')) {\n if (!allowedSeeds.includes(spec)) {\n throw new Error(\n `client-bundle: \"${source.key}\" requires \"${spec}\", which is neither a relative module nor an allowed platform seed ` +\n `(${allowedSeeds.join(', ')}) — a client bundle may only require seed words and its own bundled modules`\n );\n }\n externals.add(spec);\n continue;\n }\n const key = keyOf(spec);\n if (key.includes('/')) {\n throw new Error(`client-bundle: \"${source.key}\" requires \"${spec}\" — only flat sibling modules are bundled`);\n }\n if (!byKey.has(key)) throw new Error(`client-bundle: \"${source.key}\" requires \"${spec}\" but no module \"${key}\" is bundled`);\n localEdges.push({ spec, key });\n }\n }\n\n const ordered = sources.map((source) => source.key);\n const body = sources\n .map((source) => {\n const indented = source.code\n .split('\\n')\n .map((line) => (line.length === 0 ? line : `\\t\\t\\t${line}`))\n .join('\\n');\n return `\\t\\t\"${source.key}\": function (module, exports, require) {\\n${indented}\\n\\t\\t}`;\n })\n .join(',\\n');\n\n const code = `window.__ModuleLoader__.load({\n\\tid: \"${id}\",\n\\tfactory: (require) => {\n\\t\\tvar module = { exports: {} };\n\\t\\tvar exports = module.exports;\n\\t\\tObject.defineProperty(exports, Symbol.toStringTag, { value: \"Module\" });\n\\t\\tvar __factories = {\n${body}\n\\t\\t};\n\\t\\tvar __cache = Object.create(null);\n\\t\\tvar __load = function (key) {\n\\t\\t\\tvar cached = __cache[key];\n\\t\\t\\tif (cached !== undefined) return cached.exports;\n\\t\\t\\tvar factory = __factories[key];\n\\t\\t\\tif (factory === undefined) throw new Error(\"client-modules: no bundled module \\\\\"\" + key + \"\\\\\" in ${id}\");\n\\t\\t\\tvar record = { exports: {} };\n\\t\\t\\t__cache[key] = record;\n\\t\\t\\tfactory(record, record.exports, __require);\n\\t\\t\\treturn record.exports;\n\\t\\t};\n\\t\\tvar __require = function (spec) {\n\\t\\t\\tif (spec.charCodeAt(0) === 46) return __load(spec.replace(/^\\\\.\\\\//, \"\"));\n\\t\\t\\treturn require(spec);\n\\t\\t};\n\\t\\t__cache[\"${entry}\"] = module;\n\\t\\t__factories[\"${entry}\"](module, module.exports, __require);\n\\t\\treturn module.exports;\n\\t}\n});\n`;\n\n return { code, keys: ordered, externals: [...externals].sort(), localEdges };\n}\n\n/**\n * Read every compiled module of a directory.\n * @param directory - the directory holding the compiled browser half.\n * @returns one source per `.js` file, entry first and the rest alphabetically.\n */\nexport function readSources(directory: string): BundleSource[] {\n const names = readdirSync(directory)\n .filter((name) => name.endsWith('.js'))\n .sort();\n if (names.length === 0) {\n throw new Error(`client-bundle: no compiled modules in ${directory} — run the client TypeScript build first`);\n }\n return names.map((name) => ({\n key: name.slice(0, -3),\n code: readFileSync(join(directory, name), 'utf8')\n }));\n}\n\n/** What one artifact build produced. */\nexport interface ClientArtifact {\n outputPath: string;\n bytes: number;\n keys: string[];\n externals: string[];\n}\n\n/**\n * Compile-time view of the package.json fields this artifact depends on.\n *\n * Only the fields that must agree with the bundle are modelled; everything else\n * is ignored rather than copied, so the verifier cannot silently accept a\n * manifest shape it did not intend to check.\n */\nexport interface BundledPackageManifest {\n name?: unknown;\n files?: unknown;\n exports?: unknown;\n dsh?: unknown;\n}\n\n/**\n * Build `client.js` from a compiled browser half.\n * @param options - package directory and optional source/output overrides.\n * @returns what was written.\n */\nexport function buildClientArtifact(options: {\n packageDir: string;\n sourceDir?: string;\n outputPath?: string;\n}): ClientArtifact {\n const sourceDir = options.sourceDir ?? join(options.packageDir, CLIENT_OUT_DIR);\n const outputPath = options.outputPath ?? join(options.packageDir, BUNDLE_RELATIVE_PATH);\n const built = buildBundle(readSources(sourceDir));\n writeFileSync(outputPath, built.code);\n return { outputPath, bytes: Buffer.byteLength(built.code), keys: built.keys, externals: built.externals };\n}\n\n/**\n * Check a package manifest against its built artifact.\n * @param pkg - the parsed `package.json`.\n * @param bundle - the artifact description.\n * @param bundleExists - whether `exports[\"./client\"]` resolves to a real file.\n * @returns one message per problem; empty means the manifest and artifact agree.\n */\nexport function verifyClientPackage(\n pkg: BundledPackageManifest,\n bundle: Pick<BuiltBundle, 'externals' | 'keys'> | ClientArtifact,\n bundleExists: boolean\n): string[] {\n const problems: string[] = [];\n const dsh = pkg.dsh;\n const client = dsh !== null && typeof dsh === 'object' ? (dsh as { client?: unknown }).client : undefined;\n if (client === null || typeof client !== 'object') {\n problems.push('package.json declares no dsh.client block');\n return problems;\n }\n const declaration = client as { platform?: unknown; inject?: unknown; external?: unknown; immediately?: unknown };\n if (declaration.platform !== 'web') problems.push(`dsh.client.platform must be \"web\" (got ${JSON.stringify(declaration.platform)})`);\n if (pkg.name !== CLIENT_BUNDLE_ID) {\n problems.push(`package name ${JSON.stringify(pkg.name)} must equal the bundle id \"${CLIENT_BUNDLE_ID}\"`);\n }\n const external = Array.isArray(declaration.external) ? declaration.external.filter((item): item is string => typeof item === 'string') : [];\n for (const spec of bundle.externals) {\n if (!external.includes(spec)) problems.push(`the bundle requires platform module \"${spec}\" but dsh.client.external does not list it`);\n }\n for (const spec of external) {\n if (!bundle.externals.includes(spec)) {\n problems.push(`dsh.client.external lists \"${spec}\" but the bundle never requires it`);\n }\n }\n const exportsField = pkg.exports;\n const clientExport =\n exportsField !== null && typeof exportsField === 'object' ? (exportsField as Record<string, unknown>)['./client'] : undefined;\n const clientPath =\n typeof clientExport === 'string'\n ? clientExport\n : clientExport !== null && typeof clientExport === 'object'\n ? ((clientExport as { default?: unknown }).default as string | undefined)\n : undefined;\n if (clientPath === undefined) {\n problems.push('package.json exports no \"./client\" entry, so the browser half is unreachable');\n } else if (clientPath !== `./${BUNDLE_RELATIVE_PATH}`) {\n problems.push(`exports[\"./client\"] is ${JSON.stringify(clientPath)}, expected \"./${BUNDLE_RELATIVE_PATH}\"`);\n } else if (!bundleExists) {\n problems.push(`exports[\"./client\"] points at ${clientPath}, which does not exist — the artifact is missing or stale`);\n }\n const files = Array.isArray(pkg.files) ? pkg.files.filter((item): item is string => typeof item === 'string') : [];\n if (!files.includes(BUNDLE_RELATIVE_PATH)) problems.push(`package.json \"files\" does not include \"${BUNDLE_RELATIVE_PATH}\"`);\n if (bundle.keys.length === 0) problems.push('the bundle carries no modules');\n if (!bundle.keys.includes(CLIENT_ENTRY_KEY)) problems.push(`the bundle has no entry module \"${CLIENT_ENTRY_KEY}\"`);\n return problems;\n}\n\n/**\n * Command-line entry: build the artifact and print what it produced.\n * @param argv - process arguments; the third may name the package directory.\n * @returns the process exit code.\n */\nexport function main(argv: readonly string[]): number {\n const here = fileURLToPath(import.meta.url);\n const packageDir = resolve(argv[2] ?? dirname(dirname(here)));\n try {\n const artifact = buildClientArtifact({ packageDir });\n process.stdout.write(\n `client-bundle: wrote ${artifact.outputPath} (${String(artifact.bytes)} bytes, ${String(artifact.keys.length)} modules, externals: ${artifact.externals.join(', ') || 'none'})\\n`\n );\n return 0;\n } catch (error) {\n process.stderr.write(`client-bundle: ${error instanceof Error ? error.message : String(error)}\\n`);\n return 1;\n }\n}\n\n// Run only when this file *is* the program: importing it from a test must not\n// write artifacts as a side effect.\nif (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {\n process.exitCode = main(process.argv);\n}\n"]}
1
+ {"version":3,"file":"client-bundle.js","sourceRoot":"","sources":["../src/client-bundle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,YAAY,EAAE,WAA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,CAClB,wBAAwB,QAAQ,CAAC,UAAU,KAAK,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,KAAK,CAClL,CAAC;QACF,OAAO,CAAC,CAAC;IACX,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACnG,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC;AAED,8EAA8E;AAC9E,oCAAoC;AACpC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACjG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/**\n * Bundler for the browser half of this plugin.\n *\n * DSH serves a client plugin as **one** artifact: `dsh.client` names an\n * `exports[\"./client\"]` entry, and the host hands that file's\n * `__ModuleLoader__.load({ id, factory })` call a `require` that resolves\n * *package ids and platform seed words only*. A plugin's own internal modules\n * therefore cannot be reached with `require(\"./x\")` at runtime — the dynamic\n * form (`require.async`) would need separately served chunks — so the artifact\n * has to be self-contained.\n *\n * This step produces exactly that, and refuses to guess while doing it:\n *\n * - The browser sources are compiled to CommonJS by `tsconfig.client.json`, so\n * no source rewriting happens here. The bundler only *wraps* what `tsc` emits,\n * which is why it can be this small: `require(\"./panel\")` in the emitted code\n * is already the call shape a local factory registry answers.\n * - Every non-relative specifier must appear in {@link ALLOWED_SEEDS}, and every\n * relative one must name a bundled module. Anything else fails the build\n * instead of the page: at runtime an unresolvable specifier throws inside the\n * module table and the plugin never activates.\n * - `verifyClientPackage` cross-checks the artifact against the manifest, so\n * `dsh.client.external`, `exports[\"./client\"]`, and `files` cannot drift away\n * from what the bundle actually needs.\n *\n * @module dsh-reflex/client-bundle\n */\nimport { readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * `__ModuleLoader__` id of the bundle: the npm package name.\n *\n * The DSH client loader keys every bundle by its **package name**\n * (`dsh-client-modules/lib/index.js:546` reads `fiber.entry.options.name`, and\n * `lib/client.js:874` rejects an artifact whose `__ModuleLoader__.load({id})`\n * does not match), so hardcoding a second copy here goes stale the moment the\n * package name changes. Reading the manifest keeps one source of truth.\n *\n * This is not the Cordis plugin id (`export const name = 'dsh-reflex'`), the\n * `/dsh-reflex/api/*` route prefix, or the `data-reflex-*` attributes — those\n * stay stable across a package rename.\n */\nexport const CLIENT_BUNDLE_ID = (createRequire(import.meta.url)('../package.json') as { name: string }).name;\n\n/** Bundled module key the factory block executes first. */\nexport const CLIENT_ENTRY_KEY = 'index';\n\n/**\n * Module specifiers the bundle may require from the platform.\n *\n * The shell's seed table is the only source of shared modules for a client\n * bundle, and `react` is the one entry this plugin needs. Growing this list is a\n * deliberate act: every addition must be a documented seed word, or the require\n * throws at materialization time in the browser.\n */\nexport const ALLOWED_SEEDS: readonly string[] = ['react'];\n\n/** Package-relative path of the committed artifact. */\nexport const BUNDLE_RELATIVE_PATH = 'client.js';\n\n/** Directory the browser sources are compiled into. */\nexport const CLIENT_OUT_DIR = 'dist-client';\n\n/** One compiled module on its way into the bundle. */\nexport interface BundleSource {\n /** Module key: the file's basename without its extension. */\n key: string;\n /** Compiled CommonJS body. */\n code: string;\n}\n\n/** Result of wrapping a set of compiled modules into one artifact. */\nexport interface BuiltBundle {\n /** The artifact text. */\n code: string;\n /** Module keys in emission order. */\n keys: string[];\n /** Non-relative specifiers the bundle requires, sorted. */\n externals: string[];\n /** Relative specifiers and the keys they resolved to. */\n localEdges: { spec: string; key: string }[];\n}\n\n/** One lexical token of a compiled module, comments excluded. */\nexport interface Token {\n kind: 'name' | 'string' | 'punct';\n /** Identifier text, string contents with escapes intact, or one punctuation character. */\n value: string;\n}\n\n/**\n * Tokenize JavaScript well enough to recognize `require(...)` calls.\n *\n * A regex over the raw text is not sufficient here: this package's prose\n * *discusses* `require` calls, and its doc comments and string literals both\n * contain parentheses, quotes and slashes. Tokenizing removes comments, keeps\n * string literals as single tokens (so a specifier is unambiguous), and drops\n * everything else into names and punctuation. Template literals are taken\n * whole — no bundled module interpolates a `require` call into one, and the\n * scanner is a build gate, not a parser.\n *\n * @param code - compiled CommonJS source.\n * @returns tokens in source order.\n */\nexport function tokenize(code: string): Token[] {\n const tokens: Token[] = [];\n let index = 0;\n while (index < code.length) {\n const char = code[index] as string;\n const next = code[index + 1];\n if (char === '/' && next === '/') {\n const end = code.indexOf('\\n', index);\n index = end === -1 ? code.length : end;\n continue;\n }\n if (char === '/' && next === '*') {\n const end = code.indexOf('*/', index + 2);\n index = end === -1 ? code.length : end + 2;\n continue;\n }\n if (char === '\"' || char === \"'\" || char === '`') {\n const quote = char;\n let value = '';\n index += 1;\n while (index < code.length) {\n const inner = code[index] as string;\n index += 1;\n if (inner === '\\\\') {\n value += inner + ((code[index] as string) ?? '');\n index += 1;\n continue;\n }\n if (inner === quote) break;\n value += inner;\n }\n tokens.push({ kind: 'string', value });\n continue;\n }\n if (/[A-Za-z_$]/.test(char)) {\n let value = char;\n index += 1;\n while (index < code.length && /[A-Za-z0-9_$]/.test(code[index] as string)) {\n value += code[index] as string;\n index += 1;\n }\n tokens.push({ kind: 'name', value });\n continue;\n }\n if (/\\s/.test(char)) {\n index += 1;\n continue;\n }\n tokens.push({ kind: 'punct', value: char });\n index += 1;\n }\n return tokens;\n}\n\n/**\n * Collect every module specifier a compiled module requires.\n * @param code - compiled CommonJS source.\n * @returns specifiers in source order, without duplicates.\n */\nexport function collectRequires(code: string): string[] {\n const tokens = tokenize(code);\n const found: string[] = [];\n for (let index = 0; index + 3 < tokens.length; index += 1) {\n if ((tokens[index] as Token).value !== 'require' || (tokens[index] as Token).kind !== 'name') continue;\n if ((tokens[index + 1] as Token).value !== '(') continue;\n const spec = tokens[index + 2] as Token;\n if (spec.kind !== 'string' || (tokens[index + 3] as Token).value !== ')') continue;\n if (!found.includes(spec.value)) found.push(spec.value);\n }\n return found;\n}\n\n/** Resolve one relative specifier to a bundled module key. */\nfunction keyOf(spec: string): string {\n return spec.replace(/^\\.\\//, '');\n}\n\n/**\n * Wrap compiled modules into one `__ModuleLoader__.load` artifact.\n *\n * @param sources - compiled modules, entry included.\n * @param options - bundle id, entry key, and the platform specifiers allowed.\n * @returns the artifact plus the edges it was built from.\n * @throws Error when the entry is absent, a relative specifier has no module, or a non-relative one is not an allowed seed.\n */\nexport function buildBundle(\n sources: readonly BundleSource[],\n options: { id?: string; entry?: string; allowedSeeds?: readonly string[] } = {}\n): BuiltBundle {\n const id = options.id ?? CLIENT_BUNDLE_ID;\n const entry = options.entry ?? CLIENT_ENTRY_KEY;\n const allowedSeeds = options.allowedSeeds ?? ALLOWED_SEEDS;\n const byKey = new Map<string, string>();\n for (const source of sources) {\n if (byKey.has(source.key)) throw new Error(`client-bundle: duplicate module key \"${source.key}\"`);\n byKey.set(source.key, source.code);\n }\n if (!byKey.has(entry)) throw new Error(`client-bundle: the module set has no entry module \"${entry}\"`);\n\n const externals = new Set<string>();\n const localEdges: { spec: string; key: string }[] = [];\n for (const source of sources) {\n for (const spec of collectRequires(source.code)) {\n if (!spec.startsWith('./')) {\n if (!allowedSeeds.includes(spec)) {\n throw new Error(\n `client-bundle: \"${source.key}\" requires \"${spec}\", which is neither a relative module nor an allowed platform seed ` +\n `(${allowedSeeds.join(', ')}) — a client bundle may only require seed words and its own bundled modules`\n );\n }\n externals.add(spec);\n continue;\n }\n const key = keyOf(spec);\n if (key.includes('/')) {\n throw new Error(`client-bundle: \"${source.key}\" requires \"${spec}\" — only flat sibling modules are bundled`);\n }\n if (!byKey.has(key)) throw new Error(`client-bundle: \"${source.key}\" requires \"${spec}\" but no module \"${key}\" is bundled`);\n localEdges.push({ spec, key });\n }\n }\n\n const ordered = sources.map((source) => source.key);\n const body = sources\n .map((source) => {\n const indented = source.code\n .split('\\n')\n .map((line) => (line.length === 0 ? line : `\\t\\t\\t${line}`))\n .join('\\n');\n return `\\t\\t\"${source.key}\": function (module, exports, require) {\\n${indented}\\n\\t\\t}`;\n })\n .join(',\\n');\n\n const code = `window.__ModuleLoader__.load({\n\\tid: \"${id}\",\n\\tfactory: (require) => {\n\\t\\tvar module = { exports: {} };\n\\t\\tvar exports = module.exports;\n\\t\\tObject.defineProperty(exports, Symbol.toStringTag, { value: \"Module\" });\n\\t\\tvar __factories = {\n${body}\n\\t\\t};\n\\t\\tvar __cache = Object.create(null);\n\\t\\tvar __load = function (key) {\n\\t\\t\\tvar cached = __cache[key];\n\\t\\t\\tif (cached !== undefined) return cached.exports;\n\\t\\t\\tvar factory = __factories[key];\n\\t\\t\\tif (factory === undefined) throw new Error(\"client-modules: no bundled module \\\\\"\" + key + \"\\\\\" in ${id}\");\n\\t\\t\\tvar record = { exports: {} };\n\\t\\t\\t__cache[key] = record;\n\\t\\t\\tfactory(record, record.exports, __require);\n\\t\\t\\treturn record.exports;\n\\t\\t};\n\\t\\tvar __require = function (spec) {\n\\t\\t\\tif (spec.charCodeAt(0) === 46) return __load(spec.replace(/^\\\\.\\\\//, \"\"));\n\\t\\t\\treturn require(spec);\n\\t\\t};\n\\t\\t__cache[\"${entry}\"] = module;\n\\t\\t__factories[\"${entry}\"](module, module.exports, __require);\n\\t\\treturn module.exports;\n\\t}\n});\n`;\n\n return { code, keys: ordered, externals: [...externals].sort(), localEdges };\n}\n\n/**\n * Read every compiled module of a directory.\n * @param directory - the directory holding the compiled browser half.\n * @returns one source per `.js` file, entry first and the rest alphabetically.\n */\nexport function readSources(directory: string): BundleSource[] {\n const names = readdirSync(directory)\n // Tests are not browser modules. A `*.test.js` here would have to `require`\n // `node:assert` / `node:test`, which no client bundle may do — and nothing\n // imports them, so including one could only ever fail the build.\n .filter((name) => name.endsWith('.js') && !name.endsWith('.test.js'))\n .sort();\n if (names.length === 0) {\n throw new Error(`client-bundle: no compiled modules in ${directory} — run the client TypeScript build first`);\n }\n return names.map((name) => ({\n key: name.slice(0, -3),\n code: readFileSync(join(directory, name), 'utf8')\n }));\n}\n\n/** What one artifact build produced. */\nexport interface ClientArtifact {\n outputPath: string;\n bytes: number;\n keys: string[];\n externals: string[];\n}\n\n/**\n * Compile-time view of the package.json fields this artifact depends on.\n *\n * Only the fields that must agree with the bundle are modelled; everything else\n * is ignored rather than copied, so the verifier cannot silently accept a\n * manifest shape it did not intend to check.\n */\nexport interface BundledPackageManifest {\n name?: unknown;\n files?: unknown;\n exports?: unknown;\n dsh?: unknown;\n}\n\n/**\n * Build `client.js` from a compiled browser half.\n * @param options - package directory and optional source/output overrides.\n * @returns what was written.\n */\nexport function buildClientArtifact(options: {\n packageDir: string;\n sourceDir?: string;\n outputPath?: string;\n}): ClientArtifact {\n const sourceDir = options.sourceDir ?? join(options.packageDir, CLIENT_OUT_DIR);\n const outputPath = options.outputPath ?? join(options.packageDir, BUNDLE_RELATIVE_PATH);\n const built = buildBundle(readSources(sourceDir));\n writeFileSync(outputPath, built.code);\n return { outputPath, bytes: Buffer.byteLength(built.code), keys: built.keys, externals: built.externals };\n}\n\n/**\n * Check a package manifest against its built artifact.\n * @param pkg - the parsed `package.json`.\n * @param bundle - the artifact description.\n * @param bundleExists - whether `exports[\"./client\"]` resolves to a real file.\n * @returns one message per problem; empty means the manifest and artifact agree.\n */\nexport function verifyClientPackage(\n pkg: BundledPackageManifest,\n bundle: Pick<BuiltBundle, 'externals' | 'keys'> | ClientArtifact,\n bundleExists: boolean\n): string[] {\n const problems: string[] = [];\n const dsh = pkg.dsh;\n const client = dsh !== null && typeof dsh === 'object' ? (dsh as { client?: unknown }).client : undefined;\n if (client === null || typeof client !== 'object') {\n problems.push('package.json declares no dsh.client block');\n return problems;\n }\n const declaration = client as { platform?: unknown; inject?: unknown; external?: unknown; immediately?: unknown };\n if (declaration.platform !== 'web') problems.push(`dsh.client.platform must be \"web\" (got ${JSON.stringify(declaration.platform)})`);\n if (pkg.name !== CLIENT_BUNDLE_ID) {\n problems.push(`package name ${JSON.stringify(pkg.name)} must equal the bundle id \"${CLIENT_BUNDLE_ID}\"`);\n }\n const external = Array.isArray(declaration.external) ? declaration.external.filter((item): item is string => typeof item === 'string') : [];\n for (const spec of bundle.externals) {\n if (!external.includes(spec)) problems.push(`the bundle requires platform module \"${spec}\" but dsh.client.external does not list it`);\n }\n for (const spec of external) {\n if (!bundle.externals.includes(spec)) {\n problems.push(`dsh.client.external lists \"${spec}\" but the bundle never requires it`);\n }\n }\n const exportsField = pkg.exports;\n const clientExport =\n exportsField !== null && typeof exportsField === 'object' ? (exportsField as Record<string, unknown>)['./client'] : undefined;\n const clientPath =\n typeof clientExport === 'string'\n ? clientExport\n : clientExport !== null && typeof clientExport === 'object'\n ? ((clientExport as { default?: unknown }).default as string | undefined)\n : undefined;\n if (clientPath === undefined) {\n problems.push('package.json exports no \"./client\" entry, so the browser half is unreachable');\n } else if (clientPath !== `./${BUNDLE_RELATIVE_PATH}`) {\n problems.push(`exports[\"./client\"] is ${JSON.stringify(clientPath)}, expected \"./${BUNDLE_RELATIVE_PATH}\"`);\n } else if (!bundleExists) {\n problems.push(`exports[\"./client\"] points at ${clientPath}, which does not exist — the artifact is missing or stale`);\n }\n const files = Array.isArray(pkg.files) ? pkg.files.filter((item): item is string => typeof item === 'string') : [];\n if (!files.includes(BUNDLE_RELATIVE_PATH)) problems.push(`package.json \"files\" does not include \"${BUNDLE_RELATIVE_PATH}\"`);\n if (bundle.keys.length === 0) problems.push('the bundle carries no modules');\n if (!bundle.keys.includes(CLIENT_ENTRY_KEY)) problems.push(`the bundle has no entry module \"${CLIENT_ENTRY_KEY}\"`);\n return problems;\n}\n\n/**\n * Command-line entry: build the artifact and print what it produced.\n * @param argv - process arguments; the third may name the package directory.\n * @returns the process exit code.\n */\nexport function main(argv: readonly string[]): number {\n const here = fileURLToPath(import.meta.url);\n const packageDir = resolve(argv[2] ?? dirname(dirname(here)));\n try {\n const artifact = buildClientArtifact({ packageDir });\n process.stdout.write(\n `client-bundle: wrote ${artifact.outputPath} (${String(artifact.bytes)} bytes, ${String(artifact.keys.length)} modules, externals: ${artifact.externals.join(', ') || 'none'})\\n`\n );\n return 0;\n } catch (error) {\n process.stderr.write(`client-bundle: ${error instanceof Error ? error.message : String(error)}\\n`);\n return 1;\n }\n}\n\n// Run only when this file *is* the program: importing it from a test must not\n// write artifacts as a side effect.\nif (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {\n process.exitCode = main(process.argv);\n}\n"]}
package/dist/command.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { describeAttribution } from './attribution.js';
1
2
  /**
2
3
  * The human command that reads this activation's decision ledger.
3
4
  *
@@ -41,6 +42,12 @@ function latencyOf(latencyMs) {
41
42
  }
42
43
  /**
43
44
  * Render one entry as a single line: time, type, and the facts that entry owns.
45
+ *
46
+ * The provenance (g-068) comes last: the connection the call used and the model
47
+ * it requested, plus its source whenever that source is not a plain remote
48
+ * answer. An entry recorded before g-068 simply has none of these, and
49
+ * {@link describeAttribution} returns `undefined` for it rather than inventing
50
+ * a connection from today's settings.
44
51
  * @param entry - one ledger record.
45
52
  * @returns the line, without a trailing newline.
46
53
  */
@@ -56,6 +63,9 @@ function entryLine(entry) {
56
63
  facts.push('shadow');
57
64
  if (entry.skipReason)
58
65
  facts.push(`跳过:${entry.skipReason}`);
66
+ const provenance = describeAttribution((entry.details ?? {}));
67
+ if (provenance !== undefined)
68
+ facts.push(provenance);
59
69
  return `- ${clockOf(entry.timestamp)} ${entry.type} · ${facts.join(' · ')}`;
60
70
  }
61
71
  /**