@ekanos/harness 0.18.0 → 0.20.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 (187) hide show
  1. package/dist/api-types.d.ts +490 -0
  2. package/dist/api-types.js +6 -0
  3. package/dist/api.d.ts +33 -0
  4. package/dist/api.js +36 -1
  5. package/dist/app.js +6 -1
  6. package/dist/internal/components/approvals-tray.d.ts +17 -0
  7. package/dist/internal/components/approvals-tray.js +116 -0
  8. package/dist/internal/components/ask-assistant-bridge.js +1 -1
  9. package/dist/internal/components/connect-controls.d.ts +12 -0
  10. package/dist/internal/components/connect-controls.js +69 -0
  11. package/dist/internal/components/connect-dialog.d.ts +19 -0
  12. package/dist/internal/components/connect-dialog.js +61 -0
  13. package/dist/internal/components/connect-panel.d.ts +25 -0
  14. package/dist/internal/components/connect-panel.js +292 -0
  15. package/dist/internal/components/connection-chip.d.ts +14 -0
  16. package/dist/internal/components/connection-chip.js +75 -0
  17. package/dist/internal/components/dashboard-grid.js +38 -24
  18. package/dist/internal/components/dev-toolbar.js +176 -103
  19. package/dist/internal/components/events-panel.d.ts +10 -0
  20. package/dist/internal/components/events-panel.js +111 -0
  21. package/dist/internal/components/health-panel.d.ts +4 -0
  22. package/dist/internal/components/health-panel.js +56 -0
  23. package/dist/internal/components/integration-badge.d.ts +29 -0
  24. package/dist/internal/components/integration-badge.js +105 -0
  25. package/dist/internal/components/local-oauth-panel.js +21 -1
  26. package/dist/internal/components/operation-runner-panel.d.ts +12 -0
  27. package/dist/internal/components/operation-runner-panel.js +331 -0
  28. package/dist/internal/components/provenance-banner.d.ts +12 -0
  29. package/dist/internal/components/provenance-banner.js +107 -0
  30. package/dist/internal/components/repo-connection.d.ts +10 -0
  31. package/dist/internal/components/repo-connection.js +32 -0
  32. package/dist/internal/components/run-log.d.ts +9 -0
  33. package/dist/internal/components/run-log.js +228 -0
  34. package/dist/internal/components/runtime-strip.d.ts +12 -0
  35. package/dist/internal/components/runtime-strip.js +158 -0
  36. package/dist/internal/components/schema-form.d.ts +13 -0
  37. package/dist/internal/components/schema-form.js +382 -0
  38. package/dist/internal/components/scrollable-nav.d.ts +12 -0
  39. package/dist/internal/components/scrollable-nav.js +68 -0
  40. package/dist/internal/components/surface-nav.d.ts +31 -1
  41. package/dist/internal/components/surface-nav.js +244 -31
  42. package/dist/internal/components/workflow-runner.d.ts +14 -0
  43. package/dist/internal/components/workflow-runner.js +104 -0
  44. package/dist/internal/lib/bundled-secrets.d.ts +9 -0
  45. package/dist/internal/lib/bundled-secrets.js +24 -0
  46. package/dist/internal/lib/chrome-slot.d.ts +2 -0
  47. package/dist/internal/lib/chrome-slot.js +25 -0
  48. package/dist/internal/lib/connection-facts.d.ts +44 -0
  49. package/dist/internal/lib/connection-facts.js +116 -0
  50. package/dist/internal/lib/console-client.d.ts +55 -0
  51. package/dist/internal/lib/console-client.js +295 -0
  52. package/dist/internal/lib/console-context.d.ts +56 -0
  53. package/dist/internal/lib/console-context.js +67 -0
  54. package/dist/internal/lib/console-hooks.d.ts +33 -0
  55. package/dist/internal/lib/console-hooks.js +118 -0
  56. package/dist/internal/lib/console-types.d.ts +279 -0
  57. package/dist/internal/lib/console-types.js +0 -0
  58. package/dist/internal/lib/experience-runtime.d.ts +8 -0
  59. package/dist/internal/lib/experience-runtime.js +22 -0
  60. package/dist/internal/lib/preview-sections.d.ts +13 -0
  61. package/dist/internal/lib/preview-sections.js +32 -0
  62. package/dist/internal/lib/repo-context.d.ts +20 -0
  63. package/dist/internal/lib/repo-context.js +64 -0
  64. package/dist/internal/lib/run-log-view.d.ts +24 -0
  65. package/dist/internal/lib/run-log-view.js +57 -0
  66. package/dist/internal/lib/schema-form-model.d.ts +34 -0
  67. package/dist/internal/lib/schema-form-model.js +272 -0
  68. package/dist/internal/lib/toolbar-context.d.ts +9 -1
  69. package/dist/internal/lib/toolbar-context.js +13 -3
  70. package/dist/internal/lib/toolbar-visibility.d.ts +16 -0
  71. package/dist/internal/lib/toolbar-visibility.js +31 -0
  72. package/dist/internal/registry-context.d.ts +2 -0
  73. package/dist/internal/registry-context.js +11 -9
  74. package/dist/internal/routes/activation-page.js +44 -20
  75. package/dist/internal/routes/console-home-page.d.ts +5 -0
  76. package/dist/internal/routes/console-home-page.js +18 -0
  77. package/dist/internal/routes/experience-connect-page.d.ts +6 -0
  78. package/dist/internal/routes/experience-connect-page.js +127 -0
  79. package/dist/internal/routes/experience-layout-page.d.ts +8 -0
  80. package/dist/internal/routes/experience-layout-page.js +126 -0
  81. package/dist/internal/routes/experience-page-host.d.ts +7 -0
  82. package/dist/internal/routes/experience-page-host.js +79 -0
  83. package/dist/internal/routes/experience-review-queue-page.d.ts +2 -0
  84. package/dist/internal/routes/experience-review-queue-page.js +60 -0
  85. package/dist/internal/routes/experience-runs-page.d.ts +1 -0
  86. package/dist/internal/routes/experience-runs-page.js +13 -0
  87. package/dist/internal/routes/experience-summary-page.d.ts +1 -0
  88. package/dist/internal/routes/experience-summary-page.js +101 -0
  89. package/dist/internal/routes/experience-widget-page.d.ts +1 -0
  90. package/dist/internal/routes/experience-widget-page.js +26 -0
  91. package/dist/internal/routes/experience-widgets-page.d.ts +6 -0
  92. package/dist/internal/routes/experience-widgets-page.js +22 -0
  93. package/dist/internal/routes/experience-workflow-page.d.ts +1 -0
  94. package/dist/internal/routes/experience-workflow-page.js +24 -0
  95. package/dist/internal/routes/experience-workflows-page.d.ts +1 -0
  96. package/dist/internal/routes/experience-workflows-page.js +44 -0
  97. package/dist/internal/routes/index-page.d.ts +10 -9
  98. package/dist/internal/routes/index-page.js +3 -68
  99. package/dist/internal/routes/integration-layout.d.ts +12 -1
  100. package/dist/internal/routes/integration-layout.js +20 -6
  101. package/dist/internal/routes/integrations-connect-page.d.ts +1 -0
  102. package/dist/internal/routes/integrations-connect-page.js +19 -0
  103. package/dist/internal/routes/integrations-events-page.d.ts +1 -0
  104. package/dist/internal/routes/integrations-events-page.js +10 -0
  105. package/dist/internal/routes/integrations-health-page.d.ts +1 -0
  106. package/dist/internal/routes/integrations-health-page.js +10 -0
  107. package/dist/internal/routes/integrations-layout.d.ts +17 -0
  108. package/dist/internal/routes/integrations-layout.js +106 -0
  109. package/dist/internal/routes/integrations-list-page.d.ts +2 -0
  110. package/dist/internal/routes/integrations-list-page.js +94 -0
  111. package/dist/internal/routes/integrations-operation-page.d.ts +1 -0
  112. package/dist/internal/routes/integrations-operation-page.js +29 -0
  113. package/dist/internal/routes/integrations-operations-page.d.ts +1 -0
  114. package/dist/internal/routes/integrations-operations-page.js +61 -0
  115. package/dist/internal/routes/integrations-overview-page.d.ts +1 -0
  116. package/dist/internal/routes/integrations-overview-page.js +90 -0
  117. package/dist/internal/routes/integrations-runs-page.d.ts +1 -0
  118. package/dist/internal/routes/integrations-runs-page.js +14 -0
  119. package/dist/internal/routes/integrations-scope.d.ts +12 -0
  120. package/dist/internal/routes/integrations-scope.js +39 -0
  121. package/dist/internal/routes/legacy-preview-redirect.d.ts +6 -0
  122. package/dist/internal/routes/legacy-preview-redirect.js +12 -0
  123. package/dist/internal/routes/preview-index-page.d.ts +2 -0
  124. package/dist/internal/routes/preview-index-page.js +14 -0
  125. package/dist/internal/routes/repo-connections-page.d.ts +6 -0
  126. package/dist/internal/routes/repo-connections-page.js +8 -0
  127. package/dist/internal/routes/repo-home-page.d.ts +2 -0
  128. package/dist/internal/routes/repo-home-page.js +320 -0
  129. package/dist/internal/routes/repo-layout.d.ts +7 -0
  130. package/dist/internal/routes/repo-layout.js +76 -0
  131. package/dist/internal/routes/repo-package-layouts.d.ts +20 -0
  132. package/dist/internal/routes/repo-package-layouts.js +104 -0
  133. package/dist/internal/routes/root-layout.d.ts +3 -1
  134. package/dist/internal/routes/root-layout.js +13 -3
  135. package/dist/internal/routes/single-widget-page.js +5 -12
  136. package/dist/internal/routes/tile-page.js +20 -41
  137. package/dist/internal/routes/triggers-page.js +55 -62
  138. package/dist/internal/routes/widgets-page.js +1 -1
  139. package/dist/internal/server/api-router.js +46 -4
  140. package/dist/internal/server/approvals.d.ts +44 -0
  141. package/dist/internal/server/approvals.js +76 -0
  142. package/dist/internal/server/contract-sources.d.ts +28 -0
  143. package/dist/internal/server/contract-sources.js +83 -0
  144. package/dist/internal/server/definition-loader.d.ts +22 -0
  145. package/dist/internal/server/definition-loader.js +125 -0
  146. package/dist/internal/server/ekanos-api-router.d.ts +34 -0
  147. package/dist/internal/server/ekanos-api-router.js +835 -0
  148. package/dist/internal/server/experience-loader.d.ts +57 -0
  149. package/dist/internal/server/experience-loader.js +146 -0
  150. package/dist/internal/server/integration-lookup.d.ts +29 -0
  151. package/dist/internal/server/integration-lookup.js +33 -0
  152. package/dist/internal/server/integration-resolver.d.ts +121 -0
  153. package/dist/internal/server/integration-resolver.js +605 -0
  154. package/dist/internal/server/live-invoker.d.ts +11 -0
  155. package/dist/internal/server/live-invoker.js +106 -0
  156. package/dist/internal/server/local-secrets.d.ts +82 -1
  157. package/dist/internal/server/local-secrets.js +112 -1
  158. package/dist/internal/server/local-state.d.ts +12 -0
  159. package/dist/internal/server/local-state.js +45 -0
  160. package/dist/internal/server/oauth-persistence.d.ts +19 -0
  161. package/dist/internal/server/oauth-persistence.js +76 -0
  162. package/dist/internal/server/operation-runner.d.ts +95 -0
  163. package/dist/internal/server/operation-runner.js +231 -0
  164. package/dist/internal/server/project-manifest.d.ts +71 -0
  165. package/dist/internal/server/project-manifest.js +215 -0
  166. package/dist/internal/server/registry-cache.d.ts +68 -0
  167. package/dist/internal/server/registry-cache.js +328 -0
  168. package/dist/internal/server/repo-api-router.d.ts +33 -0
  169. package/dist/internal/server/repo-api-router.js +391 -0
  170. package/dist/internal/server/run-log.d.ts +22 -0
  171. package/dist/internal/server/run-log.js +32 -0
  172. package/dist/internal/server/semantics.d.ts +28 -0
  173. package/dist/internal/server/semantics.js +67 -0
  174. package/dist/internal/server/session-catalog.d.ts +67 -0
  175. package/dist/internal/server/session-catalog.js +18 -0
  176. package/dist/internal/server/workflow-runner.d.ts +36 -0
  177. package/dist/internal/server/workflow-runner.js +183 -0
  178. package/dist/registry.d.ts +7 -0
  179. package/dist/resolver.d.ts +145 -0
  180. package/dist/resolver.js +211 -0
  181. package/dist/routes.d.ts +66 -2
  182. package/dist/routes.js +61 -3
  183. package/dist/runtime.d.ts +46 -0
  184. package/dist/runtime.js +60 -0
  185. package/package.json +23 -9
  186. package/dist/internal/routes/integration-index-page.d.ts +0 -13
  187. package/dist/internal/routes/integration-index-page.js +0 -17
