@tangle-network/agent-runtime 0.337.2 → 0.339.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 (155) hide show
  1. package/dist/{activation-DRHM55Oo.d.ts → activation-CJIIl_Ey.d.ts} +90 -22
  2. package/dist/activation-CVSFxis9.js +876 -0
  3. package/dist/activation-CVSFxis9.js.map +1 -0
  4. package/dist/agent.d.ts +4 -4
  5. package/dist/agent.js +4 -7
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{bundle-BPGjESee.js → bundle-DVOhBTic.js} +2 -2
  8. package/dist/{bundle-BPGjESee.js.map → bundle-DVOhBTic.js.map} +1 -1
  9. package/dist/candidate-execution/index.d.ts +4 -63
  10. package/dist/candidate-execution/index.js +6 -146
  11. package/dist/candidate-execution/index.js.map +1 -1
  12. package/dist/content-digest-sBTLujlK.js +9 -0
  13. package/dist/content-digest-sBTLujlK.js.map +1 -0
  14. package/dist/{delegate-B-T_ZB50.js → delegate-CCWE_AkU.js} +2 -2
  15. package/dist/{delegate-B-T_ZB50.js.map → delegate-CCWE_AkU.js.map} +1 -1
  16. package/dist/{coordination-driver-BHkFVqIq.js → driver-control-acknowledgers-C53ggdJ6.js} +4520 -4442
  17. package/dist/driver-control-acknowledgers-C53ggdJ6.js.map +1 -0
  18. package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
  19. package/dist/durable-file-gNI9ILAn.js.map +1 -0
  20. package/dist/durable.d.ts +3 -35
  21. package/dist/durable.js +225 -229
  22. package/dist/durable.js.map +1 -1
  23. package/dist/{graph-C4RFlWAJ.js → graph-CI9JXKqO.js} +65 -18
  24. package/dist/graph-CI9JXKqO.js.map +1 -0
  25. package/dist/{graph-registry-DAI6KNXB.js → graph-registry-BnO64cn8.js} +18 -17
  26. package/dist/graph-registry-BnO64cn8.js.map +1 -0
  27. package/dist/{improvement-cycle-D1I4hQvf.js → improve-BOXTLWJ3.js} +76 -1248
  28. package/dist/improve-BOXTLWJ3.js.map +1 -0
  29. package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-HUt_-cWA.d.ts} +2 -20
  30. package/dist/index.d.ts +10 -207
  31. package/dist/index.js +91 -305
  32. package/dist/index.js.map +1 -1
  33. package/dist/intelligence.d.ts +10 -229
  34. package/dist/intelligence.js +506 -88
  35. package/dist/intelligence.js.map +1 -1
  36. package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
  37. package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
  38. package/dist/kernel.d.ts +4 -3
  39. package/dist/kernel.js +12 -13
  40. package/dist/loop-runner-CWzG1bH4.d.ts +32 -0
  41. package/dist/loop-runner-bin.d.ts +32 -2
  42. package/dist/loop-runner-bin.js +93 -1
  43. package/dist/loop-runner-bin.js.map +1 -0
  44. package/dist/loop-runner-pmPIHFVY.js +59 -0
  45. package/dist/loop-runner-pmPIHFVY.js.map +1 -0
  46. package/dist/mcp/bin.js +3 -3
  47. package/dist/mcp/bin.js.map +1 -1
  48. package/dist/mcp/index.d.ts +101 -416
  49. package/dist/mcp/index.js +122 -206
  50. package/dist/mcp/index.js.map +1 -1
  51. package/dist/mcp/memory-bin.js +231 -1
  52. package/dist/mcp/memory-bin.js.map +1 -1
  53. package/dist/model-policy-CyCUwHed.js.map +1 -1
  54. package/dist/placement.d.ts +2 -9
  55. package/dist/placement.js +1 -1
  56. package/dist/placement.js.map +1 -1
  57. package/dist/platform.d.ts +194 -2
  58. package/dist/platform.js +145 -9
  59. package/dist/platform.js.map +1 -1
  60. package/dist/{prepare-CER-ZkPp.js → prepare-bXkvPMJA.js} +1213 -710
  61. package/dist/prepare-bXkvPMJA.js.map +1 -0
  62. package/dist/{profile-gNUsHNIJ.js → profile-Dpei_Sq0.js} +89 -3
  63. package/dist/profile-Dpei_Sq0.js.map +1 -0
  64. package/dist/{profile-materialization-BnoEf1co.d.ts → profile-materialization-B1wm2SPT.d.ts} +3 -5
  65. package/dist/profiles.d.ts +2 -2
  66. package/dist/profiles.js +4 -43
  67. package/dist/profiles.js.map +1 -1
  68. package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-BGgpy2r9.d.ts} +4 -30
  69. package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
  70. package/dist/{provision-supervisor-DGegCUH4.js → provision-supervisor-CJ6Zz6dz.js} +13 -10
  71. package/dist/provision-supervisor-CJ6Zz6dz.js.map +1 -0
  72. package/dist/record-value-B6bwJxLa.js +12 -0
  73. package/dist/record-value-B6bwJxLa.js.map +1 -0
  74. package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-C9oL62sW.js} +175 -100
  75. package/dist/run-cancellation-C9oL62sW.js.map +1 -0
  76. package/dist/{runtime-BOGpotnH.js → runtime-B2fjL9Oi.js} +2639 -3187
  77. package/dist/runtime-B2fjL9Oi.js.map +1 -0
  78. package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
  79. package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-BzVBFqrz.js} +690 -699
  80. package/dist/sandbox-profile-compat-BzVBFqrz.js.map +1 -0
  81. package/dist/search-executor-zMumiak_.js +1916 -0
  82. package/dist/search-executor-zMumiak_.js.map +1 -0
  83. package/dist/{server-hZWM-G8w.js → server-_4voDNrl.js} +362 -67
  84. package/dist/server-_4voDNrl.js.map +1 -0
  85. package/dist/{search-executor-Cm1WZmL-.js → structural-rollout-DpLCXzaL.js} +1680 -3403
  86. package/dist/structural-rollout-DpLCXzaL.js.map +1 -0
  87. package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
  88. package/dist/substrate-CGDFTSRh.js.map +1 -0
  89. package/dist/{supervise-CvAKVfue.js → supervise-qAwXmPtD.js} +7768 -5360
  90. package/dist/supervise-qAwXmPtD.js.map +1 -0
  91. package/dist/{supervisor-Rz8AGpYb.js → supervisor-DHrUJhEZ.js} +26301 -26964
  92. package/dist/supervisor-DHrUJhEZ.js.map +1 -0
  93. package/dist/testing.d.ts +227 -2
  94. package/dist/testing.js +13 -14
  95. package/dist/testing.js.map +1 -1
  96. package/dist/tool-loop.d.ts +1 -1
  97. package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
  98. package/dist/tool-server-XV4aJwoQ.js.map +1 -0
  99. package/dist/top-snapshot-CbZE1JsU.js +502 -0
  100. package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
  101. package/dist/tui/bin.js +711 -1
  102. package/dist/tui/bin.js.map +1 -1
  103. package/dist/tui/index.d.ts +5 -71
  104. package/dist/tui/index.js +3 -3
  105. package/dist/{types-Dl5L4r8Z.d.ts → types-CaOXqRTq.d.ts} +16230 -17376
  106. package/dist/workspace-store/index.d.ts +2 -27
  107. package/dist/workspace-store/index.js +2 -2
  108. package/dist/workspace-store/index.js.map +1 -1
  109. package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BiS4ABah.d.ts} +19 -32
  110. package/package.json +2 -2
  111. package/skills/agent-graphs/SKILL.md +10 -3
  112. package/skills/agent-graphs/references/authoring.md +18 -0
  113. package/skills/profile-authoring/SKILL.md +3 -3
  114. package/skills/supervise/SKILL.md +2 -2
  115. package/dist/activation-BDP6Eivv.js +0 -234
  116. package/dist/activation-BDP6Eivv.js.map +0 -1
  117. package/dist/coder-yhVWbdWc.js +0 -40
  118. package/dist/coder-yhVWbdWc.js.map +0 -1
  119. package/dist/coordination-driver-BHkFVqIq.js.map +0 -1
  120. package/dist/delegation-status-CF4D0NZ_.js +0 -358
  121. package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
  122. package/dist/durable-file-B_eJr6Mb.js.map +0 -1
  123. package/dist/graph-C4RFlWAJ.js.map +0 -1
  124. package/dist/graph-registry-DAI6KNXB.js.map +0 -1
  125. package/dist/improvement-cycle-D1I4hQvf.js.map +0 -1
  126. package/dist/integrations-DopfCC2a.d.ts +0 -190
  127. package/dist/integrations-dFi-ALk7.js +0 -132
  128. package/dist/integrations-dFi-ALk7.js.map +0 -1
  129. package/dist/kb-gate-C8z2juK8.d.ts +0 -80
  130. package/dist/kb-gate-DpaSwXVx.js +0 -80
  131. package/dist/kb-gate-DpaSwXVx.js.map +0 -1
  132. package/dist/loop-runner-bin-DOuBIJ2O.d.ts +0 -164
  133. package/dist/loop-runner-bin-Dv5QvYDH.js +0 -246
  134. package/dist/loop-runner-bin-Dv5QvYDH.js.map +0 -1
  135. package/dist/memory-server-DXQ8IxGR.js +0 -234
  136. package/dist/memory-server-DXQ8IxGR.js.map +0 -1
  137. package/dist/openai-tools-DoQ32vpe.js +0 -44
  138. package/dist/openai-tools-DoQ32vpe.js.map +0 -1
  139. package/dist/openai-tools-Oxk4KQrY.d.ts +0 -24
  140. package/dist/prepare-CER-ZkPp.js.map +0 -1
  141. package/dist/profile-gNUsHNIJ.js.map +0 -1
  142. package/dist/protected-model-port-BuRsviSL.js +0 -766
  143. package/dist/protected-model-port-BuRsviSL.js.map +0 -1
  144. package/dist/provision-supervisor-DGegCUH4.js.map +0 -1
  145. package/dist/run-layout-Cu8H7aeh.js.map +0 -1
  146. package/dist/runtime-BOGpotnH.js.map +0 -1
  147. package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
  148. package/dist/search-executor-Cm1WZmL-.js.map +0 -1
  149. package/dist/server-hZWM-G8w.js.map +0 -1
  150. package/dist/substrate-B0TYNrXn.js.map +0 -1
  151. package/dist/supervise-CvAKVfue.js.map +0 -1
  152. package/dist/supervisor-Rz8AGpYb.js.map +0 -1
  153. package/dist/tool-server-Dqer2M4_.js.map +0 -1
  154. package/dist/top-app-BaMw1W2z.js +0 -1212
  155. package/dist/top-app-BaMw1W2z.js.map +0 -1
