@hop-top/kit 0.4.0-alpha.1

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 (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/routellm.ts
21
+ var routellm_exports = {};
22
+ __export(routellm_exports, {
23
+ RouteLLMAdapter: () => RouteLLMAdapter,
24
+ parseModelField: () => parseModelField,
25
+ parseRouterConfig: () => parseRouterConfig
26
+ });
27
+ module.exports = __toCommonJS(routellm_exports);
28
+
29
+ // src/llm.ts
30
+ var LLMError = class extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "LLMError";
34
+ Object.setPrototypeOf(this, new.target.prototype);
35
+ }
36
+ };
37
+ var registry = /* @__PURE__ */ new Map();
38
+ function register(scheme, factory) {
39
+ if (registry.has(scheme)) {
40
+ throw new LLMError(`provider already registered for scheme: ${scheme}`);
41
+ }
42
+ registry.set(scheme, factory);
43
+ }
44
+
45
+ // src/routellm.ts
46
+ function defaultRouterConfig() {
47
+ return {
48
+ baseUrl: "http://localhost:6060",
49
+ grpcPort: 6061,
50
+ strongModel: "",
51
+ weakModel: "",
52
+ routers: [],
53
+ routerConfig: {},
54
+ eva: { contracts: [], enforce: false },
55
+ autostart: false
56
+ };
57
+ }
58
+ function parseRouterConfig(extras) {
59
+ const cfg = defaultRouterConfig();
60
+ if (extras) {
61
+ const raw = extras["routellm"];
62
+ if (raw !== void 0) {
63
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
64
+ throw new LLMError(
65
+ `routellm: expected map, got ${typeof raw}`
66
+ );
67
+ }
68
+ const sub = raw;
69
+ if (typeof sub["base_url"] === "string") cfg.baseUrl = sub["base_url"];
70
+ if (typeof sub["grpc_port"] === "number") cfg.grpcPort = sub["grpc_port"];
71
+ if (typeof sub["strong_model"] === "string") {
72
+ cfg.strongModel = sub["strong_model"];
73
+ }
74
+ if (typeof sub["weak_model"] === "string") {
75
+ cfg.weakModel = sub["weak_model"];
76
+ }
77
+ if (Array.isArray(sub["routers"])) {
78
+ cfg.routers = sub["routers"].filter(
79
+ (r) => typeof r === "string"
80
+ );
81
+ }
82
+ if (typeof sub["router_config"] === "object" && sub["router_config"] !== null && !Array.isArray(sub["router_config"])) {
83
+ cfg.routerConfig = sub["router_config"];
84
+ }
85
+ if (typeof sub["eva"] === "object" && sub["eva"] !== null) {
86
+ const e = sub["eva"];
87
+ if (Array.isArray(e["contracts"])) {
88
+ cfg.eva.contracts = e["contracts"].filter(
89
+ (c) => typeof c === "string"
90
+ );
91
+ }
92
+ if (typeof e["enforce"] === "boolean") cfg.eva.enforce = e["enforce"];
93
+ }
94
+ if (typeof sub["autostart"] === "boolean") {
95
+ cfg.autostart = sub["autostart"];
96
+ }
97
+ }
98
+ }
99
+ const envBaseUrl = process.env["ROUTELLM_BASE_URL"];
100
+ if (envBaseUrl) cfg.baseUrl = envBaseUrl;
101
+ const envStrong = process.env["ROUTELLM_STRONG_MODEL"];
102
+ if (envStrong) cfg.strongModel = envStrong;
103
+ const envWeak = process.env["ROUTELLM_WEAK_MODEL"];
104
+ if (envWeak) cfg.weakModel = envWeak;
105
+ const envRouters = process.env["ROUTELLM_ROUTERS"];
106
+ if (envRouters) {
107
+ cfg.routers = envRouters.split(",").map((r) => r.trim()).filter(Boolean);
108
+ }
109
+ return cfg;
110
+ }
111
+ function parseModelField(model) {
112
+ if (!model) {
113
+ throw new LLMError(
114
+ "model field is required (format: router_name:threshold)"
115
+ );
116
+ }
117
+ const idx = model.indexOf(":");
118
+ if (idx < 0) {
119
+ throw new LLMError(
120
+ `invalid model "${model}": expected format router_name:threshold (e.g. mf:0.7)`
121
+ );
122
+ }
123
+ const routerName = model.slice(0, idx);
124
+ const rawThreshold = model.slice(idx + 1);
125
+ if (!routerName || !rawThreshold) {
126
+ throw new LLMError(
127
+ `invalid model "${model}": expected format router_name:threshold (e.g. mf:0.7)`
128
+ );
129
+ }
130
+ const threshold = Number(rawThreshold);
131
+ if (Number.isNaN(threshold)) {
132
+ throw new LLMError(`invalid threshold "${rawThreshold}": not a number`);
133
+ }
134
+ return { routerName, threshold };
135
+ }
136
+ var RouteLLMAdapter = class {
137
+ constructor(cfg) {
138
+ this.config = parseRouterConfig(cfg.provider.extras);
139
+ const model = cfg.provider.model || cfg.uri.model;
140
+ const parsed = parseModelField(model);
141
+ this.routerName = parsed.routerName;
142
+ this.threshold = parsed.threshold;
143
+ if (this.threshold < 0 || this.threshold > 1) {
144
+ throw new LLMError(
145
+ `routellm: threshold ${this.threshold} out of range [0, 1]`
146
+ );
147
+ }
148
+ this._serverModel = `router-${this.routerName}-${this.threshold}`;
149
+ let baseUrl = this.config.baseUrl;
150
+ if (baseUrl === "http://localhost:6060" && cfg.provider.baseURL) {
151
+ baseUrl = cfg.provider.baseURL;
152
+ }
153
+ this._baseUrl = baseUrl;
154
+ this._apiKey = cfg.provider.apiKey ?? "";
155
+ }
156
+ async complete(req) {
157
+ const body = this._buildBody(req, false);
158
+ const resp = await this._post("/v1/chat/completions", body);
159
+ const data = await resp.json();
160
+ const choice = data.choices?.[0];
161
+ const content = choice?.message?.content ?? "";
162
+ const finishReason = choice?.finish_reason ?? "";
163
+ const usage = data.usage ? {
164
+ promptTokens: data.usage.prompt_tokens ?? 0,
165
+ completionTokens: data.usage.completion_tokens ?? 0,
166
+ totalTokens: data.usage.total_tokens ?? 0
167
+ } : void 0;
168
+ return { content, role: "assistant", usage, finishReason };
169
+ }
170
+ async *stream(req) {
171
+ const body = this._buildBody(req, true);
172
+ const resp = await this._post("/v1/chat/completions", body);
173
+ if (!resp.body) {
174
+ throw new LLMError("routellm: streaming response has no body");
175
+ }
176
+ const reader = resp.body.getReader();
177
+ const decoder = new TextDecoder();
178
+ let buf = "";
179
+ try {
180
+ for (; ; ) {
181
+ const { done, value } = await reader.read();
182
+ if (done) break;
183
+ buf += decoder.decode(value, { stream: true });
184
+ const lines = buf.split("\n");
185
+ buf = lines.pop() ?? "";
186
+ for (const line of lines) {
187
+ const trimmed = line.trim();
188
+ if (!trimmed || !trimmed.startsWith("data: ")) continue;
189
+ const payload = trimmed.slice(6);
190
+ if (payload === "[DONE]") {
191
+ yield { content: "", done: true };
192
+ return;
193
+ }
194
+ const chunk = JSON.parse(payload);
195
+ const delta = chunk.choices?.[0]?.delta;
196
+ const content = delta?.content ?? "";
197
+ const isDone = chunk.choices?.[0]?.finish_reason != null;
198
+ yield { content, done: isDone };
199
+ }
200
+ }
201
+ } finally {
202
+ reader.releaseLock();
203
+ }
204
+ }
205
+ close() {
206
+ }
207
+ // ── private ────────────────────────────────────────────────────
208
+ _buildBody(req, stream) {
209
+ const body = {
210
+ model: this._serverModel,
211
+ messages: req.messages.map((m) => ({
212
+ role: m.role,
213
+ content: m.content
214
+ })),
215
+ stream
216
+ };
217
+ if (req.temperature !== void 0) body["temperature"] = req.temperature;
218
+ if (req.maxTokens !== void 0) body["max_tokens"] = req.maxTokens;
219
+ if (req.stopSequences?.length) body["stop"] = req.stopSequences;
220
+ return body;
221
+ }
222
+ async _post(path, body) {
223
+ const url = `${this._baseUrl}${path}`;
224
+ const headers = {
225
+ "Content-Type": "application/json"
226
+ };
227
+ if (this._apiKey) {
228
+ headers["Authorization"] = `Bearer ${this._apiKey}`;
229
+ }
230
+ const resp = await fetch(url, {
231
+ method: "POST",
232
+ headers,
233
+ body: JSON.stringify(body)
234
+ });
235
+ if (!resp.ok) {
236
+ const text = await resp.text().catch(() => "");
237
+ throw new LLMError(
238
+ `routellm: HTTP ${resp.status} from ${url}: ${text}`
239
+ );
240
+ }
241
+ return resp;
242
+ }
243
+ };
244
+ function routellmFactory(cfg) {
245
+ const adapter = new RouteLLMAdapter(cfg);
246
+ return {
247
+ complete: (req) => adapter.complete(req),
248
+ stream: (req) => adapter.stream(req),
249
+ close: () => adapter.close()
250
+ };
251
+ }
252
+ register("routellm", routellmFactory);
253
+ // Annotate the CommonJS export names for ESM import in node:
254
+ 0 && (module.exports = {
255
+ RouteLLMAdapter,
256
+ parseModelField,
257
+ parseRouterConfig
258
+ });
package/dist/rpc.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { Entity, Query } from './api.js';
2
+
3
+ /**
4
+ * Typed ConnectRPC client for kit EntityService.
5
+ *
6
+ * Thin wrapper over generated Connect stubs, mapping between
7
+ * JS objects and protobuf Struct (JSON intermediate).
8
+ */
9
+
10
+ interface RPCClientOptions {
11
+ baseURL: string;
12
+ auth?: string;
13
+ }
14
+ declare class RPCClient<T extends Entity> {
15
+ private client;
16
+ private auth?;
17
+ constructor(opts: RPCClientOptions);
18
+ create(entity: Omit<T, "id"> | T): Promise<T>;
19
+ get(id: string): Promise<T>;
20
+ list(q?: Query): Promise<T[]>;
21
+ update(entity: T): Promise<T>;
22
+ delete(id: string): Promise<void>;
23
+ }
24
+
25
+ export { RPCClient, type RPCClientOptions };
package/dist/rpc.js ADDED
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/rpc.ts
21
+ var rpc_exports = {};
22
+ __export(rpc_exports, {
23
+ RPCClient: () => RPCClient
24
+ });
25
+ module.exports = __toCommonJS(rpc_exports);
26
+ var import_connect = require("@connectrpc/connect");
27
+ var import_connect_web = require("@connectrpc/connect-web");
28
+ var import_protobuf = require("@bufbuild/protobuf");
29
+
30
+ // src/gen/crud_pb.ts
31
+ var import_codegenv2 = require("@bufbuild/protobuf/codegenv2");
32
+ var import_wkt = require("@bufbuild/protobuf/wkt");
33
+ var file_crud = /* @__PURE__ */ (0, import_codegenv2.fileDesc)("CgpjcnVkLnByb3RvEgdjcnVkLnYxIjgKDUNyZWF0ZVJlcXVlc3QSJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCI5Cg5DcmVhdGVSZXNwb25zZRInCgZlbnRpdHkYASABKAsyFy5nb29nbGUucHJvdG9idWYuU3RydWN0IhgKCkdldFJlcXVlc3QSCgoCaWQYASABKAkiNgoLR2V0UmVzcG9uc2USJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCJKCgtMaXN0UmVxdWVzdBINCgVsaW1pdBgBIAEoBRIOCgZvZmZzZXQYAiABKAUSDAoEc29ydBgDIAEoCRIOCgZzZWFyY2gYBCABKAkiOQoMTGlzdFJlc3BvbnNlEikKCGVudGl0aWVzGAEgAygLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCI4Cg1VcGRhdGVSZXF1ZXN0EicKBmVudGl0eRgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QiOQoOVXBkYXRlUmVzcG9uc2USJwoGZW50aXR5GAEgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdCIbCg1EZWxldGVSZXF1ZXN0EgoKAmlkGAEgASgJIhAKDkRlbGV0ZVJlc3BvbnNlMqcCCg1FbnRpdHlTZXJ2aWNlEjkKBkNyZWF0ZRIWLmNydWQudjEuQ3JlYXRlUmVxdWVzdBoXLmNydWQudjEuQ3JlYXRlUmVzcG9uc2USMAoDR2V0EhMuY3J1ZC52MS5HZXRSZXF1ZXN0GhQuY3J1ZC52MS5HZXRSZXNwb25zZRIzCgRMaXN0EhQuY3J1ZC52MS5MaXN0UmVxdWVzdBoVLmNydWQudjEuTGlzdFJlc3BvbnNlEjkKBlVwZGF0ZRIWLmNydWQudjEuVXBkYXRlUmVxdWVzdBoXLmNydWQudjEuVXBkYXRlUmVzcG9uc2USOQoGRGVsZXRlEhYuY3J1ZC52MS5EZWxldGVSZXF1ZXN0GhcuY3J1ZC52MS5EZWxldGVSZXNwb25zZUJ3Cgtjb20uY3J1ZC52MUIJQ3J1ZFByb3RvUAFaIGhvcC50b3Ava2l0L3Byb3RvL2NydWQvdjE7Y3J1ZHYxogIDQ1hYqgIHQ3J1ZC5WMcoCB0NydWRcVjHiAhNDcnVkXFYxXEdQQk1ldGFkYXRh6gIIQ3J1ZDo6VjFiBnByb3RvMw", [import_wkt.file_google_protobuf_struct]);
34
+ var CreateRequestSchema = /* @__PURE__ */ (0, import_codegenv2.messageDesc)(file_crud, 0);
35
+ var GetRequestSchema = /* @__PURE__ */ (0, import_codegenv2.messageDesc)(file_crud, 2);
36
+ var ListRequestSchema = /* @__PURE__ */ (0, import_codegenv2.messageDesc)(file_crud, 4);
37
+ var UpdateRequestSchema = /* @__PURE__ */ (0, import_codegenv2.messageDesc)(file_crud, 6);
38
+ var DeleteRequestSchema = /* @__PURE__ */ (0, import_codegenv2.messageDesc)(file_crud, 8);
39
+ var EntityService = /* @__PURE__ */ (0, import_codegenv2.serviceDesc)(file_crud, 0);
40
+
41
+ // src/rpc.ts
42
+ var RPCClient = class {
43
+ constructor(opts) {
44
+ this.auth = opts.auth;
45
+ const transport = (0, import_connect_web.createConnectTransport)({
46
+ baseUrl: opts.baseURL,
47
+ interceptors: this.auth ? [
48
+ (next) => async (req) => {
49
+ req.header.set(
50
+ "Authorization",
51
+ `Bearer ${this.auth}`
52
+ );
53
+ return next(req);
54
+ }
55
+ ] : []
56
+ });
57
+ this.client = (0, import_connect.createClient)(EntityService, transport);
58
+ }
59
+ async create(entity) {
60
+ const res = await this.client.create(
61
+ (0, import_protobuf.create)(CreateRequestSchema, {
62
+ entity
63
+ })
64
+ );
65
+ return res.entity ?? {};
66
+ }
67
+ async get(id) {
68
+ const res = await this.client.get(
69
+ (0, import_protobuf.create)(GetRequestSchema, { id })
70
+ );
71
+ return res.entity ?? {};
72
+ }
73
+ async list(q) {
74
+ const res = await this.client.list(
75
+ (0, import_protobuf.create)(ListRequestSchema, {
76
+ limit: q?.limit ?? 0,
77
+ offset: q?.offset ?? 0,
78
+ sort: q?.sort ?? "",
79
+ search: q?.search ?? ""
80
+ })
81
+ );
82
+ return res.entities ?? [];
83
+ }
84
+ async update(entity) {
85
+ const res = await this.client.update(
86
+ (0, import_protobuf.create)(UpdateRequestSchema, {
87
+ entity
88
+ })
89
+ );
90
+ return res.entity ?? {};
91
+ }
92
+ async delete(id) {
93
+ await this.client.delete(
94
+ (0, import_protobuf.create)(DeleteRequestSchema, { id })
95
+ );
96
+ }
97
+ };
98
+ // Annotate the CommonJS export names for ESM import in node:
99
+ 0 && (module.exports = {
100
+ RPCClient
101
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @module safety
3
+ * @package @hop-top/kit
4
+ *
5
+ * Factor 10 — Delegation Safety.
6
+ *
7
+ * Guards destructive operations behind --force, with stricter
8
+ * requirements in non-TTY (scripted/agent) contexts.
9
+ */
10
+ type SafetyLevel = 'read' | 'caution' | 'dangerous';
11
+ /**
12
+ * Validates that the current context permits the requested safety level.
13
+ *
14
+ * - `read`: always passes
15
+ * - `caution`: passes in TTY; requires `--force` in non-TTY
16
+ * - `dangerous`: always requires `--force`
17
+ *
18
+ * @throws {Error} when guard fails, with message referencing --force
19
+ */
20
+ declare function safetyGuard(level: SafetyLevel, opts?: {
21
+ force?: boolean;
22
+ }): void;
23
+
24
+ export { type SafetyLevel, safetyGuard };
package/dist/safety.js ADDED
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/safety.ts
21
+ var safety_exports = {};
22
+ __export(safety_exports, {
23
+ safetyGuard: () => safetyGuard
24
+ });
25
+ module.exports = __toCommonJS(safety_exports);
26
+ function safetyGuard(level, opts) {
27
+ if (level === "read") return;
28
+ const force = opts?.force ?? false;
29
+ const isTTY = !!process.stdout.isTTY;
30
+ if (level === "dangerous" && !force) {
31
+ throw new Error(
32
+ "dangerous operation requires --force"
33
+ );
34
+ }
35
+ if (level === "caution" && !isTTY && !force) {
36
+ throw new Error(
37
+ "caution-level operation in non-TTY requires --force"
38
+ );
39
+ }
40
+ }
41
+ // Annotate the CommonJS export names for ESM import in node:
42
+ 0 && (module.exports = {
43
+ safetyGuard
44
+ });
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Filesystem path policy guardrails — TypeScript port of `hop.top/kit/go/core/scope`.
5
+ *
6
+ * Mirrors the Go API surface (`New`, `Default`, `Allow`, `Deny`, `Check`,
7
+ * `Enforce`, `SetMode`, `SetDefault`, `Snapshot`, `SecretPaths`). The default
8
+ * deny list is loaded from `contracts/parity/scope-defaults.json` (the
9
+ * cross-language source of truth).
10
+ *
11
+ * Glob matching uses [`picomatch`](https://github.com/micromatch/picomatch)
12
+ * which supports the subset of bash-style globs (including `**`) that the Go
13
+ * port relies on via `bmatcuk/doublestar/v4`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { Default, Op, Strict } from '@hop-top/kit/scope';
18
+ *
19
+ * const dec = Default().check('/Users/me/.ssh/id_rsa', Op.Read);
20
+ * // -> Decision.Denied
21
+ * ```
22
+ */
23
+ /** Mode controls how `Enforce` reacts to a `Denied` decision. */
24
+ declare enum Mode {
25
+ /** Strict denies → throws `ErrDenied`. The default. */
26
+ Strict = "strict",
27
+ /** Warn denies → logs to stderr and returns. */
28
+ Warn = "warn",
29
+ /** Prompt denies → invokes the prompt callback. */
30
+ Prompt = "prompt"
31
+ }
32
+ /** Op is a bitset of filesystem operations. */
33
+ declare enum Op {
34
+ Read = 1,
35
+ Write = 2,
36
+ Exec = 4
37
+ }
38
+ /** Decision is the outcome of `Check`. */
39
+ declare enum Decision {
40
+ Unknown = "unknown",
41
+ Allowed = "allowed",
42
+ Denied = "denied"
43
+ }
44
+ /** A single rule: glob patterns + ops bitset + allow/deny verdict. */
45
+ interface Rule {
46
+ patterns: string[];
47
+ ops: Op;
48
+ allow: boolean;
49
+ }
50
+ /** Prompt callback used in `Mode.Prompt`. Return `true` to allow this call. */
51
+ type PromptFunc = (path: string, op: Op) => boolean;
52
+ /** Error thrown by `Enforce` when a path is denied. */
53
+ declare class ErrDenied extends Error {
54
+ constructor(p: string, op: Op);
55
+ }
56
+ /**
57
+ * Policy holds an ordered list of rules, a Mode, and an optional prompt
58
+ * callback. Construct via `New()` or `Default()`.
59
+ */
60
+ declare class Policy {
61
+ private rules;
62
+ private mode;
63
+ private prompt?;
64
+ /** Register an allow rule covering Read|Write|Exec. */
65
+ allow(...patterns: string[]): this;
66
+ /** Register an allow rule for the given operations. */
67
+ allowOp(op: Op, ...patterns: string[]): this;
68
+ /** Register a deny rule covering Read|Write|Exec. */
69
+ deny(...patterns: string[]): this;
70
+ /** Register a deny rule for the given operations. */
71
+ denyOp(op: Op, ...patterns: string[]): this;
72
+ /** Set the enforcement mode. */
73
+ setMode(m: Mode): this;
74
+ /** Get the current enforcement mode. */
75
+ getMode(): Mode;
76
+ /** Set the prompt callback used in `Mode.Prompt`. */
77
+ setPromptFunc(fn: PromptFunc): this;
78
+ /** Defensive copy of the policy's rules in registration order. */
79
+ getRules(): Rule[];
80
+ /**
81
+ * Evaluate `(p, op)` against the policy. Pure — no prompt, no mutation.
82
+ * Resolves symlinks before matching to defeat symlink escapes; on ENOENT
83
+ * the cleaned path is used so "intent to write" still matches deny rules.
84
+ */
85
+ check(p: string, op: Op): Decision;
86
+ /**
87
+ * Enforce calls `check` and translates the decision according to mode:
88
+ * Strict + (Denied|Unknown) throws; Warn + Denied logs; Prompt + Denied
89
+ * invokes the prompt callback.
90
+ */
91
+ enforce(p: string, op: Op): void;
92
+ private handleDeny;
93
+ /** Deep copy. Useful for per-test isolation paired with `setDefault`. */
94
+ snapshot(): Policy;
95
+ }
96
+ /** Create an empty `Policy` in `Mode.Strict`. */
97
+ declare function New(): Policy;
98
+ /**
99
+ * Returns the package-level singleton policy used by primitives that don't
100
+ * accept an explicit policy. Lazy-initialised on first call. The singleton is
101
+ * pre-seeded with `SecretPaths()` as a deny-all-ops rule.
102
+ */
103
+ declare function Default(): Policy;
104
+ /**
105
+ * Swap the package-level singleton with `p`. Returns a restore function that
106
+ * puts the previous policy back. Intended for tests:
107
+ *
108
+ * ```ts
109
+ * const restore = setDefault(New().allow('~/tmp/**'));
110
+ * try { ... } finally { restore(); }
111
+ * ```
112
+ */
113
+ declare function setDefault(p: Policy): () => void;
114
+ /**
115
+ * Returns the default deny pattern set: common patterns plus the patterns
116
+ * specific to the current platform. Patterns are ready to feed into
117
+ * `Policy.deny`. `~` and Windows env macros are resolved at match time.
118
+ */
119
+ declare function SecretPaths(): string[];
120
+
121
+ export { Decision, Default, ErrDenied, Mode, New, Op, Policy, type PromptFunc, type Rule, SecretPaths, setDefault };