@@ -0,0 +1,835 @@
1
+ import { validateAgainstSchema } from "@ekanos/integration-schema";
2
+ import path from "node:path";
3
+ import { z } from "zod";
4
+ import { deriveConnectionFacts } from "../lib/connection-facts.js";
5
+ import { createApprovalsTray } from "./approvals.js";
6
+ import {
7
+ loadExperience,
8
+ usedByIndex
9
+ } from "./experience-loader.js";
10
+ import { publishIntegrationLookup } from "./integration-lookup.js";
11
+ import {
12
+ formatProvenanceLines,
13
+ repoOf,
14
+ resolveIntegrations
15
+ } from "./integration-resolver.js";
16
+ import { getLiveStore } from "./live-context.js";
17
+ import { liveStateFor, createLiveInvoker } from "./live-invoker.js";
18
+ import {
19
+ clearActivationBlock,
20
+ declaredSecretNames,
21
+ readLocalSecrets,
22
+ selectConnectionTarget,
23
+ writeActivationSecrets,
24
+ writeLocalSecrets
25
+ } from "./local-secrets.js";
26
+ import { isPinnedToFixtures, setPinnedToFixtures } from "./local-state.js";
27
+ import { loopbackRefusal, isLoopbackHost } from "./loopback-guard.js";
28
+ import { hasStoredOauthConnection } from "./oauth-persistence.js";
29
+ import {
30
+ createFileFixtureSource,
31
+ runOperation
32
+ } from "./operation-runner.js";
33
+ import { resolveProjectRoot } from "./project-root.js";
34
+ import { createRunLog } from "./run-log.js";
35
+ import { readSessionCatalog } from "./session-catalog.js";
36
+ import { runWorkflow } from "./workflow-runner.js";
37
+ function json(body, init = {}) {
38
+ return new Response(JSON.stringify(body), {
39
+ ...init,
40
+ headers: {
41
+ "content-type": "application/json",
42
+ "cache-control": "private, no-store",
43
+ ...init.headers ?? {}
44
+ }
45
+ });
46
+ }
47
+ function apiError(status, code, message) {
48
+ const body = { error: { code, message } };
49
+ return json(body, { status });
50
+ }
51
+ function acceptLegacySlot(body) {
52
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
53
+ return body;
54
+ }
55
+ const record = body;
56
+ if (record.slot === void 0 || record.integration !== void 0) {
57
+ return body;
58
+ }
59
+ const { slot, ...rest } = record;
60
+ return { ...rest, integration: slot };
61
+ }
62
+ const RunBodySchema = z.preprocess(
63
+ acceptLegacySlot,
64
+ z.object({
65
+ integration: z.string().min(1),
66
+ op: z.string().min(1),
67
+ input: z.unknown().optional(),
68
+ channel: z.enum(["http", "rsc", "workflow"]),
69
+ mode: z.enum(["fixtures", "live"]).optional(),
70
+ scenario: z.enum(["default", "empty", "error"]).optional(),
71
+ origin: z.string().max(200).optional()
72
+ })
73
+ );
74
+ const DecideBodySchema = z.object({ decision: z.enum(["approve", "reject"]) });
75
+ const EmitBodySchema = z.preprocess(
76
+ acceptLegacySlot,
77
+ z.object({
78
+ integration: z.string().min(1),
79
+ event: z.string().min(1),
80
+ payload: z.unknown(),
81
+ mode: z.enum(["fixtures", "live"]).optional(),
82
+ webhook: z.string().min(1).optional()
83
+ })
84
+ );
85
+ const CredentialsBodySchema = z.object({
86
+ values: z.record(z.string(), z.string())
87
+ });
88
+ const ActivationBodySchema = z.object({
89
+ activationData: z.record(z.string(), z.unknown())
90
+ });
91
+ const RuntimeModeBodySchema = z.object({ mode: z.enum(["auto", "fixtures"]) });
92
+ const DisconnectBodySchema = z.object({ clearKeys: z.boolean().optional() });
93
+ function toIntegrationView(integration, runtime) {
94
+ return {
95
+ runtime,
96
+ integration: integration.integration,
97
+ version: integration.version,
98
+ operations: integration.operations,
99
+ modes: integration.modes,
100
+ bindingMode: integration.bindingMode,
101
+ provenance: integration.provenance,
102
+ runModes: integration.runModes,
103
+ defaultMode: integration.defaultMode,
104
+ canDevelop: integration.canDevelop,
105
+ ...integration.self ? { self: true } : {},
106
+ ...integration.sameRepo ? { sameRepo: true } : {}
107
+ };
108
+ }
109
+ function createEkanosApiRouter(partial = {}) {
110
+ const env = partial.env ?? process.env;
111
+ const root = partial.projectRoot ? { ok: true, root: partial.projectRoot } : resolveProjectRoot({ env, cwd: partial.cwd ?? process.cwd() });
112
+ const httpWrites = partial.httpWrites ?? (env.EKANOS_HARNESS_HTTP_WRITES === "refuse" ? "refuse" : "approval");
113
+ const approvals = createApprovalsTray({
114
+ ...partial.now ? { now: partial.now } : {}
115
+ });
116
+ const runLog = createRunLog({ ...partial.now ? { now: partial.now } : {} });
117
+ const live = partial.live ?? createLiveInvoker();
118
+ const loadExp = partial.loadExperience ?? loadExperience;
119
+ let resolution = null;
120
+ let experience = null;
121
+ function projectRoot() {
122
+ if (!root.ok) throw new Error(root.message);
123
+ return root.root;
124
+ }
125
+ function getResolution() {
126
+ resolution ??= (async () => {
127
+ const dir = projectRoot();
128
+ const contractsDir = partial.contractsDir ?? env.EKANOS_CONTRACTS_DIR?.trim();
129
+ const catalog = partial.resolve?.catalog !== void 0 ? partial.resolve.catalog : readSessionCatalog(dir);
130
+ return resolveIntegrations({
131
+ ...partial.resolve,
132
+ projectRoot: dir,
133
+ env,
134
+ ...contractsDir ? { contractsDir } : {},
135
+ catalog
136
+ });
137
+ })();
138
+ return resolution;
139
+ }
140
+ function getExperience() {
141
+ experience ??= loadExp(projectRoot());
142
+ return experience;
143
+ }
144
+ async function factsOf(integration) {
145
+ const forced = isPinnedToFixtures(
146
+ integration.credentialRoot,
147
+ integration.integration
148
+ );
149
+ const contractAuth = integration.contract.connection.auth;
150
+ const base = {
151
+ contractAuth,
152
+ forced,
153
+ defaultMode: integration.defaultMode,
154
+ supportsLive: integration.runModes.includes("live")
155
+ };
156
+ const empty = {
157
+ usesOauth: false,
158
+ declared: [],
159
+ missing: [],
160
+ activationFieldsSet: [],
161
+ oauthHeld: false,
162
+ target: []
163
+ };
164
+ if (!integration.loadDefinition) {
165
+ return deriveConnectionFacts({ ...base, ...empty, manageable: false });
166
+ }
167
+ try {
168
+ const definition = await integration.loadDefinition();
169
+ const names = declaredSecretNames(definition);
170
+ const secrets = readLocalSecrets({
171
+ projectRoot: integration.credentialRoot,
172
+ slug: definition.slug,
173
+ names
174
+ });
175
+ if (!secrets.ok) {
176
+ return deriveConnectionFacts({
177
+ ...base,
178
+ ...empty,
179
+ manageable: true,
180
+ unreadable: secrets.message
181
+ });
182
+ }
183
+ const usesOauth = Boolean(definition.oauth) || Object.keys(definition.oauthConnections ?? {}).length > 0;
184
+ const held = getLiveStore().get(definition.slug);
185
+ return deriveConnectionFacts({
186
+ ...base,
187
+ usesOauth,
188
+ declared: names,
189
+ missing: secrets.missing,
190
+ activationFieldsSet: Object.keys(secrets.activation),
191
+ oauthHeld: Boolean(
192
+ held && (held.connection || Object.keys(held.connections).length > 0)
193
+ ) || hasStoredOauthConnection(integration.credentialRoot, definition.slug),
194
+ manageable: true,
195
+ target: selectConnectionTarget(secrets.activation, names)
196
+ });
197
+ } catch (error) {
198
+ console.error("[harness:ekanos-api] connection check failed", error);
199
+ return deriveConnectionFacts({
200
+ ...base,
201
+ ...empty,
202
+ manageable: true,
203
+ unreadable: "The connection could not be checked."
204
+ });
205
+ }
206
+ }
207
+ async function runtimeOf(integration) {
208
+ const facts = await factsOf(integration);
209
+ const noConnectionNeeded = facts.state === "no_connection_needed";
210
+ return {
211
+ mode: facts.answers,
212
+ reason: facts.answersWhy,
213
+ connected: facts.state === "connected" || noConnectionNeeded,
214
+ forced: facts.forced,
215
+ oauth: facts.kind === "oauth",
216
+ ...noConnectionNeeded ? { noConnectionNeeded: true } : {},
217
+ target: facts.target,
218
+ facts
219
+ };
220
+ }
221
+ async function run(body, gate) {
222
+ const state = await getResolution();
223
+ return runOperation(
224
+ { ...body, ...gate ? { gate } : {} },
225
+ {
226
+ integrations: state.integrations,
227
+ channels: { httpWrites },
228
+ approvals,
229
+ runLog,
230
+ fixtures: (partial.fixtures ?? createFileFixtureSource)(projectRoot()),
231
+ live,
232
+ // A call that names no mode: reads of a connected integration (or one
233
+ // that needs no connection) run live, the rest answer as configured.
234
+ // Writes are held for approval in the runner whichever mode this is.
235
+ defaultModeFor: async (integration, effect) => {
236
+ const runtime = await runtimeOf(integration);
237
+ if (runtime.forced) return "fixtures";
238
+ return effect === "read" && runtime.mode === "live" && runtime.connected ? "live" : integration.defaultMode;
239
+ },
240
+ ...partial.approvalTimeoutMs !== void 0 ? { approvalTimeoutMs: partial.approvalTimeoutMs } : {}
241
+ }
242
+ );
243
+ }
244
+ publishIntegrationLookup(async (slug) => {
245
+ try {
246
+ const state = await getResolution();
247
+ return state.integrations.find(
248
+ (integration) => integration.integration === slug
249
+ ) ?? null;
250
+ } catch {
251
+ return null;
252
+ }
253
+ });
254
+ return async (request, segments) => {
255
+ const refusal = loopbackRefusal(request, env);
256
+ if (refusal) return refusal;
257
+ const origin = request.headers.get("origin");
258
+ if (origin && env.EKANOS_HARNESS_EXPOSED !== "1") {
259
+ let originHost = "";
260
+ try {
261
+ originHost = new URL(origin).host;
262
+ } catch {
263
+ originHost = "";
264
+ }
265
+ if (!isLoopbackHost(originHost)) {
266
+ return apiError(
267
+ 403,
268
+ "cross_origin",
269
+ "Cross-origin requests to the harness API are refused."
270
+ );
271
+ }
272
+ }
273
+ if (!root.ok)
274
+ return apiError(500, "no_project_root", `${root.message} ${root.hint}`);
275
+ const method = request.method.toUpperCase();
276
+ const [head, ...rest] = segments;
277
+ try {
278
+ if ((head === "integrations" || head === "slots") && rest.length === 0) {
279
+ if (method !== "GET")
280
+ return apiError(405, "method_not_allowed", "GET only.");
281
+ const state = await getResolution();
282
+ const body = {
283
+ kind: state.kind,
284
+ integrations: await Promise.all(
285
+ state.integrations.map(
286
+ async (integration) => toIntegrationView(integration, await runtimeOf(integration))
287
+ )
288
+ ),
289
+ overrides: state.overrides,
290
+ publishBlocked: state.overrides.length > 0,
291
+ provenanceLines: formatProvenanceLines(state),
292
+ notices: state.notices,
293
+ errors: state.errors
294
+ };
295
+ if (head === "slots") {
296
+ return json({
297
+ ...body,
298
+ slots: body.integrations.map((view) => ({
299
+ ...view,
300
+ slot: view.integration,
301
+ line: view.version
302
+ }))
303
+ });
304
+ }
305
+ return json(body);
306
+ }
307
+ if (head === "contract" && rest.length === 1) {
308
+ if (method !== "GET")
309
+ return apiError(405, "method_not_allowed", "GET only.");
310
+ const state = await getResolution();
311
+ const integration = state.integrations.find(
312
+ (s) => s.integration === rest[0]
313
+ );
314
+ if (!integration)
315
+ return apiError(
316
+ 404,
317
+ "unknown_integration",
318
+ `No resolved integration uses "${rest[0]}".`
319
+ );
320
+ const exp = await getExperience().catch(() => null);
321
+ const index = new Map(
322
+ state.integrations.map((s) => [
323
+ s.integration,
324
+ { integration: s.integration, version: s.version }
325
+ ])
326
+ );
327
+ const body = {
328
+ integration: integration.integration,
329
+ version: integration.version,
330
+ contract: integration.contract,
331
+ provenance: integration.provenance,
332
+ usedBy: exp ? usedByIndex(exp, index) : {}
333
+ };
334
+ return json(body);
335
+ }
336
+ if (head === "experience" && rest.length === 0) {
337
+ if (method !== "GET")
338
+ return apiError(405, "method_not_allowed", "GET only.");
339
+ const state = await getResolution();
340
+ const exp = state.kind === "experience" ? await getExperience() : null;
341
+ if (!exp)
342
+ return apiError(
343
+ 404,
344
+ "no_experience",
345
+ "This project declares no experience."
346
+ );
347
+ const relative = (id) => id.split("/").slice(1).join("/");
348
+ const body = {
349
+ name: exp.slug,
350
+ workflows: exp.workflows.map((workflow) => ({
351
+ id: workflow.id,
352
+ title: workflow.name,
353
+ steps: workflow.steps.map((step) => ({
354
+ id: step.id,
355
+ type: step.type,
356
+ label: step.id,
357
+ ...typeof step.slot === "string" ? { integration: step.slot } : {},
358
+ ...typeof step.tool === "string" ? { opKey: step.tool } : {}
359
+ }))
360
+ })),
361
+ reviewQueue: exp.reviewQueue.map((section) => ({
362
+ id: section.id,
363
+ title: section.id,
364
+ integration: section.integration,
365
+ opKey: relative(section.read),
366
+ args: {}
367
+ })),
368
+ checks: {
369
+ pins: state.errors.length === 0 ? "ok" : "failed",
370
+ boundary: "unknown"
371
+ }
372
+ };
373
+ return json(body);
374
+ }
375
+ if (head === "ops" && rest[0] === "run" && rest.length === 1) {
376
+ if (method !== "POST")
377
+ return apiError(405, "method_not_allowed", "POST only.");
378
+ const parsed = RunBodySchema.safeParse(
379
+ await request.json().catch(() => null)
380
+ );
381
+ if (!parsed.success) {
382
+ return apiError(
383
+ 400,
384
+ "invalid_request",
385
+ parsed.error.issues.map((i) => i.message).join("; ")
386
+ );
387
+ }
388
+ const outcome = await run(parsed.data);
389
+ const body = {
390
+ result: outcome.result,
391
+ runId: outcome.run.id,
392
+ ...outcome.approvalId ? { approvalId: outcome.approvalId } : {}
393
+ };
394
+ return json(body);
395
+ }
396
+ if (head === "approvals") {
397
+ if (rest.length === 0) {
398
+ if (method !== "GET")
399
+ return apiError(405, "method_not_allowed", "GET only.");
400
+ const body = { approvals: approvals.list() };
401
+ return json(body);
402
+ }
403
+ if (rest.length === 1) {
404
+ if (method !== "POST")
405
+ return apiError(405, "method_not_allowed", "POST only.");
406
+ const parsed = DecideBodySchema.safeParse(
407
+ await request.json().catch(() => null)
408
+ );
409
+ if (!parsed.success)
410
+ return apiError(
411
+ 400,
412
+ "invalid_request",
413
+ 'Body must be { decision: "approve" | "reject" }.'
414
+ );
415
+ const current = approvals.get(rest[0]);
416
+ if (!current)
417
+ return apiError(404, "unknown_approval", "No such approval.");
418
+ if (current.status !== "pending") {
419
+ return apiError(
420
+ 409,
421
+ "already_decided",
422
+ `This approval is already ${current.status}.`
423
+ );
424
+ }
425
+ const decided = approvals.decide(rest[0], parsed.data.decision);
426
+ const body = { approval: decided };
427
+ return json(body);
428
+ }
429
+ }
430
+ if (head === "runs" && rest.length === 0) {
431
+ if (method !== "GET")
432
+ return apiError(405, "method_not_allowed", "GET only.");
433
+ const after = Number(
434
+ new URL(request.url).searchParams.get("after") ?? "0"
435
+ );
436
+ const body = runLog.list(
437
+ Number.isFinite(after) ? after : 0
438
+ );
439
+ return json(body);
440
+ }
441
+ if (head === "events" && rest[0] === "emit") {
442
+ if (method !== "POST")
443
+ return apiError(405, "method_not_allowed", "POST only.");
444
+ const parsed = EmitBodySchema.safeParse(
445
+ await request.json().catch(() => null)
446
+ );
447
+ if (!parsed.success)
448
+ return apiError(
449
+ 400,
450
+ "invalid_request",
451
+ "Body must be { integration, event, payload }."
452
+ );
453
+ const state = await getResolution();
454
+ const integration = state.integrations.find(
455
+ (s) => s.integration === parsed.data.integration
456
+ );
457
+ const event = integration?.contract.events.find(
458
+ (e) => e.name === parsed.data.event
459
+ );
460
+ if (!integration || !event)
461
+ return apiError(
462
+ 404,
463
+ "unknown_event",
464
+ "No such event in a resolved contract."
465
+ );
466
+ const errors = validateAgainstSchema(
467
+ event.payload,
468
+ parsed.data.payload
469
+ );
470
+ const exp = await getExperience().catch(() => null);
471
+ const matchingWorkflows = (exp?.workflows ?? []).filter((workflow) => {
472
+ const trigger = workflow.trigger;
473
+ return trigger?.type === "fusion_event" && [
474
+ event.name,
475
+ `${integration.integration}.${event.name}`,
476
+ `${integration.integration}/${event.name}`
477
+ ].includes(trigger.event ?? "");
478
+ }).map((workflow) => workflow.id);
479
+ const valid = errors.length === 0;
480
+ const mode = parsed.data.mode ?? integration.defaultMode;
481
+ if (mode === "live" && !integration.runModes.includes("live"))
482
+ return apiError(
483
+ 409,
484
+ "live_unavailable",
485
+ `Integration "${integration.integration}" has no integration code to run live; emit in fixtures mode.`
486
+ );
487
+ let outcome = "validated-only";
488
+ let detail;
489
+ let status = valid ? "ok" : "refused";
490
+ let failure;
491
+ if (valid && mode === "live" && live.deliverWebhook) {
492
+ const declared = integration.loadDefinition ? ((await integration.loadDefinition()).webhooks ?? []).map(
493
+ (w) => w.id
494
+ ) : [];
495
+ const bare = event.name.split(".").slice(1).join(".");
496
+ const webhookId = parsed.data.webhook ?? [event.name, bare].find((id) => id && declared.includes(id));
497
+ if (!webhookId || !declared.includes(webhookId)) {
498
+ detail = { reason: "no_handler", webhooks: declared };
499
+ } else {
500
+ const secrets = live.secretsFor(integration);
501
+ const scrub = (text) => secrets.reduce(
502
+ (out, secret) => secret.length >= 4 ? out.split(secret).join("\u2039redacted\u203A") : out,
503
+ text
504
+ );
505
+ try {
506
+ const result = await live.deliverWebhook({
507
+ integration,
508
+ webhookId,
509
+ payload: parsed.data.payload
510
+ });
511
+ outcome = "ran";
512
+ detail = {
513
+ webhook: webhookId,
514
+ status: result.status,
515
+ ...result.detail ? { detail: scrub(result.detail) } : {},
516
+ ...result.events ? { events: result.events } : {}
517
+ };
518
+ } catch (error) {
519
+ console.error(
520
+ `[harness] events/emit: webhook "${webhookId}" threw`,
521
+ error
522
+ );
523
+ outcome = "ran";
524
+ status = "error";
525
+ failure = scrub(
526
+ error instanceof Error ? error.message : String(error)
527
+ );
528
+ detail = {
529
+ webhook: webhookId,
530
+ status: "failed",
531
+ detail: failure
532
+ };
533
+ }
534
+ }
535
+ }
536
+ runLog.append({
537
+ integration: integration.integration,
538
+ version: integration.version,
539
+ opKey: `event/${event.name}`,
540
+ effect: null,
541
+ channel: "http",
542
+ mode,
543
+ provenance: integration.provenance,
544
+ status,
545
+ ...failure ? { detail: failure } : {},
546
+ durationMs: 0,
547
+ inputBytes: JSON.stringify(parsed.data.payload ?? null).length,
548
+ outputBytes: 0,
549
+ origin: "events/emit"
550
+ });
551
+ const body = {
552
+ valid,
553
+ errors,
554
+ outcome,
555
+ ...detail === void 0 ? {} : { detail },
556
+ matchingWorkflows
557
+ };
558
+ return json(body);
559
+ }
560
+ if (head === "health" && rest.length === 1) {
561
+ if (method !== "POST")
562
+ return apiError(405, "method_not_allowed", "POST only.");
563
+ const state = await getResolution();
564
+ const integration = state.integrations.find(
565
+ (s) => s.integration === rest[0]
566
+ );
567
+ if (!integration)
568
+ return apiError(
569
+ 404,
570
+ "unknown_integration",
571
+ `No resolved integration uses "${rest[0]}".`
572
+ );
573
+ const body = await checkHealth(integration);
574
+ return json(body);
575
+ }
576
+ if (head === "workflows" && rest.length === 2 && rest[1] === "run") {
577
+ if (method !== "POST")
578
+ return apiError(405, "method_not_allowed", "POST only.");
579
+ const exp = await getExperience();
580
+ const workflow = exp?.workflows.find((w) => w.id === rest[0]);
581
+ if (!workflow)
582
+ return apiError(404, "unknown_workflow", `No workflow "${rest[0]}".`);
583
+ const resolution2 = await getResolution();
584
+ const body = await runWorkflow(workflow, {
585
+ projectRoot: projectRoot(),
586
+ effectOf: (integrationName, op) => {
587
+ const contract = resolution2.integrations.find(
588
+ (s) => s.integration === integrationName
589
+ )?.contract;
590
+ const [kind, name] = op.split("/");
591
+ return contract?.operations.find(
592
+ (o) => o.kind === kind && o.name === name
593
+ )?.effect;
594
+ },
595
+ approvals,
596
+ ...partial.approvalTimeoutMs !== void 0 ? { approvalTimeoutMs: partial.approvalTimeoutMs } : {},
597
+ run: (req, gate) => run(req, gate)
598
+ });
599
+ return json(body);
600
+ }
601
+ if (head === "integrations" && rest.length === 2 && rest[1] === "mode") {
602
+ if (method !== "PUT") {
603
+ return apiError(405, "method_not_allowed", "PUT only.");
604
+ }
605
+ const state = await getResolution();
606
+ const integration = state.integrations.find(
607
+ (s) => s.integration === rest[0]
608
+ );
609
+ if (!integration) {
610
+ return apiError(
611
+ 404,
612
+ "unknown_integration",
613
+ `No resolved integration uses "${rest[0]}".`
614
+ );
615
+ }
616
+ const parsed = RuntimeModeBodySchema.safeParse(
617
+ await request.json().catch(() => null)
618
+ );
619
+ if (!parsed.success) {
620
+ return apiError(
621
+ 400,
622
+ "invalid_request",
623
+ 'Body must be { mode: "auto" | "fixtures" }.'
624
+ );
625
+ }
626
+ setPinnedToFixtures(
627
+ integration.credentialRoot,
628
+ integration.integration,
629
+ parsed.data.mode === "fixtures"
630
+ );
631
+ return json(await runtimeOf(integration));
632
+ }
633
+ if (head === "credentials" && rest.length === 2 && rest[1] === "activation") {
634
+ if (method !== "PUT") {
635
+ return apiError(405, "method_not_allowed", "PUT only.");
636
+ }
637
+ const state = await getResolution();
638
+ const integration = state.integrations.find(
639
+ (s) => s.integration === rest[0]
640
+ );
641
+ if (!integration?.loadDefinition) {
642
+ return apiError(
643
+ 404,
644
+ "unknown_integration",
645
+ `No resolved integration with local credentials is named "${rest[0]}".`
646
+ );
647
+ }
648
+ const parsed = ActivationBodySchema.safeParse(
649
+ await request.json().catch(() => null)
650
+ );
651
+ if (!parsed.success) {
652
+ return apiError(
653
+ 400,
654
+ "invalid_request",
655
+ 'Body must be { activationData: { "<field name>": "<value>" } }.'
656
+ );
657
+ }
658
+ const definition = await integration.loadDefinition();
659
+ const written = writeActivationSecrets({
660
+ projectRoot: integration.credentialRoot,
661
+ slug: definition.slug,
662
+ activationData: parsed.data.activationData
663
+ });
664
+ if (!written.ok) return apiError(400, "rejected", written.message);
665
+ getLiveStore().delete(definition.slug);
666
+ return json(await credentialsFor(integration));
667
+ }
668
+ if (head === "credentials" && rest.length === 2 && rest[1] === "disconnect") {
669
+ if (method !== "POST") {
670
+ return apiError(405, "method_not_allowed", "POST only.");
671
+ }
672
+ const state = await getResolution();
673
+ const integration = state.integrations.find(
674
+ (s) => s.integration === rest[0]
675
+ );
676
+ if (!integration?.loadDefinition) {
677
+ return apiError(
678
+ 404,
679
+ "unknown_integration",
680
+ `No resolved integration with local credentials is named "${rest[0]}".`
681
+ );
682
+ }
683
+ const parsed = DisconnectBodySchema.safeParse(
684
+ await request.json().catch(() => ({}))
685
+ );
686
+ if (!parsed.success) {
687
+ return apiError(
688
+ 400,
689
+ "invalid_request",
690
+ "Body must be { clearKeys?: boolean }."
691
+ );
692
+ }
693
+ const definition = await integration.loadDefinition();
694
+ const names = declaredSecretNames(definition);
695
+ const cleared = clearActivationBlock({
696
+ projectRoot: integration.credentialRoot,
697
+ slug: definition.slug
698
+ });
699
+ if (!cleared.ok) return apiError(400, "rejected", cleared.message);
700
+ if (parsed.data.clearKeys && names.length > 0) {
701
+ const blanked = writeLocalSecrets({
702
+ projectRoot: integration.credentialRoot,
703
+ slug: definition.slug,
704
+ names,
705
+ values: Object.fromEntries(names.map((name) => [name, ""]))
706
+ });
707
+ if (!blanked.ok) return apiError(400, "rejected", blanked.message);
708
+ }
709
+ getLiveStore().delete(definition.slug);
710
+ return json(await credentialsFor(integration));
711
+ }
712
+ if (head === "credentials" && rest.length === 1) {
713
+ const state = await getResolution();
714
+ const integration = state.integrations.find(
715
+ (s) => s.integration === rest[0]
716
+ );
717
+ if (!integration)
718
+ return apiError(
719
+ 404,
720
+ "unknown_integration",
721
+ `No resolved integration uses "${rest[0]}".`
722
+ );
723
+ if (method === "PUT") {
724
+ const parsed = CredentialsBodySchema.safeParse(
725
+ await request.json().catch(() => null)
726
+ );
727
+ if (!parsed.success)
728
+ return apiError(
729
+ 400,
730
+ "invalid_request",
731
+ "Body must be { values: { name: string } }."
732
+ );
733
+ if (!integration.loadDefinition)
734
+ return apiError(
735
+ 409,
736
+ "not_manageable",
737
+ "This integration has no credential UI (fixtures only)."
738
+ );
739
+ const definition = await integration.loadDefinition();
740
+ const written = writeLocalSecrets({
741
+ projectRoot: integration.credentialRoot,
742
+ slug: definition.slug,
743
+ names: declaredSecretNames(definition),
744
+ values: parsed.data.values
745
+ });
746
+ if (!written.ok) return apiError(400, "rejected", written.message);
747
+ } else if (method !== "GET") {
748
+ return apiError(405, "method_not_allowed", "GET or PUT only.");
749
+ }
750
+ return json(await credentialsFor(integration));
751
+ }
752
+ return apiError(
753
+ 404,
754
+ "not_found",
755
+ `No harness API route at /__ekanos/api/${segments.join("/")}.`
756
+ );
757
+ } catch (error) {
758
+ console.error("[harness:ekanos-api] handler failed", error);
759
+ return apiError(
760
+ 500,
761
+ "internal",
762
+ error instanceof Error ? error.message : String(error)
763
+ );
764
+ }
765
+ };
766
+ function displayRootOf(root2) {
767
+ const repo = repoOf(root2);
768
+ if (!repo) return void 0;
769
+ const rel = path.relative(repo.root, root2);
770
+ return rel && !rel.startsWith("..") ? rel.split(path.sep).join("/") : void 0;
771
+ }
772
+ async function credentialsFor(integration) {
773
+ const facts = await factsOf(integration);
774
+ if (!integration.loadDefinition) {
775
+ return {
776
+ integration: integration.integration,
777
+ root: integration.credentialRoot,
778
+ manageable: false,
779
+ declared: [],
780
+ set: [],
781
+ missing: [],
782
+ activationFieldsSet: [],
783
+ target: [],
784
+ ...displayRootOf(integration.credentialRoot) ? { displayRoot: displayRootOf(integration.credentialRoot) } : {},
785
+ facts
786
+ };
787
+ }
788
+ const definition = await integration.loadDefinition();
789
+ const names = declaredSecretNames(definition);
790
+ const secrets = readLocalSecrets({
791
+ projectRoot: integration.credentialRoot,
792
+ slug: definition.slug,
793
+ names
794
+ });
795
+ if (!secrets.ok) throw new Error(secrets.message);
796
+ return {
797
+ integration: integration.integration,
798
+ root: integration.credentialRoot,
799
+ manageable: true,
800
+ declared: names,
801
+ set: Object.keys(secrets.values),
802
+ missing: secrets.missing,
803
+ activationFieldsSet: Object.keys(secrets.activation),
804
+ target: selectConnectionTarget(secrets.activation, names),
805
+ oauth: facts.kind === "oauth",
806
+ ...displayRootOf(integration.credentialRoot) ? { displayRoot: displayRootOf(integration.credentialRoot) } : {},
807
+ facts
808
+ };
809
+ }
810
+ async function checkHealth(integration) {
811
+ if (!integration.loadDefinition || !integration.runModes.includes("live")) {
812
+ return { outcome: "not-checked-locally" };
813
+ }
814
+ const definition = await integration.loadDefinition();
815
+ const health = definition.health;
816
+ if (!health?.check) return { outcome: "not-checked-locally" };
817
+ const { state } = await liveStateFor(integration);
818
+ const result = await health.check(state.ctx);
819
+ let detail = result.detail;
820
+ if (detail) {
821
+ for (const secret of live.secretsFor(integration)) {
822
+ if (secret.length >= 4)
823
+ detail = detail.split(secret).join("\u2039redacted\u203A");
824
+ }
825
+ }
826
+ return {
827
+ outcome: "checked",
828
+ status: result.status,
829
+ ...detail ? { detail } : {}
830
+ };
831
+ }
832
+ }
833
+ export {
834
+ createEkanosApiRouter
835
+ };