@rendotdev/rig 0.0.20 → 0.0.22

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 (30) hide show
  1. package/README.md +3 -1
  2. package/dist/{cli-nk194xv0.js → cli-043bae8s.js} +85 -3
  3. package/dist/{cli-es8j6mma.js → cli-1ssn3a04.js} +3 -3
  4. package/dist/{cli-13q90bjr.js → cli-32dzwg3p.js} +6 -0
  5. package/dist/{cli-1hm5dxfw.js → cli-ahwyqf1f.js} +2 -2
  6. package/dist/{cli-f7p31fzm.js → cli-dqz4gvqd.js} +3 -3
  7. package/dist/cli-eavzwv49.js +5161 -0
  8. package/dist/{cli-1354fmns.js → cli-q2ajq5qe.js} +3 -3
  9. package/dist/{cli-884hpkjc.js → cli-zbp3334x.js} +1 -1
  10. package/dist/{config-20f90shh.js → config-72dha2z0.js} +2 -2
  11. package/dist/{create-pvym2abv.js → create-pnsj60ym.js} +4 -4
  12. package/dist/cron-zhb9hpbs.js +18 -0
  13. package/dist/{dev-link-e1mj8w17.js → dev-link-znh4mch1.js} +1 -1
  14. package/dist/{discover-95bpzy46.js → discover-549nzamy.js} +3 -3
  15. package/dist/{help-qj75r0x3.js → help-kg1zhj6n.js} +5 -5
  16. package/dist/{inspect-0ckw7bs5.js → inspect-vqtm5htv.js} +5 -5
  17. package/dist/list-2n0p40dn.js +13 -0
  18. package/dist/{paths-3vxw7dek.js → paths-4kzahz8f.js} +1 -1
  19. package/dist/{registry-fzc3aeb8.js → registry-nvnbmws0.js} +2 -2
  20. package/dist/rig.js +50 -40
  21. package/dist/run-mvhmkkfe.js +13 -0
  22. package/dist/{runtime-comment-07cpchsr.js → runtime-comment-n9aft3g5.js} +10 -3
  23. package/dist/{sync-k2spbt3f.js → sync-javg558s.js} +11 -7
  24. package/dist/{typecheck-971tmqbp.js → typecheck-c944bvz2.js} +4 -4
  25. package/dist/{update-check-dpkh7hc6.js → update-check-bqa9ejex.js} +1 -1
  26. package/package.json +2 -1
  27. package/dist/cli-113n7c3t.js +0 -513
  28. package/dist/cron-aw908dzn.js +0 -18
  29. package/dist/list-gqdh0m23.js +0 -13
  30. package/dist/run-thx15p83.js +0 -13
