@cleocode/runtime 2026.10.4 → 2026.10.5-rc.ci.672

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 (36) hide show
  1. package/dist/{chunk-L5BLVQDA.js → chunk-4PUSKGDO.js} +2 -2
  2. package/dist/chunk-4PUSKGDO.js.map +1 -0
  3. package/dist/{chunk-KQBVXGOL.js → chunk-GULKX44R.js} +5 -3
  4. package/dist/chunk-GULKX44R.js.map +1 -0
  5. package/dist/{chunk-7Q7BEWM7.js → chunk-HXTRXEFI.js} +7 -9
  6. package/dist/chunk-HXTRXEFI.js.map +1 -0
  7. package/dist/{chunk-U2ESNIJ5.js → chunk-NOPLC5WS.js} +4 -2
  8. package/dist/chunk-NOPLC5WS.js.map +1 -0
  9. package/dist/chunk-PDZ5T4LO.js +597 -0
  10. package/dist/chunk-PDZ5T4LO.js.map +1 -0
  11. package/dist/{chunk-XJOMQIXL.js → chunk-WO6LJMDC.js} +4 -2
  12. package/dist/chunk-WO6LJMDC.js.map +1 -0
  13. package/dist/daemon/index.js +1 -1
  14. package/dist/dispatch-BWjVeeMg.d.ts +290 -0
  15. package/dist/gateway/dispatch.d.ts +5 -0
  16. package/dist/gateway/dispatch.js +53 -0
  17. package/dist/gateway/dispatch.js.map +1 -0
  18. package/dist/gateway/http/index.d.ts +897 -11
  19. package/dist/gateway/http/index.js +2 -2
  20. package/dist/gateway/index.d.ts +549 -4
  21. package/dist/gateway/index.js +26 -581
  22. package/dist/gateway/index.js.map +1 -1
  23. package/dist/gateway/mcp/index.d.ts +232 -10
  24. package/dist/gateway/mcp/index.js +2 -2
  25. package/dist/gateway/rpc/index.d.ts +5 -2036
  26. package/dist/gateway/rpc/index.js +1 -1
  27. package/dist/gateway-handler-DCU6E0a2.d.ts +80 -0
  28. package/dist/index.d.ts +4 -3
  29. package/dist/index.js +9 -6
  30. package/dist/index.js.map +1 -1
  31. package/package.json +7 -3
  32. package/dist/chunk-7Q7BEWM7.js.map +0 -1
  33. package/dist/chunk-KQBVXGOL.js.map +0 -1
  34. package/dist/chunk-L5BLVQDA.js.map +0 -1
  35. package/dist/chunk-U2ESNIJ5.js.map +0 -1
  36. package/dist/chunk-XJOMQIXL.js.map +0 -1
