@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,232 @@
1
+ /**
2
+ * SWRankingRouter — Similarity-Weighted ranking router.
3
+ *
4
+ * Uses OpenAI embeddings to find similar arena battles, computes
5
+ * weighted Elo ratings, and derives the strong-model win rate.
6
+ *
7
+ * Port of Python's SWRankingRouter from routellm/routers/routers.py.
8
+ */
9
+
10
+ import type { Router } from "./router";
11
+
12
+ // ─── Types ───────────────────────────────────────────────────────────────────
13
+
14
+ /** A single arena battle record. */
15
+ export interface ArenaBattle {
16
+ modelA: string;
17
+ modelB: string;
18
+ /** "model_a" | "model_b" | "tie" */
19
+ winner: string;
20
+ }
21
+
22
+ /** Function that fetches an embedding vector for a prompt. */
23
+ export type EmbeddingFn = (prompt: string) => Promise<number[]>;
24
+
25
+ export interface SWRankingOptions {
26
+ /** Pre-loaded arena battles. */
27
+ battles: ArenaBattle[];
28
+ /** Pre-computed embeddings for each battle (same order). */
29
+ battleEmbeddings: number[][];
30
+ /** Function to get prompt embedding. */
31
+ embed: EmbeddingFn;
32
+ /** Strong model name for Elo lookup (default: "gpt-4-1106-preview"). */
33
+ strongModel?: string;
34
+ /** Weak model name for Elo lookup (default: "mixtral-8x7b-instruct-v0.1"). */
35
+ weakModel?: string;
36
+ /** Number of Elo tiers (default: 10). */
37
+ numTiers?: number;
38
+ }
39
+
40
+ // ─── Math helpers ────────────────────────────────────────────────────────────
41
+
42
+ /** Dot product of two vectors. Uses min length to avoid NaN on mismatch. */
43
+ export function dot(a: number[], b: number[]): number {
44
+ const len = Math.min(a.length, b.length);
45
+ let sum = 0;
46
+ for (let i = 0; i < len; i++) sum += a[i] * b[i];
47
+ return sum;
48
+ }
49
+
50
+ /** L2 norm of a vector. */
51
+ export function norm(v: number[]): number {
52
+ let sum = 0;
53
+ for (let i = 0; i < v.length; i++) sum += v[i] * v[i];
54
+ return Math.sqrt(sum);
55
+ }
56
+
57
+ /**
58
+ * Cosine similarity between each row of a matrix and a vector.
59
+ * Returns an array of similarities.
60
+ */
61
+ export function cosineSimilarities(
62
+ matrix: number[][],
63
+ vec: number[],
64
+ ): number[] {
65
+ const vecNorm = norm(vec);
66
+ if (vecNorm === 0) return new Array(matrix.length).fill(0);
67
+
68
+ return matrix.map((row) => {
69
+ const rowNorm = norm(row);
70
+ if (rowNorm === 0) return 0;
71
+ return dot(row, vec) / (rowNorm * vecNorm);
72
+ });
73
+ }
74
+
75
+ /**
76
+ * Compute similarity-based weightings (10 * 10^(sim / maxSim)).
77
+ */
78
+ export function getWeightings(similarities: number[]): number[] {
79
+ let maxSim = -Infinity;
80
+ for (const s of similarities) if (s > maxSim) maxSim = s;
81
+ if (maxSim <= 0) return similarities.map(() => 10);
82
+
83
+ return similarities.map((s) => 10 * Math.pow(10, s / maxSim));
84
+ }
85
+
86
+ // ─── Elo helpers ─────────────────────────────────────────────────────────────
87
+
88
+ /**
89
+ * Compute Elo ratings via MLE with ties (simplified).
90
+ *
91
+ * This is a simplified port of compute_elo_mle_with_tie — uses
92
+ * iterative gradient ascent on the Bradley-Terry model with ties.
93
+ *
94
+ * @param battles - Array of { modelA, modelB, winner }.
95
+ * @param weights - Optional per-battle weights.
96
+ * @param numIter - Iterations of gradient ascent.
97
+ * @returns Map from model name to Elo rating.
98
+ */
99
+ export function computeEloMle(
100
+ battles: ArenaBattle[],
101
+ weights?: number[],
102
+ numIter = 200,
103
+ ): Map<string, number> {
104
+ // Collect unique models.
105
+ const modelSet = new Set<string>();
106
+ for (const b of battles) {
107
+ modelSet.add(b.modelA);
108
+ modelSet.add(b.modelB);
109
+ }
110
+ const models = [...modelSet].sort();
111
+ const idx = new Map<string, number>();
112
+ models.forEach((m, i) => idx.set(m, i));
113
+
114
+ const n = models.length;
115
+ const ratings = new Float64Array(n).fill(1000);
116
+ const lr = 10;
117
+
118
+ for (let iter = 0; iter < numIter; iter++) {
119
+ const grad = new Float64Array(n);
120
+
121
+ for (let i = 0; i < battles.length; i++) {
122
+ const b = battles[i];
123
+ const w = weights ? weights[i] : 1;
124
+ const ia = idx.get(b.modelA)!;
125
+ const ib = idx.get(b.modelB)!;
126
+
127
+ const diff = (ratings[ib] - ratings[ia]) / 400;
128
+ const pA = 1 / (1 + Math.pow(10, diff));
129
+
130
+ let sA: number;
131
+ if (b.winner === "model_a") sA = 1;
132
+ else if (b.winner === "model_b") sA = 0;
133
+ else sA = 0.5; // tie
134
+
135
+ const delta = w * (sA - pA);
136
+ grad[ia] += delta;
137
+ grad[ib] -= delta;
138
+ }
139
+
140
+ for (let j = 0; j < n; j++) {
141
+ ratings[j] += lr * grad[j];
142
+ }
143
+ }
144
+
145
+ const result = new Map<string, number>();
146
+ models.forEach((m, i) => result.set(m, ratings[i]));
147
+ return result;
148
+ }
149
+
150
+ /**
151
+ * Assign models to tiers based on Elo ratings.
152
+ *
153
+ * Models are sorted by rating and bucketed into `numTiers` tiers.
154
+ * Returns a map from model name to tier index (0-based).
155
+ */
156
+ export function computeTiers(
157
+ ratings: Map<string, number>,
158
+ numTiers: number,
159
+ ): Map<string, number> {
160
+ const sorted = [...ratings.entries()].sort((a, b) => a[1] - b[1]);
161
+ const tierSize = Math.max(1, Math.ceil(sorted.length / numTiers));
162
+ const result = new Map<string, number>();
163
+ sorted.forEach(([model], i) => {
164
+ result.set(model, Math.floor(i / tierSize));
165
+ });
166
+ return result;
167
+ }
168
+
169
+ // ─── Router ──────────────────────────────────────────────────────────────────
170
+
171
+ export class SWRankingRouter implements Router {
172
+ private readonly _battles: ArenaBattle[];
173
+ private readonly _battleEmbs: number[][];
174
+ private readonly _embed: EmbeddingFn;
175
+ private readonly _strongModel: string;
176
+ private readonly _weakModel: string;
177
+ private readonly _model2tier: Map<string, number>;
178
+ /** Battles with models replaced by their tiers. */
179
+ private readonly _tieredBattles: ArenaBattle[];
180
+
181
+ constructor(opts: SWRankingOptions) {
182
+ if (opts.battles.length !== opts.battleEmbeddings.length) {
183
+ throw new Error(
184
+ "battles and battleEmbeddings must have the same length",
185
+ );
186
+ }
187
+
188
+ this._battles = opts.battles;
189
+ this._battleEmbs = opts.battleEmbeddings;
190
+ this._embed = opts.embed;
191
+ this._strongModel = opts.strongModel ?? "gpt-4-1106-preview";
192
+ this._weakModel = opts.weakModel ?? "mixtral-8x7b-instruct-v0.1";
193
+
194
+ const numTiers = opts.numTiers ?? 10;
195
+
196
+ // Compute initial Elo ratings + tiers.
197
+ const ratings = computeEloMle(this._battles);
198
+ this._model2tier = computeTiers(ratings, numTiers);
199
+
200
+ // Replace model names with tier indices in battles.
201
+ this._tieredBattles = this._battles.map((b) => ({
202
+ modelA: String(this._model2tier.get(b.modelA) ?? 0),
203
+ modelB: String(this._model2tier.get(b.modelB) ?? 0),
204
+ winner: b.winner,
205
+ }));
206
+ }
207
+
208
+ async score(prompt: string): Promise<number> {
209
+ const promptEmb = await this._embed(prompt);
210
+ const similarities = cosineSimilarities(
211
+ this._battleEmbs,
212
+ promptEmb,
213
+ );
214
+ const weightings = getWeightings(similarities);
215
+ const wRatings = computeEloMle(this._tieredBattles, weightings);
216
+
217
+ const strongTier = this._model2tier.get(this._strongModel);
218
+ const weakTier = this._model2tier.get(this._weakModel);
219
+
220
+ if (strongTier === undefined || weakTier === undefined) {
221
+ // Unknown model in Elo data — default to strong.
222
+ return 1;
223
+ }
224
+
225
+ const strongScore = wRatings.get(String(strongTier)) ?? 1000;
226
+ const weakScore = wRatings.get(String(weakTier)) ?? 1000;
227
+
228
+ const weakWinRate =
229
+ 1 / (1 + Math.pow(10, (strongScore - weakScore) / 400));
230
+ return 1 - weakWinRate;
231
+ }
232
+ }
@@ -0,0 +1,47 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { RPCClient } from "./rpc";
3
+ import type { Entity } from "./api";
4
+
5
+ interface Item extends Entity {
6
+ id: string;
7
+ name: string;
8
+ }
9
+
10
+ describe("RPCClient", () => {
11
+ it("constructor stores options", () => {
12
+ const client = new RPCClient<Item>({
13
+ baseURL: "http://localhost:8080",
14
+ auth: "tok_123",
15
+ });
16
+ expect(client).toBeDefined();
17
+ });
18
+
19
+ it("constructor works without auth", () => {
20
+ const client = new RPCClient<Item>({
21
+ baseURL: "http://localhost:8080",
22
+ });
23
+ expect(client).toBeDefined();
24
+ });
25
+
26
+ it("exposes CRUD methods", () => {
27
+ const client = new RPCClient<Item>({
28
+ baseURL: "http://localhost:8080",
29
+ });
30
+ expect(typeof client.create).toBe("function");
31
+ expect(typeof client.get).toBe("function");
32
+ expect(typeof client.list).toBe("function");
33
+ expect(typeof client.update).toBe("function");
34
+ expect(typeof client.delete).toBe("function");
35
+ });
36
+
37
+ it("methods return promises", () => {
38
+ const client = new RPCClient<Item>({
39
+ baseURL: "http://localhost:8080",
40
+ });
41
+ // Verify async signatures — calls will fail without a server
42
+ // but should return promises (not throw synchronously)
43
+ const p = client.get("1");
44
+ expect(p).toBeInstanceOf(Promise);
45
+ p.catch(() => {}); // suppress unhandled rejection
46
+ });
47
+ });
package/src/rpc.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Typed ConnectRPC client for kit EntityService.
3
+ *
4
+ * Thin wrapper over generated Connect stubs, mapping between
5
+ * JS objects and protobuf Struct (JSON intermediate).
6
+ */
7
+
8
+ import { createClient, type Client } from "@connectrpc/connect";
9
+ import { createConnectTransport } from "@connectrpc/connect-web";
10
+ import { create, type JsonObject } from "@bufbuild/protobuf";
11
+ import {
12
+ EntityService,
13
+ CreateRequestSchema,
14
+ GetRequestSchema,
15
+ ListRequestSchema,
16
+ UpdateRequestSchema,
17
+ DeleteRequestSchema,
18
+ } from "./gen/crud_pb.js";
19
+ import type { Entity, Query } from "./api.js";
20
+
21
+ export interface RPCClientOptions {
22
+ baseURL: string;
23
+ auth?: string;
24
+ }
25
+
26
+ export class RPCClient<T extends Entity> {
27
+ private client: Client<typeof EntityService>;
28
+ private auth?: string;
29
+
30
+ constructor(opts: RPCClientOptions) {
31
+ this.auth = opts.auth;
32
+ const transport = createConnectTransport({
33
+ baseUrl: opts.baseURL,
34
+ interceptors: this.auth
35
+ ? [
36
+ (next) => async (req) => {
37
+ req.header.set(
38
+ "Authorization",
39
+ `Bearer ${this.auth}`,
40
+ );
41
+ return next(req);
42
+ },
43
+ ]
44
+ : [],
45
+ });
46
+ this.client = createClient(EntityService, transport);
47
+ }
48
+
49
+ async create(entity: Omit<T, "id"> | T): Promise<T> {
50
+ const res = await this.client.create(
51
+ create(CreateRequestSchema, {
52
+ entity: entity as unknown as JsonObject,
53
+ }),
54
+ );
55
+ return (res.entity ?? {}) as unknown as T;
56
+ }
57
+
58
+ async get(id: string): Promise<T> {
59
+ const res = await this.client.get(
60
+ create(GetRequestSchema, { id }),
61
+ );
62
+ return (res.entity ?? {}) as unknown as T;
63
+ }
64
+
65
+ async list(q?: Query): Promise<T[]> {
66
+ const res = await this.client.list(
67
+ create(ListRequestSchema, {
68
+ limit: q?.limit ?? 0,
69
+ offset: q?.offset ?? 0,
70
+ sort: q?.sort ?? "",
71
+ search: q?.search ?? "",
72
+ }),
73
+ );
74
+ return (res.entities ?? []) as unknown as T[];
75
+ }
76
+
77
+ async update(entity: T): Promise<T> {
78
+ const res = await this.client.update(
79
+ create(UpdateRequestSchema, {
80
+ entity: entity as unknown as JsonObject,
81
+ }),
82
+ );
83
+ return (res.entity ?? {}) as unknown as T;
84
+ }
85
+
86
+ async delete(id: string): Promise<void> {
87
+ await this.client.delete(
88
+ create(DeleteRequestSchema, { id }),
89
+ );
90
+ }
91
+ }
@@ -0,0 +1,53 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { safetyGuard } from './safety';
3
+
4
+ describe('safetyGuard', () => {
5
+ const origIsTTY = process.stdout.isTTY;
6
+
7
+ afterEach(() => {
8
+ process.stdout.isTTY = origIsTTY;
9
+ });
10
+
11
+ it('read level always passes', () => {
12
+ expect(() => safetyGuard('read')).not.toThrow();
13
+ });
14
+
15
+ it('read level passes even in non-TTY', () => {
16
+ process.stdout.isTTY = undefined;
17
+ expect(() => safetyGuard('read')).not.toThrow();
18
+ });
19
+
20
+ it('caution level passes in TTY', () => {
21
+ process.stdout.isTTY = true;
22
+ expect(() => safetyGuard('caution')).not.toThrow();
23
+ });
24
+
25
+ it('caution level requires --force in non-TTY', () => {
26
+ process.stdout.isTTY = undefined;
27
+ expect(() => safetyGuard('caution')).toThrow(/--force/);
28
+ });
29
+
30
+ it('caution level passes with force in non-TTY', () => {
31
+ process.stdout.isTTY = undefined;
32
+ expect(() => safetyGuard('caution', { force: true })).not.toThrow();
33
+ });
34
+
35
+ it('dangerous level throws without --force', () => {
36
+ process.stdout.isTTY = true;
37
+ expect(() => safetyGuard('dangerous')).toThrow(/--force/);
38
+ });
39
+
40
+ it('dangerous level passes with --force', () => {
41
+ expect(() => safetyGuard('dangerous', { force: true })).not.toThrow();
42
+ });
43
+
44
+ it('dangerous level requires --force in non-TTY', () => {
45
+ process.stdout.isTTY = undefined;
46
+ expect(() => safetyGuard('dangerous')).toThrow(/--force/);
47
+ });
48
+
49
+ it('dangerous level passes with --force in non-TTY', () => {
50
+ process.stdout.isTTY = undefined;
51
+ expect(() => safetyGuard('dangerous', { force: true })).not.toThrow();
52
+ });
53
+ });
package/src/safety.ts ADDED
@@ -0,0 +1,42 @@
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
+
11
+ export type SafetyLevel = 'read' | 'caution' | 'dangerous';
12
+
13
+ /**
14
+ * Validates that the current context permits the requested safety level.
15
+ *
16
+ * - `read`: always passes
17
+ * - `caution`: passes in TTY; requires `--force` in non-TTY
18
+ * - `dangerous`: always requires `--force`
19
+ *
20
+ * @throws {Error} when guard fails, with message referencing --force
21
+ */
22
+ export function safetyGuard(
23
+ level: SafetyLevel,
24
+ opts?: { force?: boolean },
25
+ ): void {
26
+ if (level === 'read') return;
27
+
28
+ const force = opts?.force ?? false;
29
+ const isTTY = !!process.stdout.isTTY;
30
+
31
+ if (level === 'dangerous' && !force) {
32
+ throw new Error(
33
+ 'dangerous operation requires --force',
34
+ );
35
+ }
36
+
37
+ if (level === 'caution' && !isTTY && !force) {
38
+ throw new Error(
39
+ 'caution-level operation in non-TTY requires --force',
40
+ );
41
+ }
42
+ }
@@ -0,0 +1,72 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://hop.top/kit/contracts/parity/scope-defaults.json",
4
+ "description": "Cross-language default deny patterns for kit/scope. Go, TypeScript, and Python ports MUST load values from here. Patterns use bmatcuk/doublestar/v4 syntax; '~' expands to the user home directory; environment macros (%APPDATA%, %LOCALAPPDATA%, %USERPROFILE%) expand to the corresponding os.UserConfigDir / os.UserHomeDir results so test overrides work.",
5
+ "version": 1,
6
+ "deny": {
7
+ "common": [
8
+ "~/.ssh/**",
9
+ "~/.aws/**",
10
+ "~/.azure/**",
11
+ "~/.config/gcloud/**",
12
+ "~/.gnupg/**",
13
+ "~/.pki/**",
14
+ "~/.kube/**",
15
+ "~/.netrc",
16
+ "~/.pgpass",
17
+ "~/.my.cnf",
18
+ "~/.npmrc",
19
+ "~/.pypirc",
20
+ "**/.env",
21
+ "**/.env.*",
22
+ "**/credentials*",
23
+ "**/secrets*",
24
+ "**/*.pem",
25
+ "**/*.key",
26
+ "**/id_rsa*",
27
+ "**/id_ed25519*",
28
+ "**/.git/config"
29
+ ],
30
+ "darwin": [
31
+ "~/Library/Keychains/**",
32
+ "~/Library/Cookies/**",
33
+ "~/Library/Application Support/Google/Chrome/**/Cookies*",
34
+ "~/Library/Application Support/Google/Chrome/**/Login Data*",
35
+ "~/Library/Application Support/Arc/User Data/**/Cookies*",
36
+ "~/Library/Application Support/BraveSoftware/Brave-Browser/**/Cookies*",
37
+ "~/Library/Application Support/Microsoft Edge/**/Cookies*",
38
+ "~/Library/Application Support/Firefox/Profiles/**/cookies.sqlite",
39
+ "~/Library/Application Support/Firefox/Profiles/**/key*.db",
40
+ "~/Library/Application Support/Firefox/Profiles/**/logins.json"
41
+ ],
42
+ "linux": [
43
+ "~/.config/google-chrome/**/Cookies*",
44
+ "~/.config/google-chrome/**/Login Data*",
45
+ "~/.config/BraveSoftware/Brave-Browser/**/Cookies*",
46
+ "~/.config/microsoft-edge/**/Cookies*",
47
+ "~/.mozilla/firefox/**/cookies.sqlite",
48
+ "~/.mozilla/firefox/**/key*.db",
49
+ "~/.mozilla/firefox/**/logins.json"
50
+ ],
51
+ "windows": [
52
+ "%USERPROFILE%/.aws/**",
53
+ "%USERPROFILE%/.azure/**",
54
+ "%APPDATA%/gcloud/**",
55
+ "%USERPROFILE%/.kube/**",
56
+ "%USERPROFILE%/.ssh/**",
57
+ "%APPDATA%/Microsoft/Credentials/**",
58
+ "%LOCALAPPDATA%/Microsoft/Credentials/**",
59
+ "%APPDATA%/Microsoft/Crypto/**",
60
+ "%APPDATA%/Microsoft/Protect/**",
61
+ "%APPDATA%/Microsoft/SystemCertificates/**",
62
+ "%APPDATA%/PuTTY/sshhostkeys",
63
+ "%APPDATA%/PuTTY/sessions/**",
64
+ "%LOCALAPPDATA%/Google/Chrome/User Data/**/Cookies*",
65
+ "%LOCALAPPDATA%/Google/Chrome/User Data/**/Login Data*",
66
+ "%LOCALAPPDATA%/Microsoft/Edge/User Data/**/Cookies*",
67
+ "%APPDATA%/Mozilla/Firefox/Profiles/**/cookies.sqlite",
68
+ "%APPDATA%/Mozilla/Firefox/Profiles/**/key*.db",
69
+ "%APPDATA%/Mozilla/Firefox/Profiles/**/logins.json"
70
+ ]
71
+ }
72
+ }