@@ -1,190 +0,0 @@
1
- //#region src/platform/integrations.d.ts
2
- /**
3
- * Server-side client for the Tangle platform's integration hub
4
- * (`/v1/hub/*`). Consumer apps use this instead of rolling their own
5
- * OAuth + connection tables.
6
- *
7
- * Auth: the caller supplies a bearer (either the user's API key from
8
- * cross-site exchange, or a platform service token) on construction.
9
- *
10
- * Endpoint contract (authoritative): the platform's `src/lib/hub-contract.ts`
11
- * + `src/routes/hub.ts`. The platform wraps every response in
12
- * `{ success, data }`; non-2xx or `success:false` surfaces as `PlatformHubError`
13
- * carrying the real upstream status.
14
- */
15
- interface PlatformHubClientOptions {
16
- /** Platform base URL, e.g. `https://id.tangle.tools`. */
17
- baseUrl: string;
18
- /** Bearer credential — user API key or service token. */
19
- bearer: string;
20
- /** Override fetch (tests + edge runtimes). */
21
- fetchImpl?: typeof fetch;
22
- }
23
- /** A live integration connection, as returned by `/v1/hub/connections`. */
24
- interface PlatformConnection {
25
- id: string;
26
- providerId: string;
27
- displayName: string;
28
- accountDisplay: string | null;
29
- scopes: string[];
30
- status: 'active' | 'revoked' | 'unhealthy' | 'reconnect_required' | (string & {});
31
- health: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {});
32
- createdAt: string;
33
- updatedAt: string;
34
- lastUsedAt: string | null;
35
- }
36
- /** A connectable provider in the catalog (`/v1/hub/providers`). */
37
- interface PlatformCatalogProvider {
38
- providerId: string;
39
- title?: string;
40
- authKind?: string;
41
- category?: string;
42
- scopes?: string[];
43
- capabilityCount?: number;
44
- native?: boolean;
45
- /** Whether the OAuth app's credentials are wired — the UI offers Connect
46
- * only when true. */
47
- configured?: boolean;
48
- [k: string]: unknown;
49
- }
50
- interface CatalogResult {
51
- providers: PlatformCatalogProvider[];
52
- /** Count of substrate-bundled connectors behind the catalog. */
53
- substrateBundled?: number;
54
- [k: string]: unknown;
55
- }
56
- interface StartAuthInput {
57
- /** The provider to connect (goes in the URL path). */
58
- providerId: string;
59
- /** Accepted for interface compatibility; the platform's start endpoint is
60
- * provider-level and does not consume a connector id. */
61
- connectorId?: string;
62
- /** Where the platform redirects the user back to after OAuth. */
63
- returnUrl: string;
64
- /** Accepted for interface compatibility; not consumed by the start endpoint. */
65
- requestedScopes?: string[];
66
- /** CLI flow flag — affects the platform's post-auth redirect handling. */
67
- cli?: boolean;
68
- }
69
- interface StartAuthResult {
70
- /** The URL to send the user to. Normalized across the platform's two start
71
- * branches: github returns `authorizationUrl`, substrate returns
72
- * `redirectUrl`. */
73
- authorizationUrl: string;
74
- state: string;
75
- expiresAt?: string;
76
- scopes?: string[];
77
- }
78
- interface ConnectionHealth {
79
- status: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {});
80
- checkedAt: string;
81
- error?: {
82
- code: string;
83
- message: string;
84
- };
85
- }
86
- interface ConnectionHealthResult {
87
- connection: PlatformConnection;
88
- health: ConnectionHealth;
89
- }
90
- /** Last-known health for a connection, derived from the connection row. */
91
- interface HealthCheck {
92
- connectionId: string;
93
- providerId: string;
94
- /** Mirrors `PlatformConnection.health`. */
95
- status: ConnectionHealth['status'];
96
- checkedAt?: string;
97
- }
98
- interface MintTokenInput {
99
- /** The hub action the token authorizes (e.g. `slack.chat.postMessage`). */
100
- actionPath: string;
101
- /** Bind to a specific connection, or … */
102
- connectionId?: string;
103
- /** … resolve the connection by provider for the calling user. */
104
- provider?: string;
105
- }
106
- interface MintTokenResult {
107
- tokenId: string;
108
- token: string;
109
- expiresAt: string;
110
- }
111
- interface ExecInput {
112
- /** The hub action path to execute. */
113
- path: string;
114
- input?: unknown;
115
- connectionId?: string;
116
- }
117
- interface PlatformHubStatus {
118
- contract?: unknown;
119
- principal: {
120
- kind: string;
121
- userId: string;
122
- [k: string]: unknown;
123
- };
124
- connections: {
125
- connectedProviderCount: number;
126
- unhealthyProviderCount: number;
127
- };
128
- }
129
- /** Thrown when a `PlatformHubClient` request returns a non-success status. */
130
- declare class PlatformHubError extends Error {
131
- readonly status: number;
132
- readonly code: string | undefined;
133
- readonly body: unknown;
134
- constructor(message: string, status: number, code: string | undefined, body: unknown);
135
- }
136
- /** HTTP client for the Tangle Platform Hub API: provider catalog, connection flow, and status. */
137
- declare class PlatformHubClient {
138
- private readonly baseUrl;
139
- private readonly bearer;
140
- private readonly fetchImpl;
141
- constructor(options: PlatformHubClientOptions);
142
- /** GET /v1/hub/providers — the connectable provider catalog. */
143
- catalog(): Promise<CatalogResult>;
144
- /** GET /v1/hub/connections — the calling user's live connections. */
145
- listConnections(): Promise<PlatformConnection[]>;
146
- /** DELETE /v1/hub/connections/:connectionId — revoke + disable a connection. */
147
- revokeConnection(connectionId: string): Promise<{
148
- connection: PlatformConnection;
149
- }>;
150
- /**
151
- * POST /v1/hub/connections/:provider/start — begin OAuth/grant. The provider
152
- * is taken from the URL; the body carries `returnUrl` (+ `cli`). The platform's
153
- * two start branches name the URL field differently (github → `authorizationUrl`,
154
- * substrate → `redirectUrl`); this normalizes to `authorizationUrl`.
155
- */
156
- startAuth(input: StartAuthInput): Promise<StartAuthResult>;
157
- /**
158
- * Last-known health for every connection. The platform has no global
159
- * healthcheck listing — health rides on each connection row — so this derives
160
- * the list from `listConnections()` (one request, no extra round-trips).
161
- */
162
- listHealthchecks(): Promise<HealthCheck[]>;
163
- /**
164
- * POST /v1/hub/connections/:connectionId/health — trigger a fresh health
165
- * probe for one connection and return its updated state.
166
- */
167
- checkConnectionHealth(connectionId: string): Promise<ConnectionHealthResult>;
168
- /**
169
- * Trigger a fresh health probe across all of the user's connections. The
170
- * platform exposes health per-connection only, so this fans out over
171
- * `listConnections()`. `scheduled` is the number of probes dispatched.
172
- */
173
- runHealthchecks(): Promise<{
174
- scheduled: number;
175
- }>;
176
- /** GET /v1/hub/status — principal + aggregate connection counts. */
177
- status(): Promise<PlatformHubStatus>;
178
- /**
179
- * POST /v1/hub/tokens — mint a short-lived, action-scoped capability token a
180
- * sandbox can use to invoke one hub action on the user's behalf without
181
- * seeing the underlying provider credential.
182
- */
183
- mintToken(input: MintTokenInput): Promise<MintTokenResult>;
184
- /** POST /v1/hub/exec — execute a hub action and return its result. */
185
- exec(input: ExecInput): Promise<unknown>;
186
- private request;
187
- }
188
- //#endregion
189
- export { HealthCheck as a, PlatformCatalogProvider as c, PlatformHubClientOptions as d, PlatformHubError as f, StartAuthResult as h, ExecInput as i, PlatformConnection as l, StartAuthInput as m, ConnectionHealth as n, MintTokenInput as o, PlatformHubStatus as p, ConnectionHealthResult as r, MintTokenResult as s, CatalogResult as t, PlatformHubClient as u };
190
- //# sourceMappingURL=integrations-DopfCC2a.d.ts.map
@@ -1,132 +0,0 @@
1
- //#region src/platform/integrations.ts
2
- /** Thrown when a `PlatformHubClient` request returns a non-success status. */
3
- var PlatformHubError = class extends Error {
4
- status;
5
- code;
6
- body;
7
- constructor(message, status, code, body) {
8
- super(message);
9
- this.status = status;
10
- this.code = code;
11
- this.body = body;
12
- this.name = "PlatformHubError";
13
- }
14
- };
15
- /** HTTP client for the Tangle Platform Hub API: provider catalog, connection flow, and status. */
16
- var PlatformHubClient = class {
17
- baseUrl;
18
- bearer;
19
- fetchImpl;
20
- constructor(options) {
21
- if (!options.baseUrl) throw new Error("PlatformHubClient: baseUrl is required");
22
- if (!options.bearer) throw new Error("PlatformHubClient: bearer is required");
23
- this.baseUrl = options.baseUrl.replace(/\/+$/, "");
24
- this.bearer = options.bearer;
25
- this.fetchImpl = options.fetchImpl ?? ((url, init) => fetch(url, init));
26
- }
27
- /** GET /v1/hub/providers — the connectable provider catalog. */
28
- catalog() {
29
- return this.request("GET", "/v1/hub/providers");
30
- }
31
- /** GET /v1/hub/connections — the calling user's live connections. */
32
- async listConnections() {
33
- return (await this.request("GET", "/v1/hub/connections")).connections;
34
- }
35
- /** DELETE /v1/hub/connections/:connectionId — revoke + disable a connection. */
36
- revokeConnection(connectionId) {
37
- return this.request("DELETE", `/v1/hub/connections/${encodeURIComponent(connectionId)}`);
38
- }
39
- /**
40
- * POST /v1/hub/connections/:provider/start — begin OAuth/grant. The provider
41
- * is taken from the URL; the body carries `returnUrl` (+ `cli`). The platform's
42
- * two start branches name the URL field differently (github → `authorizationUrl`,
43
- * substrate → `redirectUrl`); this normalizes to `authorizationUrl`.
44
- */
45
- async startAuth(input) {
46
- const body = { returnUrl: input.returnUrl };
47
- if (input.cli !== void 0) body.cli = input.cli;
48
- const data = await this.request("POST", `/v1/hub/connections/${encodeURIComponent(input.providerId)}/start`, body);
49
- const authorizationUrl = data.authorizationUrl ?? data.redirectUrl;
50
- if (!authorizationUrl) throw new PlatformHubError("Platform hub start response missing an authorization URL", 502, "HUB_INVALID_START_RESPONSE", data);
51
- return {
52
- authorizationUrl,
53
- state: data.state,
54
- expiresAt: data.expiresAt,
55
- scopes: data.scopes
56
- };
57
- }
58
- /**
59
- * Last-known health for every connection. The platform has no global
60
- * healthcheck listing — health rides on each connection row — so this derives
61
- * the list from `listConnections()` (one request, no extra round-trips).
62
- */
63
- async listHealthchecks() {
64
- return (await this.listConnections()).map((c) => ({
65
- connectionId: c.id,
66
- providerId: c.providerId,
67
- status: c.health,
68
- checkedAt: c.updatedAt
69
- }));
70
- }
71
- /**
72
- * POST /v1/hub/connections/:connectionId/health — trigger a fresh health
73
- * probe for one connection and return its updated state.
74
- */
75
- checkConnectionHealth(connectionId) {
76
- return this.request("POST", `/v1/hub/connections/${encodeURIComponent(connectionId)}/health`);
77
- }
78
- /**
79
- * Trigger a fresh health probe across all of the user's connections. The
80
- * platform exposes health per-connection only, so this fans out over
81
- * `listConnections()`. `scheduled` is the number of probes dispatched.
82
- */
83
- async runHealthchecks() {
84
- const connections = await this.listConnections();
85
- await Promise.allSettled(connections.map((c) => this.checkConnectionHealth(c.id)));
86
- return { scheduled: connections.length };
87
- }
88
- /** GET /v1/hub/status — principal + aggregate connection counts. */
89
- status() {
90
- return this.request("GET", "/v1/hub/status");
91
- }
92
- /**
93
- * POST /v1/hub/tokens — mint a short-lived, action-scoped capability token a
94
- * sandbox can use to invoke one hub action on the user's behalf without
95
- * seeing the underlying provider credential.
96
- */
97
- mintToken(input) {
98
- return this.request("POST", "/v1/hub/tokens", input);
99
- }
100
- /** POST /v1/hub/exec — execute a hub action and return its result. */
101
- async exec(input) {
102
- return (await this.request("POST", "/v1/hub/exec", input)).result;
103
- }
104
- async request(method, path, body) {
105
- const headers = {
106
- authorization: `Bearer ${this.bearer}`,
107
- accept: "application/json"
108
- };
109
- if (body !== void 0) headers["content-type"] = "application/json";
110
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
111
- method,
112
- headers,
113
- body: body !== void 0 ? JSON.stringify(body) : void 0
114
- });
115
- const text = await res.text();
116
- let parsed = null;
117
- if (text) try {
118
- parsed = JSON.parse(text);
119
- } catch {}
120
- if (!res.ok || parsed && parsed.success === false) {
121
- const code = parsed?.error && typeof parsed.error === "object" ? parsed.error.code : void 0;
122
- throw new PlatformHubError(parsed?.error && typeof parsed.error === "object" && parsed.error.message || (typeof parsed?.error === "string" ? parsed.error : `Platform hub error (${res.status})`), res.status, code, parsed ?? text);
123
- }
124
- if (!parsed) throw new PlatformHubError(`Platform hub returned non-JSON success (${res.status})`, res.status, void 0, text);
125
- if (parsed.data === void 0) throw new PlatformHubError("Platform hub envelope missing `data`", res.status, void 0, parsed);
126
- return parsed.data;
127
- }
128
- };
129
- //#endregion
130
- export { PlatformHubError as n, PlatformHubClient as t };
131
-
132
- //# sourceMappingURL=integrations-dFi-ALk7.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"integrations-dFi-ALk7.js","names":[],"sources":["../src/platform/integrations.ts"],"sourcesContent":["/**\n * Server-side client for the Tangle platform's integration hub\n * (`/v1/hub/*`). Consumer apps use this instead of rolling their own\n * OAuth + connection tables.\n *\n * Auth: the caller supplies a bearer (either the user's API key from\n * cross-site exchange, or a platform service token) on construction.\n *\n * Endpoint contract (authoritative): the platform's `src/lib/hub-contract.ts`\n * + `src/routes/hub.ts`. The platform wraps every response in\n * `{ success, data }`; non-2xx or `success:false` surfaces as `PlatformHubError`\n * carrying the real upstream status.\n */\n\nexport interface PlatformHubClientOptions {\n /** Platform base URL, e.g. `https://id.tangle.tools`. */\n baseUrl: string\n /** Bearer credential — user API key or service token. */\n bearer: string\n /** Override fetch (tests + edge runtimes). */\n fetchImpl?: typeof fetch\n}\n\n/** A live integration connection, as returned by `/v1/hub/connections`. */\nexport interface PlatformConnection {\n id: string\n providerId: string\n displayName: string\n accountDisplay: string | null\n scopes: string[]\n status: 'active' | 'revoked' | 'unhealthy' | 'reconnect_required' | (string & {})\n health: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {})\n createdAt: string\n updatedAt: string\n lastUsedAt: string | null\n}\n\n/** A connectable provider in the catalog (`/v1/hub/providers`). */\nexport interface PlatformCatalogProvider {\n providerId: string\n title?: string\n authKind?: string\n category?: string\n scopes?: string[]\n capabilityCount?: number\n native?: boolean\n /** Whether the OAuth app's credentials are wired — the UI offers Connect\n * only when true. */\n configured?: boolean\n [k: string]: unknown\n}\n\nexport interface CatalogResult {\n providers: PlatformCatalogProvider[]\n /** Count of substrate-bundled connectors behind the catalog. */\n substrateBundled?: number\n [k: string]: unknown\n}\n\nexport interface StartAuthInput {\n /** The provider to connect (goes in the URL path). */\n providerId: string\n /** Accepted for interface compatibility; the platform's start endpoint is\n * provider-level and does not consume a connector id. */\n connectorId?: string\n /** Where the platform redirects the user back to after OAuth. */\n returnUrl: string\n /** Accepted for interface compatibility; not consumed by the start endpoint. */\n requestedScopes?: string[]\n /** CLI flow flag — affects the platform's post-auth redirect handling. */\n cli?: boolean\n}\n\nexport interface StartAuthResult {\n /** The URL to send the user to. Normalized across the platform's two start\n * branches: github returns `authorizationUrl`, substrate returns\n * `redirectUrl`. */\n authorizationUrl: string\n state: string\n expiresAt?: string\n scopes?: string[]\n}\n\nexport interface ConnectionHealth {\n status: 'unknown' | 'healthy' | 'unhealthy' | 'rate_limited' | (string & {})\n checkedAt: string\n error?: { code: string; message: string }\n}\n\nexport interface ConnectionHealthResult {\n connection: PlatformConnection\n health: ConnectionHealth\n}\n\n/** Last-known health for a connection, derived from the connection row. */\nexport interface HealthCheck {\n connectionId: string\n providerId: string\n /** Mirrors `PlatformConnection.health`. */\n status: ConnectionHealth['status']\n checkedAt?: string\n}\n\nexport interface MintTokenInput {\n /** The hub action the token authorizes (e.g. `slack.chat.postMessage`). */\n actionPath: string\n /** Bind to a specific connection, or … */\n connectionId?: string\n /** … resolve the connection by provider for the calling user. */\n provider?: string\n}\n\nexport interface MintTokenResult {\n tokenId: string\n token: string\n expiresAt: string\n}\n\nexport interface ExecInput {\n /** The hub action path to execute. */\n path: string\n input?: unknown\n connectionId?: string\n}\n\nexport interface PlatformHubStatus {\n contract?: unknown\n principal: { kind: string; userId: string; [k: string]: unknown }\n connections: { connectedProviderCount: number; unhealthyProviderCount: number }\n}\n\n/** Thrown when a `PlatformHubClient` request returns a non-success status. */\nexport class PlatformHubError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string | undefined,\n public readonly body: unknown,\n ) {\n super(message)\n this.name = 'PlatformHubError'\n }\n}\n\ninterface PlatformEnvelope<T> {\n success: boolean\n data?: T\n error?: { code?: string; message?: string } | string\n}\n\n/** HTTP client for the Tangle Platform Hub API: provider catalog, connection flow, and status. */\nexport class PlatformHubClient {\n private readonly baseUrl: string\n private readonly bearer: string\n private readonly fetchImpl: typeof fetch\n\n constructor(options: PlatformHubClientOptions) {\n if (!options.baseUrl) throw new Error('PlatformHubClient: baseUrl is required')\n if (!options.bearer) throw new Error('PlatformHubClient: bearer is required')\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.bearer = options.bearer\n this.fetchImpl =\n options.fetchImpl ??\n ((url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => fetch(url, init))\n }\n\n /** GET /v1/hub/providers — the connectable provider catalog. */\n catalog(): Promise<CatalogResult> {\n return this.request('GET', '/v1/hub/providers')\n }\n\n /** GET /v1/hub/connections — the calling user's live connections. */\n async listConnections(): Promise<PlatformConnection[]> {\n const data = await this.request<{ connections: PlatformConnection[] }>(\n 'GET',\n '/v1/hub/connections',\n )\n return data.connections\n }\n\n /** DELETE /v1/hub/connections/:connectionId — revoke + disable a connection. */\n revokeConnection(connectionId: string): Promise<{ connection: PlatformConnection }> {\n return this.request('DELETE', `/v1/hub/connections/${encodeURIComponent(connectionId)}`)\n }\n\n /**\n * POST /v1/hub/connections/:provider/start — begin OAuth/grant. The provider\n * is taken from the URL; the body carries `returnUrl` (+ `cli`). The platform's\n * two start branches name the URL field differently (github → `authorizationUrl`,\n * substrate → `redirectUrl`); this normalizes to `authorizationUrl`.\n */\n async startAuth(input: StartAuthInput): Promise<StartAuthResult> {\n const body: { returnUrl: string; cli?: boolean } = { returnUrl: input.returnUrl }\n if (input.cli !== undefined) body.cli = input.cli\n const data = await this.request<{\n authorizationUrl?: string\n redirectUrl?: string\n state: string\n expiresAt?: string\n scopes?: string[]\n }>('POST', `/v1/hub/connections/${encodeURIComponent(input.providerId)}/start`, body)\n const authorizationUrl = data.authorizationUrl ?? data.redirectUrl\n if (!authorizationUrl) {\n throw new PlatformHubError(\n 'Platform hub start response missing an authorization URL',\n 502,\n 'HUB_INVALID_START_RESPONSE',\n data,\n )\n }\n return { authorizationUrl, state: data.state, expiresAt: data.expiresAt, scopes: data.scopes }\n }\n\n /**\n * Last-known health for every connection. The platform has no global\n * healthcheck listing — health rides on each connection row — so this derives\n * the list from `listConnections()` (one request, no extra round-trips).\n */\n async listHealthchecks(): Promise<HealthCheck[]> {\n const connections = await this.listConnections()\n return connections.map((c) => ({\n connectionId: c.id,\n providerId: c.providerId,\n status: c.health,\n checkedAt: c.updatedAt,\n }))\n }\n\n /**\n * POST /v1/hub/connections/:connectionId/health — trigger a fresh health\n * probe for one connection and return its updated state.\n */\n checkConnectionHealth(connectionId: string): Promise<ConnectionHealthResult> {\n return this.request('POST', `/v1/hub/connections/${encodeURIComponent(connectionId)}/health`)\n }\n\n /**\n * Trigger a fresh health probe across all of the user's connections. The\n * platform exposes health per-connection only, so this fans out over\n * `listConnections()`. `scheduled` is the number of probes dispatched.\n */\n async runHealthchecks(): Promise<{ scheduled: number }> {\n const connections = await this.listConnections()\n await Promise.allSettled(connections.map((c) => this.checkConnectionHealth(c.id)))\n return { scheduled: connections.length }\n }\n\n /** GET /v1/hub/status — principal + aggregate connection counts. */\n status(): Promise<PlatformHubStatus> {\n return this.request('GET', '/v1/hub/status')\n }\n\n /**\n * POST /v1/hub/tokens — mint a short-lived, action-scoped capability token a\n * sandbox can use to invoke one hub action on the user's behalf without\n * seeing the underlying provider credential.\n */\n mintToken(input: MintTokenInput): Promise<MintTokenResult> {\n return this.request('POST', '/v1/hub/tokens', input)\n }\n\n /** POST /v1/hub/exec — execute a hub action and return its result. */\n async exec(input: ExecInput): Promise<unknown> {\n const data = await this.request<{ result: unknown }>('POST', '/v1/hub/exec', input)\n return data.result\n }\n\n private async request<T>(\n method: 'GET' | 'POST' | 'DELETE' | 'PUT',\n path: string,\n body?: unknown,\n ): Promise<T> {\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.bearer}`,\n accept: 'application/json',\n }\n if (body !== undefined) headers['content-type'] = 'application/json'\n\n const res = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n const text = await res.text()\n let parsed: PlatformEnvelope<T> | null = null\n if (text) {\n try {\n parsed = JSON.parse(text)\n } catch {\n // fall through to error handling below\n }\n }\n if (!res.ok || (parsed && parsed.success === false)) {\n const code = parsed?.error && typeof parsed.error === 'object' ? parsed.error.code : undefined\n const message =\n (parsed?.error && typeof parsed.error === 'object' && parsed.error.message) ||\n (typeof parsed?.error === 'string' ? parsed.error : `Platform hub error (${res.status})`)\n throw new PlatformHubError(message, res.status, code, parsed ?? text)\n }\n if (!parsed) {\n throw new PlatformHubError(\n `Platform hub returned non-JSON success (${res.status})`,\n res.status,\n undefined,\n text,\n )\n }\n if (parsed.data === undefined) {\n throw new PlatformHubError(\n 'Platform hub envelope missing `data`',\n res.status,\n undefined,\n parsed,\n )\n }\n return parsed.data\n }\n}\n"],"mappings":";;AAoIA,IAAa,mBAAb,cAAsC,MAAM;CAGxB;CACA;CACA;CAJlB,Y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uBAAuB,IAAI,OAAO,KACpD,IAAI,QAAQ,MAAM,UAAU,IAAI;EACtE;EACA,IAAI,CAAC,QACH,MAAM,IAAI,iBACR,2CAA2C,IAAI,OAAO,IACtD,IAAI,QACJ,KAAA,GACA,IACF;EAEF,IAAI,OAAO,SAAS,KAAA,GAClB,MAAM,IAAI,iBACR,wCACA,IAAI,QACJ,KAAA,GACA,MACF;EAEF,OAAO,OAAO;CAChB;AACF"}
@@ -1,80 +0,0 @@
1
- //#region src/mcp/kb-gate.d.ts
2
- /**
3
- *
4
- * `createKbGate` — the valid-only knowledge-base growth gate, distilled from
5
- * physim's KB-research subsystem. A research-in-a-loop delegate (or any KB
6
- * writer) runs candidate facts through this before persisting, so the KB grows
7
- * with ONLY grounded facts — hallucinated, unsourced, or laundered claims are
8
- * vetoed at the gate.
9
- *
10
- * Fail-closed by construction: every judge must `accept`; the FIRST veto wins
11
- * and the fact is rejected. The non-negotiable floor (always on, can't be
12
- * disabled) is the **passage-present guard** — a fact's `verbatimPassage` MUST
13
- * literally appear in its `sourceText`. That single check kills the dominant
14
- * failure mode (a confident claim decoupled from any real source).
15
- *
16
- * Pure + dependency-free: it operates on fact candidates, not on a store, so it
17
- * composes with `@tangle-network/agent-knowledge` or any persistence layer
18
- * without importing it. The remediation policy (correct-on-veto vs
19
- * escalate-as-unverified) is the caller's — this returns the verdict; it never
20
- * drops a fact silently.
21
- *
22
- * @experimental
23
- */
24
- /** @experimental A fact proposed for the KB, with its grounding. */
25
- interface FactCandidate {
26
- /** The atomic claim text. */
27
- claim: string;
28
- /** Optional extracted value (number or string) the claim asserts. */
29
- value?: string | number;
30
- /** Verbatim span lifted from the source that backs the claim. */
31
- verbatimPassage: string;
32
- /** The raw source text the passage must be grounded in. */
33
- sourceText: string;
34
- /** Where the fact claims to come from — checked for circular/self citations. */
35
- citation?: string;
36
- }
37
- /** @experimental */
38
- interface FactJudgeVerdict {
39
- accept: boolean;
40
- reason?: string;
41
- }
42
- /** @experimental A pluggable fact validator. Throw is NOT allowed — return a
43
- * verdict; a thrown judge is a programmer error, not a veto. */
44
- interface FactJudge {
45
- name: string;
46
- judge(candidate: FactCandidate): FactJudgeVerdict | Promise<FactJudgeVerdict>;
47
- }
48
- /** @experimental */
49
- interface KbGateResult {
50
- accepted: boolean;
51
- /** Name of the judge that vetoed; undefined when accepted. */
52
- vetoedBy?: string;
53
- reason?: string;
54
- }
55
- /** @experimental */
56
- interface CreateKbGateOptions {
57
- /** Extra judges appended after the built-in floor (e.g. an LLM judge). */
58
- judges?: FactJudge[];
59
- /** Minimum verbatim-passage length. Default 12 — kills empty/stub passages. */
60
- minPassageChars?: number;
61
- /**
62
- * Citation tokens that denote a SELF-generated artifact (e.g. `'spec'`,
63
- * `'cad_params'`, `'requirements'`). A citation naming one is circular
64
- * (laundering) — the fact cites a derived artifact, not a real source.
65
- * Default `[]` (no circular check unless the consumer declares its kinds).
66
- */
67
- selfArtifactKinds?: string[];
68
- }
69
- /**
70
- *
71
- * Build a fail-closed KB gate. The returned function runs the built-in floor
72
- * (passage-non-empty → passage-present → value-in-passage → no-circular-citation)
73
- * then any consumer judges, returning on the first veto.
74
- *
75
- * @experimental
76
- */
77
- declare function createKbGate(options?: CreateKbGateOptions): (candidate: FactCandidate) => Promise<KbGateResult>;
78
- //#endregion
79
- export { KbGateResult as a, FactJudgeVerdict as i, FactCandidate as n, createKbGate as o, FactJudge as r, CreateKbGateOptions as t };
80
- //# sourceMappingURL=kb-gate-C8z2juK8.d.ts.map
@@ -1,80 +0,0 @@
1
- //#region src/mcp/kb-gate.ts
2
- const norm = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
3
- /** Does `value` appear in the (normalized) passage — literally, comma-grouped,
4
- * or in billion/million shorthand (the forms a source actually writes). */
5
- function valueAppears(value, passageNorm) {
6
- if (passageNorm.includes(norm(String(value)))) return true;
7
- if (typeof value !== "number" || !Number.isFinite(value)) return false;
8
- const forms = [value.toLocaleString("en-US")];
9
- if (Math.abs(value) >= 1e9) forms.push(`${trimZero(value / 1e9)} billion`);
10
- if (Math.abs(value) >= 1e6) forms.push(`${trimZero(value / 1e6)} million`);
11
- return forms.some((f) => passageNorm.includes(norm(f)));
12
- }
13
- function trimZero(n) {
14
- return Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)));
15
- }
16
- /** The always-on floor judges. Order matters: cheapest / most-fundamental first. */
17
- function builtinJudges(minPassageChars, selfArtifactKinds) {
18
- const kinds = selfArtifactKinds.map((k) => k.toLowerCase());
19
- return [
20
- {
21
- name: "passage-non-empty",
22
- judge: (c) => c.verbatimPassage.trim().length >= minPassageChars ? { accept: true } : {
23
- accept: false,
24
- reason: `passage shorter than ${minPassageChars} chars`
25
- }
26
- },
27
- {
28
- name: "passage-present",
29
- judge: (c) => norm(c.sourceText).includes(norm(c.verbatimPassage)) ? { accept: true } : {
30
- accept: false,
31
- reason: "verbatim passage not found in source (unbacked fact)"
32
- }
33
- },
34
- {
35
- name: "value-in-passage",
36
- judge: (c) => c.value === void 0 || valueAppears(c.value, norm(c.verbatimPassage)) ? { accept: true } : {
37
- accept: false,
38
- reason: `value ${JSON.stringify(c.value)} not present in passage`
39
- }
40
- },
41
- {
42
- name: "no-circular-citation",
43
- judge: (c) => {
44
- if (!c.citation || kinds.length === 0) return { accept: true };
45
- const cite = c.citation.toLowerCase();
46
- const hit = kinds.find((k) => cite.includes(k));
47
- return hit ? {
48
- accept: false,
49
- reason: `circular citation to self-generated artifact "${hit}"`
50
- } : { accept: true };
51
- }
52
- }
53
- ];
54
- }
55
- /**
56
- *
57
- * Build a fail-closed KB gate. The returned function runs the built-in floor
58
- * (passage-non-empty → passage-present → value-in-passage → no-circular-citation)
59
- * then any consumer judges, returning on the first veto.
60
- *
61
- * @experimental
62
- */
63
- function createKbGate(options = {}) {
64
- const judges = [...builtinJudges(options.minPassageChars ?? 12, options.selfArtifactKinds ?? []), ...options.judges ?? []];
65
- return async (candidate) => {
66
- for (const j of judges) {
67
- const verdict = await j.judge(candidate);
68
- if (!verdict.accept) return {
69
- accepted: false,
70
- vetoedBy: j.name,
71
- reason: verdict.reason
72
- };
73
- }
74
- return { accepted: true };
75
- };
76
- }
77
- //#endregion
78
- export { createKbGate as t };
79
-
80
- //# sourceMappingURL=kb-gate-DpaSwXVx.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"kb-gate-DpaSwXVx.js","names":[],"sources":["../src/mcp/kb-gate.ts"],"sourcesContent":["/**\n *\n * `createKbGate` — the valid-only knowledge-base growth gate, distilled from\n * physim's KB-research subsystem. A research-in-a-loop delegate (or any KB\n * writer) runs candidate facts through this before persisting, so the KB grows\n * with ONLY grounded facts — hallucinated, unsourced, or laundered claims are\n * vetoed at the gate.\n *\n * Fail-closed by construction: every judge must `accept`; the FIRST veto wins\n * and the fact is rejected. The non-negotiable floor (always on, can't be\n * disabled) is the **passage-present guard** — a fact's `verbatimPassage` MUST\n * literally appear in its `sourceText`. That single check kills the dominant\n * failure mode (a confident claim decoupled from any real source).\n *\n * Pure + dependency-free: it operates on fact candidates, not on a store, so it\n * composes with `@tangle-network/agent-knowledge` or any persistence layer\n * without importing it. The remediation policy (correct-on-veto vs\n * escalate-as-unverified) is the caller's — this returns the verdict; it never\n * drops a fact silently.\n *\n * @experimental\n */\n\n/** @experimental A fact proposed for the KB, with its grounding. */\nexport interface FactCandidate {\n /** The atomic claim text. */\n claim: string\n /** Optional extracted value (number or string) the claim asserts. */\n value?: string | number\n /** Verbatim span lifted from the source that backs the claim. */\n verbatimPassage: string\n /** The raw source text the passage must be grounded in. */\n sourceText: string\n /** Where the fact claims to come from — checked for circular/self citations. */\n citation?: string\n}\n\n/** @experimental */\nexport interface FactJudgeVerdict {\n accept: boolean\n reason?: string\n}\n\n/** @experimental A pluggable fact validator. Throw is NOT allowed — return a\n * verdict; a thrown judge is a programmer error, not a veto. */\nexport interface FactJudge {\n name: string\n judge(candidate: FactCandidate): FactJudgeVerdict | Promise<FactJudgeVerdict>\n}\n\n/** @experimental */\nexport interface KbGateResult {\n accepted: boolean\n /** Name of the judge that vetoed; undefined when accepted. */\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface CreateKbGateOptions {\n /** Extra judges appended after the built-in floor (e.g. an LLM judge). */\n judges?: FactJudge[]\n /** Minimum verbatim-passage length. Default 12 — kills empty/stub passages. */\n minPassageChars?: number\n /**\n * Citation tokens that denote a SELF-generated artifact (e.g. `'spec'`,\n * `'cad_params'`, `'requirements'`). A citation naming one is circular\n * (laundering) — the fact cites a derived artifact, not a real source.\n * Default `[]` (no circular check unless the consumer declares its kinds).\n */\n selfArtifactKinds?: string[]\n}\n\nconst norm = (s: string): string => s.toLowerCase().replace(/\\s+/g, ' ').trim()\n\n/** Does `value` appear in the (normalized) passage — literally, comma-grouped,\n * or in billion/million shorthand (the forms a source actually writes). */\nfunction valueAppears(value: string | number, passageNorm: string): boolean {\n if (passageNorm.includes(norm(String(value)))) return true\n if (typeof value !== 'number' || !Number.isFinite(value)) return false\n const forms = [value.toLocaleString('en-US')]\n if (Math.abs(value) >= 1e9) forms.push(`${trimZero(value / 1e9)} billion`)\n if (Math.abs(value) >= 1e6) forms.push(`${trimZero(value / 1e6)} million`)\n return forms.some((f) => passageNorm.includes(norm(f)))\n}\n\nfunction trimZero(n: number): string {\n return Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)))\n}\n\n/** The always-on floor judges. Order matters: cheapest / most-fundamental first. */\nfunction builtinJudges(minPassageChars: number, selfArtifactKinds: string[]): FactJudge[] {\n const kinds = selfArtifactKinds.map((k) => k.toLowerCase())\n return [\n {\n name: 'passage-non-empty',\n judge: (c) =>\n c.verbatimPassage.trim().length >= minPassageChars\n ? { accept: true }\n : { accept: false, reason: `passage shorter than ${minPassageChars} chars` },\n },\n {\n // THE anti-hallucination floor — the passage must literally be in the source.\n name: 'passage-present',\n judge: (c) =>\n norm(c.sourceText).includes(norm(c.verbatimPassage))\n ? { accept: true }\n : { accept: false, reason: 'verbatim passage not found in source (unbacked fact)' },\n },\n {\n name: 'value-in-passage',\n judge: (c) =>\n c.value === undefined || valueAppears(c.value, norm(c.verbatimPassage))\n ? { accept: true }\n : { accept: false, reason: `value ${JSON.stringify(c.value)} not present in passage` },\n },\n {\n name: 'no-circular-citation',\n judge: (c) => {\n if (!c.citation || kinds.length === 0) return { accept: true }\n const cite = c.citation.toLowerCase()\n const hit = kinds.find((k) => cite.includes(k))\n return hit\n ? { accept: false, reason: `circular citation to self-generated artifact \"${hit}\"` }\n : { accept: true }\n },\n },\n ]\n}\n\n/**\n *\n * Build a fail-closed KB gate. The returned function runs the built-in floor\n * (passage-non-empty → passage-present → value-in-passage → no-circular-citation)\n * then any consumer judges, returning on the first veto.\n *\n * @experimental\n */\nexport function createKbGate(\n options: CreateKbGateOptions = {},\n): (candidate: FactCandidate) => Promise<KbGateResult> {\n const judges = [\n ...builtinJudges(options.minPassageChars ?? 12, options.selfArtifactKinds ?? []),\n ...(options.judges ?? []),\n ]\n return async (candidate) => {\n for (const j of judges) {\n const verdict = await j.judge(candidate)\n if (!verdict.accept) {\n return { accepted: false, vetoedBy: j.name, reason: verdict.reason }\n }\n }\n return { accepted: true }\n }\n}\n"],"mappings":";AAyEA,MAAM,QAAQ,MAAsB,EAAE,YAAY,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;;;AAI9E,SAAS,aAAa,OAAwB,aAA8B;CAC1E,IAAI,YAAY,SAAS,KAAK,OAAO,KAAK,CAAC,CAAC,GAAG,OAAO;CACtD,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CACjE,MAAM,QAAQ,CAAC,MAAM,eAAe,OAAO,CAAC;CAC5C,IAAI,KAAK,IAAI,KAAK,KAAK,KAAK,MAAM,KAAK,GAAG,SAAS,QAAQ,GAAG,EAAE,SAAS;CACzE,IAAI,KAAK,IAAI,KAAK,KAAK,KAAK,MAAM,KAAK,GAAG,SAAS,QAAQ,GAAG,EAAE,SAAS;CACzE,OAAO,MAAM,MA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