@@ -27,8 +27,8 @@ import {
27
27
  statusForResponse,
28
28
  tickStreamSource,
29
29
  writeBundleAbsentError
30
- } from "../../chunk-U2ESNIJ5.js";
31
- import "../../chunk-L5BLVQDA.js";
30
+ } from "../../chunk-NOPLC5WS.js";
31
+ import "../../chunk-4PUSKGDO.js";
32
32
  export {
33
33
  NODE_PTY_INSTALL_HINT,
34
34
  SSE_HEADERS,
@@ -1,11 +1,556 @@
1
- import '@cleocode/contracts/gateway';
2
- export { a3 as BRAIN_DB_FILENAME, a4 as CLEO_DIR_NAME, DecodeResult, a5 as Dispatcher, a6 as DispatcherConfig, a7 as ErrorMeta, a8 as GatewayHandler, O as GatewayOperationKey, a9 as GatewayScope, a as GatewayStreamSource, aa as GatewaySubsystemContext, ab as GatewaySubsystemOptions, H as HttpServerHandle, b as HttpServerOptions, c as HttpUnaryRequest, d as HttpUnaryResult, LineBuffer, P as MCP_TOOL_PREFIX, Q as McpContent, R as McpInputProperty, T as McpServerOptions, V as McpTool, X as McpToolResult, ac as OPERATIONS, RpcServerHandle, RpcServerOptions, S as SSE_HEADERS, ad as STRING_TO_EXIT, e as STUDIO_PREFIX, ae as ServeGatewayHandle, af as ServeGatewayOptions, f as SseEmitter, g as SseFrame, h as SseSource, ag as StreamResolution, i as StreamSourceContext, j as StreamSourceTeardown, k as StudioStaticOptions, ah as WORKFLOWS_SUBDIR, buildErrorFrame, ai as buildNexusMetaExtensions, Y as buildToolsList, Z as callTool, aj as cleoErrorToEngineError, ak as compose, al as createDispatchMeta, am as createGatewayHandler, q as createSseStream, decodeLine, an as defineGatewaySubsystem, ao as deriveGatewayMatrix, encodeFrame, s as encodeSseFrame, t as encodeStreamEvent, ap as engineError, _ as exposedOperations, aq as formatSuggestedNext, ar as gatewaySubsystemName, as as generateTemplateConfig, at as getActiveDomains, au as getByDomain, av as getByGateway, aw as getByTier, ax as getCounts, ay as getGatewayDomains, az as getJobManager, aA as getTemplateForSubcommand, aB as inferGateway, v as isStudioPath, aC as mapNumericExitCodeToString, y as mimeType, $ as operationToMcpTool, a0 as operationToToolName, z as parseHttpRoute, aD as parseIssueTemplates, aE as pickDecoratorMetaExtensions, A as registerStreamSource, aF as resolve, aG as resolveStreamRoute, B as resolveStreamSource, C as resolveStudioAssetPath, D as resolveStudioStaticDir, routeFrame, E as routeUnary, aH as serveGateway, I as serveStudioStatic, aI as setJobManager, aJ as stampNexusMeta, J as startHttpServer, a1 as startMcpServer, startRpcServer, K as statusForResponse, L as tickStreamSource, a2 as toolNameToOperationKey, aK as validateLabels, aL as validateRequiredParams, aM as validateSuggestedNext, M as writeBundleAbsentError } from './rpc/index.js';
1
+ import { BackgroundJobManager } from '@cleocode/core/store/background-jobs.js';
3
2
  export { BackgroundJob, BackgroundJobManager, BackgroundJobManagerConfig, BackgroundJobStatus, DurableJobStore } from '@cleocode/core/store/background-jobs.js';
3
+ import { Subsystem, EngineResult, ProblemDetails } from '@cleocode/contracts';
4
4
  export { MinimalTaskRecord, OperationDef, Resolution, Session as SessionRecord, TaskRecord } from '@cleocode/contracts';
5
+ import { HttpServerHandle, HttpServerOptions } from './http/index.js';
6
+ export { GatewayStreamSource, HttpUnaryRequest, HttpUnaryResult, SSE_HEADERS, STUDIO_PREFIX, SseEmitter, SseFrame, SseSource, StreamSourceContext, StreamSourceTeardown, StudioStaticOptions, createSseStream, encodeSseFrame, encodeStreamEvent, isStudioPath, mimeType, parseHttpRoute, registerStreamSource, resolveStreamSource, resolveStudioAssetPath, resolveStudioStaticDir, routeUnary, serveStudioStatic, startHttpServer, statusForResponse, tickStreamSource, writeBundleAbsentError } from './http/index.js';
7
+ import { RpcServerHandle, RpcServerOptions } from './rpc/index.js';
8
+ export { DecodeResult, LineBuffer, buildErrorFrame, decodeLine, encodeFrame, routeFrame, startRpcServer } from './rpc/index.js';
9
+ import { G as GatewayHandler } from '../gateway-handler-DCU6E0a2.js';
10
+ export { D as Dispatcher, a as DispatcherConfig, c as createGatewayHandler } from '../gateway-handler-DCU6E0a2.js';
5
11
  export { OrchestratePlanResult } from '@cleocode/contracts/operations/orchestrate';
12
+ import * as _cleocode_core_internal from '@cleocode/core/internal';
6
13
  export { ArchiveStatsResult as ArchiveStatsData, AuditResult as AuditData, BackupResult as BackupData, BackupEntry as BackupEntryData, CleanupResult as CleanupData, CompactTask, ComplianceData, ContextData, DashboardData, DecisionRecord, DiagnosticsResult as DiagnosticsData, FileRestoreResult, HealthResult as HealthData, HelpData, HookMatrixResult, InjectGenerateResult as InjectGenerateData, IssueTemplate, IvtrHistoryEntry, LabelsResult as LabelsData, LifecycleStageEntry, LogQueryData, SystemMetricsResult as MetricsData, MigrateResult as MigrateData, OrchestratePlanInput, PathsData, PlanWarning, PlanWave, PlanWorkerEntry, ProviderMatrixEntry, ManifestEntry as ResearchManifestEntry, RestoreResult as RestoreData, RuntimeDiagnostics as RuntimeData, SafestopResult as SafestopData, ScaffoldHubData, StatsData, SyncData, TemplateConfig, TemplateSection, UncancelResult as UncancelData, addTaskWithSessionScope, completeTaskStrict, configGet, configListPresets, configSet, configSetPreset, ensureInitialized, filterEntries as filterManifestEntries, getVersion, initProject, isAutoInitEnabled, lifecycleCheck, lifecycleGateFail, lifecycleGatePass, lifecycleGates, lifecycleHistory, lifecyclePrerequisites, lifecycleProgress, lifecycleReset, lifecycleSkip, lifecycleStatus, mapCodebase, memoryBrainStats, memoryContradictions, memoryDecisionFind, memoryDecisionStore, memoryFetch, memoryFind, memoryGraphAdd, memoryGraphContext, memoryGraphNeighbors, memoryGraphRelated, memoryGraphRemove, memoryGraphShow, memoryGraphStatsFull, memoryGraphTrace, memoryLearningFind, memoryLearningStats, memoryLearningStore, memoryLink, memoryObserve, memoryPatternFind, memoryPatternStats, memoryPatternStore, memoryQualityReport, memoryReasonSimilar, memoryReasonWhy, memorySearchHybrid, memoryShow, memorySuperseded, memoryTimeline, memoryUnlink, orchestrateAnalyze, orchestrateBootstrap, orchestrateCheck, orchestrateContext, orchestrateCriticalPath, orchestrateHandoff, orchestrateNext, orchestrateParallelEnd, orchestrateParallelStart, orchestratePlan, orchestrateReady, orchestrateReport, orchestrateSkillInject, orchestrateSpawn, orchestrateSpawnExecute, orchestrateStartup, orchestrateStatus, orchestrateUnblockOpportunities, orchestrateValidate, orchestrateWaves, phaseAdvance, phaseComplete, phaseDelete, phaseList, phaseRename, phaseSet, phaseShow, phaseStart, pipelineManifestAppend, pipelineManifestArchive, pipelineManifestFind, pipelineManifestList, pipelineManifestPending, pipelineManifestShow, pipelineManifestStats, queryCommonHooks, queryHookProviders, readManifestEntries, releaseCancel, releaseCommit, releaseGateCheck, releaseGatesRun, releaseIvtrAutoSuggest, releaseList, releaseOpen, releasePlan, releasePrStatus, releasePrepare, releasePush, releaseReconcileV2, releaseRollback, releaseRollbackFull, releaseShow, releaseTag, sessionAdopt, sessionArchive, sessionBriefing, sessionChainShow, sessionCleanup, sessionComputeDebrief, sessionComputeHandoff, sessionContextDrift, sessionContextInject, sessionDebriefShow, sessionDecisionLog, sessionEnd, sessionFind, sessionGc, sessionHandoff, sessionHistory, sessionList, sessionRecordAssumption, sessionRecordDecision, sessionResume, sessionShow, sessionStart, sessionStats, sessionStatus, sessionSuspend, sessionSwitch, systemHooksMatrix, taskAnalyze, taskArchive, taskAssignee, taskBatchValidate, taskBlockers, taskBulkMove, taskCancel, taskClaim, taskComplete, taskComplexityEstimate, taskCurrentGet, taskDecompose, taskDelete, taskDepends, taskDeps, taskDepsCycles, taskDepsOverview, taskDepsTree, taskDepsValidate, taskExists, taskExport, taskFind, taskHistory, taskImpact, taskImport, taskLabelList, taskLabelShow, taskLint, taskList, taskNext, taskPlan, taskPromote, taskRankingHistory, taskRankingRevert, taskReconcileScope, taskRelates, taskRelatesAdd, taskRelatesAddBatch, taskRelatesFind, taskRelatesRemove, taskReopen, taskReorder, taskReorderRank, taskReparent, taskRestore, taskShow, taskShowIvtrHistory, taskShowOperation, taskShowWithHistory, taskSlice, taskStart, taskStats, taskStop, taskSyncLinks, taskSyncLinksRemove, taskSyncReconcile, taskTree, taskUnarchive, taskUnclaim, taskUpdate, taskWorkHistory, tasksAddBatchOp, coreBatchValidate as validateBatchValidate, validateChangelog, coreCoherenceCheck as validateCoherenceCheck, coreComplianceRecord as validateComplianceRecord, coreComplianceSummary as validateComplianceSummary, coreComplianceViolations as validateComplianceViolations, validateGateVerify, coreValidateManifest as validateManifestOp, coreValidateOutput as validateOutput, coreValidateProtocol as validateProtocol, validateProtocolArchitectureDecision, validateProtocolArtifactPublish, validateProtocolConsensus, validateProtocolContribution, validateProtocolDecomposition, validateProtocolImplementation, validateProtocolProvenance, validateProtocolRelease, validateProtocolResearch, validateProtocolSpecification, validateProtocolTesting, validateProtocolValidation, coreValidateSchema as validateSchemaOp, coreValidateTask as validateTaskOp, coreTestCoverage as validateTestCoverage, coreTestRun as validateTestRun, coreTestStatus as validateTestStatus } from '@cleocode/core/internal';
7
- export { EngineResult, engineSuccess } from '@cleocode/core';
14
+ import { EngineResult as EngineResult$1 } from '@cleocode/core';
15
+ export { EngineResult } from '@cleocode/core';
16
+ export { GatewayOperationKey, MCP_TOOL_PREFIX, McpContent, McpInputProperty, McpServerOptions, McpTool, McpToolResult, buildToolsList, callTool, exposedOperations, operationToMcpTool, operationToToolName, startMcpServer, toolNameToOperationKey } from './mcp/index.js';
17
+ export { B as BRAIN_DB_FILENAME, C as CLEO_DIR_NAME, O as OPERATIONS, S as StreamResolution, W as WORKFLOWS_SUBDIR, b as buildNexusMetaExtensions, c as compose, a as createDispatchMeta, d as deriveGatewayMatrix, f as formatSuggestedNext, g as getActiveDomains, e as getByDomain, h as getByGateway, i as getByTier, j as getCounts, k as getGatewayDomains, l as inferGateway, p as pickDecoratorMetaExtensions, r as resolve, m as resolveStreamRoute, s as stampNexusMeta, v as validateRequiredParams, n as validateSuggestedNext } from '../dispatch-BWjVeeMg.js';
18
+ export { engineSuccess } from '@cleocode/contracts/engine-result.js';
8
19
  import 'node:http';
20
+ import '@cleocode/contracts/gateway';
21
+ import 'node:stream';
9
22
  import '@cleocode/contracts/gateway/rpc';
10
23
  import 'node:net';
11
- import 'node:stream';
24
+
25
+ /**
26
+ * The gateway as a supervised **daemon subsystem**.
27
+ *
28
+ * R3-T7 (this task) closes the loop between the two R-track halves: the R3
29
+ * gateway (dispatcher + the four transport adapters) and the R2 daemon
30
+ * (`defineSubsystem` + the `SubsystemRegistry`). It expresses the
31
+ * external-facing gateway as a uniform {@link Subsystem} so the R2 daemon
32
+ * registry drives its `start → healthProbe → shutdown` lifecycle exactly like
33
+ * every other long-running concern (Studio supervision, the GC cron, …). One
34
+ * gateway subsystem is registered per scope (project / global) → one
35
+ * external-facing gateway process per scope.
36
+ *
37
+ * Which transports the daemon hosts:
38
+ * - the **RPC unix socket** (`@cleocode/runtime/gateway/rpc`) — the canonical
39
+ * local-client wire: the `cleo` CLI, Studio's server process, and test
40
+ * harnesses open it to dispatch without paying a cold `cleo` spawn.
41
+ * - the **HTTP server** (`@cleocode/runtime/gateway/http` via the daemon-local
42
+ * `startHttpServer` embedder) — for external clients that speak HTTP rather
43
+ * than the unix-socket NDJSON wire.
44
+ *
45
+ * The CLI and MCP adapters are intentionally NOT hosted by the daemon: the CLI
46
+ * adapter is in-process to the `cleo` binary, and the MCP adapter is a stdio
47
+ * server an MCP client spawns and owns — neither is a long-lived,
48
+ * daemon-supervised listener. The two external-facing listeners (RPC + HTTP)
49
+ * are the ones the daemon owns.
50
+ *
51
+ * This subsystem adds NO behavior to the adapters themselves — it only wires
52
+ * their existing `start*Server` / `close()` lifecycle (and their already-merged
53
+ * routing) into the daemon registry's uniform lifecycle. It carries NO
54
+ * `@cleocode/cleo` dependency and NO drizzle-orm (the runtime invariant): the
55
+ * caller injects the assembled {@link GatewayHandler} and the resolved bind
56
+ * coordinates; this module only orchestrates listeners.
57
+ *
58
+ * @packageDocumentation
59
+ * @module @cleocode/runtime/gateway
60
+ *
61
+ * @task T11451 (R3-T7)
62
+ * @epic T11254
63
+ * @saga T11243 SG-RUNTIME-UNIFICATION
64
+ */
65
+
66
+ /** The scope a single gateway process serves — one external-facing process per scope. */
67
+ type GatewayScope = 'project' | 'global';
68
+ /**
69
+ * Configuration for one scoped gateway subsystem.
70
+ *
71
+ * The caller injects the assembled, transport-neutral {@link GatewayHandler}
72
+ * (built with `createGatewayHandler` from its domain handlers + middleware) and
73
+ * the resolved bind coordinates for each hosted transport. The runtime never
74
+ * resolves paths/ports itself — that keeps it free of `@cleocode/paths` and of
75
+ * any policy decision about where a scope's socket/port lives.
76
+ */
77
+ interface GatewaySubsystemOptions {
78
+ /** The scope this gateway process serves (`project` | `global`). */
79
+ scope: GatewayScope;
80
+ /** The transport-neutral gateway handler every hosted transport routes through. */
81
+ handler: GatewayHandler;
82
+ /**
83
+ * RPC unix-socket transport options. When omitted, the RPC transport is not
84
+ * hosted (a deployment that only wants HTTP). At least one transport MUST be
85
+ * configured.
86
+ */
87
+ rpc?: RpcServerOptions;
88
+ /**
89
+ * HTTP transport options. When omitted, the HTTP transport is not hosted (a
90
+ * deployment that only wants the local RPC socket). At least one transport
91
+ * MUST be configured.
92
+ */
93
+ http?: HttpServerOptions;
94
+ }
95
+ /**
96
+ * The live context a started gateway subsystem threads from `start` into
97
+ * `healthProbe`/`shutdown`: the bound transport handles plus the owning pid.
98
+ *
99
+ * `void`-typed contexts are common for subsystems, but the gateway needs to
100
+ * carry its bound handles so `shutdown` can close exactly what `start` opened
101
+ * (and `healthProbe` can report the bound coordinates).
102
+ */
103
+ interface GatewaySubsystemContext {
104
+ /** The OS pid hosting the listeners (this daemon process). */
105
+ readonly pid: number;
106
+ /** The bound RPC server handle, when the RPC transport is hosted. */
107
+ readonly rpc?: RpcServerHandle;
108
+ /** The bound HTTP server handle, when the HTTP transport is hosted. */
109
+ readonly http?: HttpServerHandle;
110
+ }
111
+ /**
112
+ * The stable subsystem name (and supervised `child_id`) of a scoped gateway.
113
+ *
114
+ * Suffixed with the scope so a single daemon process supervising both scopes
115
+ * (project + global) registers two distinct, non-colliding subsystems. The
116
+ * `child_id` matches the id the Rust supervisor tracks the listener under.
117
+ *
118
+ * @param scope - The gateway scope.
119
+ * @returns The subsystem name, e.g. `gateway-project`.
120
+ */
121
+ declare function gatewaySubsystemName(scope: GatewayScope): string;
122
+ /**
123
+ * Declare the external-facing gateway as a supervised daemon {@link Subsystem}.
124
+ *
125
+ * The returned subsystem (frozen by {@link defineSubsystem}) is registered with
126
+ * a `SubsystemRegistry`, which then drives its lifecycle uniformly:
127
+ *
128
+ * - `start()` — binds the configured transports (RPC unix socket and/or
129
+ * HTTP server) over the injected handler, in a fixed order (RPC then HTTP).
130
+ * If the second listener fails to bind, the first is rolled back so a failed
131
+ * start leaves no half-open listener — then the error is re-thrown for the
132
+ * registry's `onError` sink.
133
+ * - `healthProbe()` — reports a single {@link SubsystemHealth} row keyed on the
134
+ * scoped `child_id`, `running` while the configured listeners are live, with
135
+ * a `detail` summarizing the bound coordinates. Projects losslessly onto the
136
+ * supervisor's `ChildStatus`.
137
+ * - `shutdown()` — closes every bound listener (best-effort, idempotent) in
138
+ * reverse bind order (HTTP then RPC).
139
+ *
140
+ * One subsystem instance is declared per scope, so registering the project and
141
+ * global gateways yields two supervised listeners → one external-facing gateway
142
+ * process surface per scope (AC1).
143
+ *
144
+ * @param opts - The scoped gateway configuration (handler + per-transport bind
145
+ * coordinates).
146
+ * @returns A frozen {@link Subsystem} ready to `register()` with a
147
+ * `SubsystemRegistry`.
148
+ * @throws {TypeError} When neither the RPC nor the HTTP transport is configured
149
+ * (a gateway with no hosted transport serves nothing).
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * const registry = new SubsystemRegistry();
154
+ * registry.register(
155
+ * defineGatewaySubsystem({
156
+ * scope: 'project',
157
+ * handler: createGatewayHandler(dispatcherConfig),
158
+ * rpc: { socketPath: '/run/cleo/cleo-gateway-rpc-project.sock' },
159
+ * http: { port: 7777 },
160
+ * }),
161
+ * );
162
+ * await registry.startAll(); // binds the RPC socket + HTTP server
163
+ * const health = await registry.aggregateHealth();
164
+ * await registry.shutdownAll(); // closes both listeners
165
+ * ```
166
+ */
167
+ declare function defineGatewaySubsystem(opts: GatewaySubsystemOptions): Subsystem<GatewaySubsystemContext>;
168
+
169
+ /**
170
+ * Centralized engine error helper for the transport-agnostic gateway.
171
+ *
172
+ * Every domain handler (and the engine barrel) imports `engineError()` /
173
+ * `engineSuccess()` from this module to produce consistently typed error
174
+ * results with correct exit codes and pino logging.
175
+ *
176
+ * The STRING_TO_EXIT map is the canonical mapping from string error codes
177
+ * to numeric exit codes. It mirrors ERROR_CODE_TO_EXIT in cli.ts.
178
+ *
179
+ * @remarks
180
+ * Relocated from `packages/cleo/src/dispatch/engines/_error.ts` into
181
+ * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the
182
+ * runtime owns the shared handler dependencies and can assemble the handler map
183
+ * without importing `@cleocode/cleo`. A thin re-export shim remains at the old
184
+ * `engines/_error.ts` path so in-package import sites compile unchanged.
185
+ *
186
+ * Error codes are organized into numeric ranges:
187
+ * - 1-9: General errors (invalid input, file, dependency, validation)
188
+ * - 10-19: Hierarchy errors (parent, depth, siblings, circular deps)
189
+ * - 20-29: Concurrency errors (checksum, modification, collision)
190
+ * - 30-39: Session errors (scope, claims, active task)
191
+ * - 40-47: Verification errors (gates, agents, rounds)
192
+ * - 50-54: Context safeguard (warning through emergency)
193
+ * - 60-67: Orchestrator / protocol errors
194
+ * - 70-79: Nexus errors
195
+ * - 80-94: Lifecycle, artifact, provenance errors
196
+ * - 95-99: Adapter errors
197
+ * - 100+: Special informational codes (not errors)
198
+ */
199
+
200
+ /**
201
+ * Canonical mapping from string error codes to numeric exit codes.
202
+ *
203
+ * Source of truth: src/types/exit-codes.ts (ExitCode enum).
204
+ * Must stay in sync with ERROR_CODE_TO_EXIT in src/dispatch/adapters/cli.ts.
205
+ */
206
+ declare const STRING_TO_EXIT: Record<string, number>;
207
+ /**
208
+ * Create a typed engine error result with pino logging and correct exit code.
209
+ *
210
+ * @remarks
211
+ * The exit code is derived from the {@link STRING_TO_EXIT} mapping. If the
212
+ * code is not found in the map, exit code 1 (general error) is used.
213
+ * Pino logging is automatically triggered at the appropriate level
214
+ * (error for internal issues, warn for user/domain errors, debug for
215
+ * informational codes). Logging is suppressed under Vitest to keep
216
+ * test output clean.
217
+ *
218
+ * @param code - String error code (e.g., 'E_NOT_FOUND')
219
+ * @param message - Human-readable error message
220
+ * @param options - Optional details, fix command, and alternatives
221
+ * @returns EngineResult with success=false and properly structured error
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * import { engineError } from './_error.js';
226
+ *
227
+ * return engineError('E_NOT_FOUND', `Task ${id} not found`, {
228
+ * fix: `cleo show ${id}`,
229
+ * details: { taskId: id },
230
+ * });
231
+ * ```
232
+ */
233
+ declare function engineError<T>(code: string, message: string, options?: {
234
+ exitCode?: number;
235
+ details?: Record<string, unknown>;
236
+ fix?: string;
237
+ alternatives?: Array<{
238
+ action: string;
239
+ command: string;
240
+ }>;
241
+ problemDetails?: ProblemDetails;
242
+ }): EngineResult<T>;
243
+
244
+ /**
245
+ * Minimal meta shape carrying the request ID for RFC 7807 `instance` population.
246
+ *
247
+ * Callers may pass the dispatch-layer `DispatchRequest.requestId` (or any
248
+ * other correlation identifier) so that the resulting `problemDetails.instance`
249
+ * URI uniquely identifies the specific error occurrence.
250
+ */
251
+ interface ErrorMeta {
252
+ /** Unique request identifier (used as the RFC 7807 `instance` field). */
253
+ requestId?: string;
254
+ }
255
+ /**
256
+ * Convert any caught value into an {@link EngineResult}, forwarding the rich
257
+ * `fix`, `details`, and `alternatives` fields when the caught value is a
258
+ * `CleoError` (or structurally compatible object).
259
+ *
260
+ * @remarks
261
+ * This is the canonical catch-block helper for all dispatch engines. It
262
+ * replaces the previous pattern of:
263
+ * ```typescript
264
+ * const code = (err as { code?: number })?.code;
265
+ * if (code === 4) return engineError('E_NOT_FOUND', …);
266
+ * …
267
+ * ```
268
+ * with a single call that preserves every field the core layer attached.
269
+ *
270
+ * The `fallbackCode` is used when the numeric `err.code` is not present in
271
+ * the {@link STRING_TO_EXIT} mapping (e.g. unknown exit codes, plain `Error`
272
+ * instances, or values thrown by non-CLEO code).
273
+ *
274
+ * RFC 7807 `problemDetails` is always populated from the resolved code, message,
275
+ * and exit code. The optional `meta.requestId` is forwarded to the `instance`
276
+ * field so every error occurrence is uniquely identifiable.
277
+ *
278
+ * @param err - The caught value (unknown type)
279
+ * @param fallbackCode - String error code to use when mapping fails
280
+ * @param fallbackMessage - Human-readable message when `err.message` is absent
281
+ * @param meta - Optional dispatch meta carrying `requestId` for RFC 7807 `instance`
282
+ * @returns EngineResult with all available rich fields propagated
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * import { cleoErrorToEngineError } from './_error.js';
287
+ *
288
+ * } catch (err: unknown) {
289
+ * return cleoErrorToEngineError(err, 'E_NOT_INITIALIZED', 'Task database not initialized');
290
+ * }
291
+ * ```
292
+ *
293
+ * @example With requestId for RFC 7807 instance field:
294
+ * ```typescript
295
+ * } catch (err: unknown) {
296
+ * return cleoErrorToEngineError(err, 'E_NOT_FOUND', 'Not found', { requestId });
297
+ * }
298
+ * ```
299
+ */
300
+ declare function cleoErrorToEngineError<T>(err: unknown, fallbackCode: string, fallbackMessage: string, meta?: ErrorMeta): EngineResult<T>;
301
+
302
+ /**
303
+ * Parse all templates from the repo's .github/ISSUE_TEMPLATE/ directory.
304
+ *
305
+ * @remarks
306
+ * Delegates to the core template parser and adapts the result to the
307
+ * dispatch EngineResult type.
308
+ *
309
+ * @param projectRoot - Absolute path to the project root
310
+ * @returns EngineResult containing the parsed template configuration
311
+ *
312
+ * @example
313
+ * ```typescript
314
+ * const result = parseIssueTemplates('/path/to/project');
315
+ * if (result.success) {
316
+ * console.log(result.data.templates);
317
+ * }
318
+ * ```
319
+ */
320
+ declare function parseIssueTemplates(projectRoot: string): EngineResult$1<_cleocode_core_internal.TemplateConfig>;
321
+ /**
322
+ * Get template config for a specific subcommand (bug/feature/help).
323
+ *
324
+ * @remarks
325
+ * Looks up a specific template by subcommand name from the project's
326
+ * issue template directory.
327
+ *
328
+ * @param projectRoot - Absolute path to the project root
329
+ * @param subcommand - Template subcommand identifier (e.g. "bug", "feature")
330
+ * @returns EngineResult containing the matched issue template
331
+ *
332
+ * @example
333
+ * ```typescript
334
+ * const result = getTemplateForSubcommand('/path/to/project', 'bug');
335
+ * ```
336
+ */
337
+ declare function getTemplateForSubcommand(projectRoot: string, subcommand: string): EngineResult$1<_cleocode_core_internal.IssueTemplate>;
338
+ /**
339
+ * Generate and cache the config as .cleo/issue-templates.json.
340
+ *
341
+ * @remarks
342
+ * Parses all templates and writes the resulting config to disk for caching.
343
+ *
344
+ * @param projectRoot - Absolute path to the project root
345
+ * @returns EngineResult containing the generated template configuration
346
+ *
347
+ * @example
348
+ * ```typescript
349
+ * const result = await generateTemplateConfig('/path/to/project');
350
+ * ```
351
+ */
352
+ declare function generateTemplateConfig(projectRoot: string): Promise<EngineResult$1<_cleocode_core_internal.TemplateConfig>>;
353
+ /**
354
+ * Validate that labels exist on a GitHub repo.
355
+ *
356
+ * @remarks
357
+ * Compares a set of required labels against the labels found on the repo.
358
+ *
359
+ * @param labels - Labels required by the template
360
+ * @param repoLabels - Labels that exist on the GitHub repo
361
+ * @returns EngineResult with existing and missing label lists
362
+ *
363
+ * @example
364
+ * ```typescript
365
+ * const result = validateLabels(['bug', 'enhancement'], repoLabels);
366
+ * ```
367
+ */
368
+ declare function validateLabels(labels: string[], repoLabels: string[]): EngineResult$1<{
369
+ existing: string[];
370
+ missing: string[];
371
+ }>;
372
+
373
+ /**
374
+ * Shared exit-code mapping utilities for the transport-agnostic gateway.
375
+ *
376
+ * Provides a canonical reverse lookup from numeric exit code to string error code,
377
+ * shared between the gateway engine helpers and every transport adapter (CLI,
378
+ * MCP, RPC, HTTP).
379
+ *
380
+ * @remarks
381
+ * Relocated from `packages/cleo/src/dispatch/lib/exit-codes.ts` into
382
+ * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the
383
+ * runtime can host the shared handler dependencies without importing
384
+ * `@cleocode/cleo`. A thin re-export shim remains at the old path.
385
+ *
386
+ * The forward mapping (string → number) lives in `engine-error.ts` as
387
+ * `STRING_TO_EXIT`. This module derives the inverse on first call and memoises
388
+ * it so engines can resolve a caught `CleoError.code` (numeric) to the
389
+ * string code expected by `engineError()`.
390
+ *
391
+ * @task T374
392
+ * @task T11455
393
+ * @epic T335
394
+ */
395
+ /**
396
+ * Map a numeric CleoError exit code to the canonical string engine error code.
397
+ *
398
+ * @remarks
399
+ * Returns `undefined` when the numeric code is not present in the
400
+ * `STRING_TO_EXIT` map, allowing callers to fall back to their own default.
401
+ *
402
+ * @param numericCode - Numeric exit code from a caught `CleoError.code`
403
+ * @returns Canonical string error code (e.g. `'E_NOT_FOUND'`), or `undefined`
404
+ *
405
+ * @example
406
+ * ```typescript
407
+ * import { mapNumericExitCodeToString } from '../lib/exit-codes.js';
408
+ *
409
+ * const code = mapNumericExitCodeToString(4) ?? 'E_NOT_INITIALIZED';
410
+ * // → 'E_NOT_FOUND'
411
+ * ```
412
+ */
413
+ declare function mapNumericExitCodeToString(numericCode: number | undefined): string | undefined;
414
+
415
+ /**
416
+ * Singleton accessor for the gateway {@link BackgroundJobManager}.
417
+ *
418
+ * @remarks
419
+ * Relocated from `packages/cleo/src/dispatch/lib/job-manager-accessor.ts` into
420
+ * `@cleocode/runtime/gateway` (R3-K1 · T11455 · SG-RUNTIME-UNIFICATION) so the
421
+ * `admin` domain handler resolves the job-manager singleton from the runtime
422
+ * layer rather than a cleo-internal path. A thin re-export shim remains at the
423
+ * old path so any existing import site compiles unchanged.
424
+ *
425
+ * Long-lived hosts (e.g. the daemon) call {@link setJobManager} once at startup;
426
+ * short-lived CLI invocations leave the singleton `null`, and consumers handle
427
+ * the absence gracefully.
428
+ *
429
+ * @task T4820
430
+ * @task T11455
431
+ */
432
+
433
+ /**
434
+ * Register the process-wide {@link BackgroundJobManager} singleton.
435
+ *
436
+ * @param manager - The manager to expose, or null to unregister a stopped host.
437
+ * @remarks Hosts unregister before closing their store; absence is reported explicitly.
438
+ */
439
+ declare function setJobManager(manager: BackgroundJobManager | null): void;
440
+ /**
441
+ * Retrieve the registered {@link BackgroundJobManager} singleton.
442
+ *
443
+ * @returns The registered manager, or `null` when running in a short-lived
444
+ * host (e.g. a one-shot CLI invocation) that never called {@link setJobManager}.
445
+ */
446
+ declare function getJobManager(): BackgroundJobManager | null;
447
+
448
+ /**
449
+ * Daemon-side gateway server bootstrap — the call-site `cleo daemon serve`
450
+ * drives (T11919).
451
+ *
452
+ * The HTTP gateway adapter (`./http/listen.ts`, T11254) and the supervised
453
+ * `defineGatewaySubsystem` unit (`./daemon-subsystem.ts`, T11451) both already
454
+ * exist, but nothing started them: the daemon had no `serve` call-site. This
455
+ * module is that thin bootstrap — it assembles a {@link SubsystemRegistry} with
456
+ * one scoped gateway subsystem hosting the HTTP transport (loopback by default)
457
+ * over an INJECTED {@link GatewayHandler}, starts it, and returns a live handle
458
+ * with the bound port + an idempotent `close()`.
459
+ *
460
+ * It carries NO `@cleocode/cleo` dependency and NO drizzle (the runtime
461
+ * invariant): the caller (`cleo daemon serve`) injects the assembled CLI gateway
462
+ * handler and the resolved bind coordinates. Secrets never touch the wire —
463
+ * sealed-handle resolution happens server-side inside the dispatched handler,
464
+ * exactly as it does for an in-process CLI call. The HTTP listener binds
465
+ * `127.0.0.1` by default (loopback only); exposing it on a public interface is
466
+ * an explicit caller decision.
467
+ *
468
+ * The streaming transports (SSE — T11921, WS — T11922) extend the SAME
469
+ * subsystem: when their listeners land they bind alongside the unary HTTP server
470
+ * here, so this bootstrap deliberately owns only transport assembly + lifecycle,
471
+ * leaving the per-route seam to the adapter (`parseHttpRoute`).
472
+ *
473
+ * @packageDocumentation
474
+ * @module @cleocode/runtime/gateway
475
+ *
476
+ * @task T11919
477
+ * @epic T11769
478
+ * @saga T10400
479
+ */
480
+
481
+ /**
482
+ * Options for {@link serveGateway}.
483
+ *
484
+ * The caller injects the assembled {@link GatewayHandler} and resolves the bind
485
+ * coordinates so the runtime stays free of `@cleocode/paths`/`@cleocode/cleo`.
486
+ */
487
+ interface ServeGatewayOptions {
488
+ /** The transport-neutral gateway handler every hosted transport routes through. */
489
+ handler: GatewayHandler;
490
+ /** TCP port to bind. `0` selects an ephemeral port (readable from the handle). */
491
+ port: number;
492
+ /** Host/interface to bind. Defaults to `127.0.0.1` (loopback only). */
493
+ host?: string;
494
+ /** The scope this gateway process serves. Defaults to `'global'`. */
495
+ scope?: GatewayScope;
496
+ /**
497
+ * Absolute path to the Studio static asset directory (T11979).
498
+ *
499
+ * When set, the HTTP server serves the bundled CLEO Web Studio at `/studio`
500
+ * using the `build/client/` static assets from an `adapter-node` Studio build.
501
+ * When `undefined`, `/studio` routes return a clean 503 "bundle absent" JSON
502
+ * envelope. The caller resolves this path (typically via
503
+ * `resolveStudioStaticDir` from `@cleocode/cleo`) so the runtime stays free of
504
+ * any path-resolution policy.
505
+ */
506
+ studioStaticDir?: string;
507
+ }
508
+ /**
509
+ * A live gateway server handle returned by {@link serveGateway}.
510
+ *
511
+ * Exposes the actually-bound `port`/`host` (resolved even when `0` was
512
+ * requested) and an idempotent {@link close} for deterministic teardown
513
+ * (daemon shutdown, tests). Mirrors the lower-level
514
+ * {@link import('./http/listen.js').HttpServerHandle} so a test can boot, probe,
515
+ * and tear down on an ephemeral port.
516
+ */
517
+ interface ServeGatewayHandle {
518
+ /** The actually-bound HTTP port (resolved when `0` was requested). */
519
+ port: number;
520
+ /** Host/interface the HTTP listener is bound to. */
521
+ host: string;
522
+ /** The scope the gateway process serves. */
523
+ scope: GatewayScope;
524
+ /** Stop every bound listener (best-effort, idempotent); resolves once closed. */
525
+ close(): Promise<void>;
526
+ }
527
+ /**
528
+ * Boot the HTTP gateway as a supervised subsystem and return a live handle.
529
+ *
530
+ * Declares one scoped gateway subsystem hosting the HTTP transport (loopback
531
+ * default) over the injected handler via {@link defineGatewaySubsystem}, starts
532
+ * it, and reads the actually-bound port from the start context (so the caller —
533
+ * and tests — learn the ephemeral port when `0` was requested). The returned
534
+ * `close()` drives the subsystem's `shutdown(context)` so teardown is the same
535
+ * lifecycle the daemon registry uses for every other supervised concern.
536
+ *
537
+ * Using `defineGatewaySubsystem` directly (rather than a full
538
+ * `SubsystemRegistry`) keeps the bound HTTP handle in reach for the port
539
+ * resolution while still routing through the canonical start→shutdown contract.
540
+ *
541
+ * @param opts - The injected handler + resolved bind coordinates.
542
+ * @returns A promise resolving to the live {@link ServeGatewayHandle}.
543
+ *
544
+ * @example
545
+ * ```ts
546
+ * const handle = await serveGateway({
547
+ * handler: createCliGatewayHandler(),
548
+ * port: 0, // ephemeral
549
+ * });
550
+ * // POST http://127.0.0.1:${handle.port}/v1/tasks/show
551
+ * await handle.close();
552
+ * ```
553
+ */
554
+ declare function serveGateway(opts: ServeGatewayOptions): Promise<ServeGatewayHandle>;
555
+
556
+ export { type ErrorMeta, GatewayHandler, type GatewayScope, type GatewaySubsystemContext, type GatewaySubsystemOptions, HttpServerHandle, HttpServerOptions, RpcServerHandle, RpcServerOptions, STRING_TO_EXIT, type ServeGatewayHandle, type ServeGatewayOptions, cleoErrorToEngineError, defineGatewaySubsystem, engineError, gatewaySubsystemName, generateTemplateConfig, getJobManager, getTemplateForSubcommand, mapNumericExitCodeToString, parseIssueTemplates, serveGateway, setJobManager, validateLabels };