@@ -1,513 +0,0 @@
1
- import {
2
- SchemaRenderer
3
- } from "./cli-884hpkjc.js";
4
- import {
5
- CommandIds,
6
- ToolLoader,
7
- createRigToolKit
8
- } from "./cli-f7p31fzm.js";
9
- import {
10
- RigError,
11
- RigErrors
12
- } from "./cli-1c7te5cg.js";
13
-
14
- // src/tools/run.ts
15
- import { readFile } from "node:fs/promises";
16
-
17
- // src/runtime/envelope.ts
18
- class EnvelopeFactory {
19
- static success(params) {
20
- return {
21
- data: params.data,
22
- errors: []
23
- };
24
- }
25
- static error(params) {
26
- return {
27
- data: null,
28
- errors: [
29
- {
30
- code: params.code,
31
- message: params.message,
32
- details: params.details
33
- }
34
- ]
35
- };
36
- }
37
- }
38
-
39
- // src/runtime/truncation.ts
40
- import { mkdtemp, writeFile } from "node:fs/promises";
41
- import { tmpdir } from "node:os";
42
- import { join } from "node:path";
43
- var DEFAULT_TRUNCATION_MAX_BYTES = 50 * 1024;
44
- var DEFAULT_TRUNCATION_MAX_LINES = 2000;
45
-
46
- class TextMetrics {
47
- encoder = new TextEncoder;
48
- byteLength(value) {
49
- return this.encoder.encode(value).byteLength;
50
- }
51
- lineCount(value) {
52
- if (value.length === 0)
53
- return 0;
54
- return value.split(`
55
- `).length;
56
- }
57
- }
58
-
59
- class TextHeadTruncator {
60
- metrics = new TextMetrics;
61
- encoder = new TextEncoder;
62
- decoder = new TextDecoder;
63
- truncate(value, options) {
64
- const totalBytes = this.metrics.byteLength(value);
65
- const totalLines = this.metrics.lineCount(value);
66
- let content = value;
67
- if (totalLines > options.maxLines) {
68
- content = content.split(`
69
- `).slice(0, options.maxLines).join(`
70
- `);
71
- }
72
- if (this.metrics.byteLength(content) > options.maxBytes) {
73
- content = this.decoder.decode(this.encoder.encode(content).slice(0, options.maxBytes));
74
- }
75
- const outputBytes = this.metrics.byteLength(content);
76
- const outputLines = this.metrics.lineCount(content);
77
- return {
78
- content,
79
- truncated: outputBytes < totalBytes || outputLines < totalLines,
80
- totalBytes,
81
- totalLines,
82
- outputBytes,
83
- outputLines
84
- };
85
- }
86
- }
87
-
88
- class OutputTempFileStore {
89
- async writeJson(content) {
90
- const dir = await mkdtemp(join(tmpdir(), "rig-output-"));
91
- const path = join(dir, "data.json");
92
- if (typeof Bun !== "undefined")
93
- await Bun.write(path, `${content}
94
- `);
95
- else
96
- await writeFile(path, `${content}
97
- `, "utf8");
98
- return path;
99
- }
100
- }
101
-
102
- class JsonDataSerializer {
103
- serialize(value) {
104
- return JSON.stringify(value, null, 2) ?? "null";
105
- }
106
- }
107
-
108
- class SizeFormatter {
109
- format(bytes) {
110
- if (bytes < 1024)
111
- return `${bytes}B`;
112
- if (bytes < 1024 * 1024)
113
- return `${(bytes / 1024).toFixed(1)}KB`;
114
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
115
- }
116
- }
117
-
118
- class RigOutputTruncator {
119
- options;
120
- serializer = new JsonDataSerializer;
121
- truncator = new TextHeadTruncator;
122
- store = new OutputTempFileStore;
123
- sizeFormatter = new SizeFormatter;
124
- constructor(options = {}) {
125
- this.options = {
126
- maxBytes: options.maxBytes ?? DEFAULT_TRUNCATION_MAX_BYTES,
127
- maxLines: options.maxLines ?? DEFAULT_TRUNCATION_MAX_LINES
128
- };
129
- }
130
- async truncateData(data) {
131
- const serialized = this.serializer.serialize(data);
132
- const truncation = this.truncator.truncate(serialized, this.options);
133
- if (!truncation.truncated)
134
- return data;
135
- const fullOutputPath = await this.store.writeJson(serialized);
136
- const omittedBytes = truncation.totalBytes - truncation.outputBytes;
137
- const omittedLines = truncation.totalLines - truncation.outputLines;
138
- return {
139
- truncated: true,
140
- strategy: "head",
141
- preview: truncation.content,
142
- previewFormat: "partial-json",
143
- fullOutputPath,
144
- fullOutputFormat: "json",
145
- maxBytes: this.options.maxBytes,
146
- maxLines: this.options.maxLines,
147
- totalBytes: truncation.totalBytes,
148
- totalLines: truncation.totalLines,
149
- shownBytes: truncation.outputBytes,
150
- shownLines: truncation.outputLines,
151
- omittedBytes,
152
- omittedLines,
153
- message: `Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${this.sizeFormatter.format(truncation.outputBytes)} of ${this.sizeFormatter.format(truncation.totalBytes)}). Full output saved to: ${fullOutputPath}`
154
- };
155
- }
156
- }
157
-
158
- // src/tools/db.ts
159
- import { createHash } from "node:crypto";
160
- import { mkdir } from "node:fs/promises";
161
- import { dirname, join as join2 } from "node:path";
162
- class MigrationChecksum {
163
- digest(version, name, sql) {
164
- return createHash("sha256").update(`${version}\x00${name}\x00${sql}`).digest("hex");
165
- }
166
- }
167
-
168
- class RigDatabaseMigrator {
169
- db;
170
- lastVersion = 0;
171
- checksums = new MigrationChecksum;
172
- constructor(db) {
173
- this.db = db;
174
- }
175
- ensureMetadata() {
176
- this.db.run(`
177
- create table if not exists _rig_migrations (
178
- version integer primary key,
179
- name text not null,
180
- checksum text not null,
181
- applied_at text not null
182
- );
183
- `);
184
- }
185
- migrate(version, name, sql) {
186
- this.validate(version, name, sql);
187
- const checksum = this.checksums.digest(version, name, sql);
188
- const existing = this.existingMigration(version);
189
- if (existing) {
190
- this.assertExistingMigrationMatches(version, name, checksum, existing);
191
- return;
192
- }
193
- const apply = this.db.transaction(() => {
194
- this.db.run(sql);
195
- this.db.query(`insert into _rig_migrations (version, name, checksum, applied_at)
196
- values ($version, $name, $checksum, $appliedAt)`).run({ version, name, checksum, appliedAt: new Date().toISOString() });
197
- });
198
- apply();
199
- }
200
- validate(version, name, sql) {
201
- if (!Number.isInteger(version) || version <= 0) {
202
- throw new RigError("TOOL_INVALID", `Migration version must be a positive integer: ${version}`);
203
- }
204
- if (version <= this.lastVersion) {
205
- throw new RigError("TOOL_INVALID", `Migration versions must be declared in ascending order: ${version} after ${this.lastVersion}`);
206
- }
207
- if (!name.trim())
208
- throw new RigError("TOOL_INVALID", "Migration name must not be empty.");
209
- if (!sql.trim())
210
- throw new RigError("TOOL_INVALID", `Migration ${version} SQL must not be empty.`);
211
- this.lastVersion = version;
212
- }
213
- existingMigration(version) {
214
- const row = this.db.query("select name, checksum from _rig_migrations where version = ?").get(version);
215
- return row ?? undefined;
216
- }
217
- assertExistingMigrationMatches(version, name, checksum, existing) {
218
- if (existing.name === name && existing.checksum === checksum)
219
- return;
220
- throw new RigError("TOOL_INVALID", `Migration ${version} has changed since it was applied.`, {
221
- version,
222
- expected: existing,
223
- actual: { name, checksum }
224
- });
225
- }
226
- }
227
-
228
- class BunSqliteModuleLoader {
229
- async database() {
230
- const database = globalThis.rigSqliteDatabaseForTests;
231
- if (!database)
232
- return this.nativeDatabase();
233
- return database;
234
- }
235
- async nativeDatabase() {
236
- const specifier = "bun:sqlite";
237
- const moduleValue = await import(specifier);
238
- return moduleValue.Database;
239
- }
240
- }
241
-
242
- class RigToolDatabaseFactory {
243
- sqlite = new BunSqliteModuleLoader;
244
- async create(toolPath) {
245
- const dbPath = this.dbPathForToolPath(toolPath);
246
- await mkdir(dirname(dbPath), { recursive: true });
247
- const Database = await this.sqlite.database();
248
- const db = new Database(dbPath, { create: true, strict: true });
249
- const migrator = new RigDatabaseMigrator(db);
250
- Object.defineProperty(db, "path", { value: dbPath, enumerable: true });
251
- Object.defineProperty(db, "migrate", {
252
- value: (version, name, sql) => migrator.migrate(version, name, sql),
253
- enumerable: true
254
- });
255
- db.run("PRAGMA journal_mode = WAL;");
256
- migrator.ensureMetadata();
257
- return db;
258
- }
259
- dbPathForToolPath(toolPath) {
260
- return join2(dirname(toolPath), "index.sqlite");
261
- }
262
- }
263
-
264
- class UnavailableToolDatabaseFactory {
265
- create(toolName) {
266
- return new Proxy({}, {
267
- get() {
268
- throw new RigError("TOOL_INVALID", `Tool ${toolName} must define setupDb before using context.db.`, {
269
- tool: toolName
270
- });
271
- }
272
- });
273
- }
274
- }
275
-
276
- class ToolDatabaseService {
277
- factory = new RigToolDatabaseFactory;
278
- async setup(tool) {
279
- if (!tool.definition.setupDb)
280
- return;
281
- const db = await this.factory.create(tool.path);
282
- await tool.definition.setupDb(db);
283
- return db;
284
- }
285
- dbPathForToolPath(toolPath) {
286
- return this.factory.dbPathForToolPath(toolPath);
287
- }
288
- }
289
-
290
- // src/tools/run.ts
291
- class RunInputReader {
292
- async read(command, options) {
293
- const args = options.args ?? [];
294
- const inputSources = [
295
- Boolean(options.input),
296
- Boolean(options.inputFile),
297
- args.length > 0
298
- ].filter(Boolean).length;
299
- if (inputSources > 1) {
300
- throw new RigError("INPUT_ERROR", "Use args, --input, or --input-file, not more than one.");
301
- }
302
- if (options.inputFile) {
303
- const value = typeof Bun !== "undefined" ? await Bun.file(options.inputFile).json() : JSON.parse(await readFile(options.inputFile, "utf8"));
304
- return { value, source: `--input-file ${options.inputFile}` };
305
- }
306
- if (options.input) {
307
- return { value: JSON.parse(options.input), source: `--input '${options.input}'` };
308
- }
309
- if (args.length > 0) {
310
- const parser = new InputArgumentParser(command.input);
311
- return { value: parser.parse(args), source: new InputSourceRenderer().render(args) };
312
- }
313
- return { value: {}, source: "--input '{}'" };
314
- }
315
- }
316
-
317
- class InputArgumentParser {
318
- schema;
319
- constructor(schema) {
320
- this.schema = schema;
321
- }
322
- parse(args) {
323
- if (args.length === 1) {
324
- const maybeJson = this.tryParseJson(args[0]);
325
- if (maybeJson.parsed && this.shouldUseJsonValue(maybeJson.value))
326
- return maybeJson.value;
327
- }
328
- if (args.every((arg) => arg.includes("="))) {
329
- return Object.fromEntries(args.map((arg) => this.parseKeyValueArg(arg)));
330
- }
331
- const fields = this.inputFieldNames();
332
- if (fields.length === 0) {
333
- if (args.length === 1)
334
- return this.parseScalar(args[0]);
335
- throw new RigError("INPUT_ERROR", "This command does not declare positional input fields.", {
336
- args
337
- });
338
- }
339
- if (args.length > fields.length) {
340
- throw new RigError("INPUT_ERROR", "Too many positional arguments.", {
341
- args,
342
- expectedFields: fields
343
- });
344
- }
345
- return Object.fromEntries(args.map((arg, index) => [fields[index], this.parseScalar(arg)]));
346
- }
347
- parseKeyValueArg(arg) {
348
- const separatorIndex = arg.indexOf("=");
349
- const key = arg.slice(0, separatorIndex);
350
- const value = arg.slice(separatorIndex + 1);
351
- if (!key) {
352
- throw new RigError("INPUT_ERROR", "Argument keys must not be empty.", { arg });
353
- }
354
- return [key, this.parseScalar(value)];
355
- }
356
- parseScalar(value) {
357
- const maybeJson = this.tryParseJson(value);
358
- return maybeJson.parsed ? maybeJson.value : value;
359
- }
360
- tryParseJson(value) {
361
- try {
362
- return { parsed: true, value: JSON.parse(value) };
363
- } catch {
364
- return { parsed: false };
365
- }
366
- }
367
- shouldUseJsonValue(value) {
368
- return typeof value === "object" && value !== null;
369
- }
370
- inputFieldNames() {
371
- const jsonSchema = SchemaRenderer.toJsonSchema(this.schema);
372
- if (!this.isRecord(jsonSchema) || !this.isRecord(jsonSchema.properties))
373
- return [];
374
- return Object.keys(jsonSchema.properties);
375
- }
376
- isRecord(value) {
377
- return typeof value === "object" && value !== null && !Array.isArray(value);
378
- }
379
- }
380
-
381
- class InputSourceRenderer {
382
- render(args) {
383
- return args.map((arg) => this.shellArg(arg)).join(" ");
384
- }
385
- shellArg(value) {
386
- if (/^[A-Za-z0-9_./:=@+-]+$/.test(value))
387
- return value;
388
- return `'${value.replaceAll("'", "'\\''")}'`;
389
- }
390
- }
391
-
392
- class ZodErrorPresenter {
393
- present(error) {
394
- return {
395
- ...this.flattenObject(error.flatten()),
396
- issues: (error.issues ?? []).map((issue) => this.presentIssue(issue))
397
- };
398
- }
399
- presentIssue(issue) {
400
- if (!this.isRecord(issue))
401
- return { message: String(issue) };
402
- return Object.fromEntries(Object.entries({
403
- path: Array.isArray(issue.path) ? issue.path.join(".") : "",
404
- code: issue.code,
405
- message: issue.message,
406
- expected: issue.expected,
407
- received: issue.received
408
- }).filter(([, value]) => value !== undefined));
409
- }
410
- flattenObject(value) {
411
- return this.isRecord(value) ? value : {};
412
- }
413
- isRecord(value) {
414
- return typeof value === "object" && value !== null && !Array.isArray(value);
415
- }
416
- }
417
-
418
- class DryRunPresenter {
419
- present(params) {
420
- return {
421
- dryRun: true,
422
- wouldRun: false,
423
- tool: params.tool,
424
- command: params.command,
425
- id: CommandIds.from(params.tool, params.command),
426
- input: params.input,
427
- commandLine: `rig run ${CommandIds.from(params.tool, params.command)} ${params.inputSource}`
428
- };
429
- }
430
- }
431
-
432
- class ToolRunner {
433
- options;
434
- databases = new ToolDatabaseService;
435
- loader;
436
- inputReader = new RunInputReader;
437
- outputTruncator = new RigOutputTruncator;
438
- unavailableDatabases = new UnavailableToolDatabaseFactory;
439
- constructor(options = {}) {
440
- this.options = options;
441
- this.loader = new ToolLoader(options);
442
- }
443
- async run(toolName, commandName, options = {}) {
444
- let db;
445
- try {
446
- const { tool, command } = await this.loader.loadCommand(toolName, commandName);
447
- const input = await this.inputReader.read(command, options);
448
- const inputResult = command.input.safeParse(input.value);
449
- if (!inputResult.success) {
450
- throw new RigError("VALIDATION_ERROR", "Invalid input.", new ZodErrorPresenter().present(inputResult.error));
451
- }
452
- if (options.dryRun) {
453
- const data2 = new DryRunPresenter().present({
454
- tool: toolName,
455
- command: commandName,
456
- input: inputResult.data,
457
- inputSource: input.source
458
- });
459
- return {
460
- envelope: EnvelopeFactory.success({
461
- data: await this.outputTruncator.truncateData(data2)
462
- }),
463
- exitCode: 0
464
- };
465
- }
466
- const rig = createRigToolKit(this.options);
467
- db = await this.databases.setup(tool);
468
- const data = await command.run({
469
- input: inputResult.data,
470
- env: tool.env,
471
- processEnv: process.env,
472
- cwd: process.cwd(),
473
- db: db ?? this.unavailableDatabases.create(toolName),
474
- rig
475
- });
476
- const outputResult = command.output.safeParse(data);
477
- if (!outputResult.success) {
478
- throw new RigError("OUTPUT_VALIDATION_ERROR", "Command returned invalid output.", new ZodErrorPresenter().present(outputResult.error));
479
- }
480
- return {
481
- envelope: EnvelopeFactory.success({
482
- data: await this.outputTruncator.truncateData(outputResult.data)
483
- }),
484
- exitCode: 0
485
- };
486
- } catch (error) {
487
- const rigError = this.asInputAwareRigError(error);
488
- return {
489
- envelope: EnvelopeFactory.error({
490
- code: rigError.code,
491
- message: rigError.message,
492
- details: rigError.details
493
- }),
494
- exitCode: 1
495
- };
496
- } finally {
497
- this.closeDatabase(db);
498
- }
499
- }
500
- closeDatabase(db) {
501
- try {
502
- db?.close(false);
503
- } catch {}
504
- }
505
- asInputAwareRigError(error) {
506
- if (error instanceof SyntaxError) {
507
- return new RigError("INPUT_ERROR", "Input JSON is invalid.", { message: error.message });
508
- }
509
- return RigErrors.from(error);
510
- }
511
- }
512
-
513
- export { ToolRunner };
@@ -1,18 +0,0 @@
1
- import {
2
- RigCronService,
3
- RigCronWorker,
4
- cronModuleUrl
5
- } from "./cli-es8j6mma.js";
6
- import"./cli-113n7c3t.js";
7
- import"./cli-884hpkjc.js";
8
- import"./cli-f7p31fzm.js";
9
- import"./cli-1hm5dxfw.js";
10
- import"./cli-nk194xv0.js";
11
- import"./cli-1c7te5cg.js";
12
- import"./cli-13q90bjr.js";
13
- import"./cli-b7jgjgy7.js";
14
- export {
15
- cronModuleUrl,
16
- RigCronWorker,
17
- RigCronService
18
- };
@@ -1,13 +0,0 @@
1
- import {
2
- ToolListService
3
- } from "./cli-1354fmns.js";
4
- import"./cli-884hpkjc.js";
5
- import"./cli-f7p31fzm.js";
6
- import"./cli-1hm5dxfw.js";
7
- import"./cli-nk194xv0.js";
8
- import"./cli-1c7te5cg.js";
9
- import"./cli-13q90bjr.js";
10
- import"./cli-b7jgjgy7.js";
11
- export {
12
- ToolListService
13
- };
@@ -1,13 +0,0 @@
1
- import {
2
- ToolRunner
3
- } from "./cli-113n7c3t.js";
4
- import"./cli-884hpkjc.js";
5
- import"./cli-f7p31fzm.js";
6
- import"./cli-1hm5dxfw.js";
7
- import"./cli-nk194xv0.js";
8
- import"./cli-1c7te5cg.js";
9
- import"./cli-13q90bjr.js";
10
- import"./cli-b7jgjgy7.js";
11
- export {
12
- ToolRunner
13
- };