agent-package-manager 0.1.0 → 0.2.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.
package/dist/cli/index.js CHANGED
@@ -27,8 +27,8 @@ function createProgram(handlers2, version) {
27
27
  program2.command("materialize").description("Build resolved DSL and generate runtime artifacts.").option("--no-generate", "Skip agent-runtime generate step.", false).option("--no-lint", "Skip agent-contracts lint step.", false).option("--clean", "Clean build directory before materializing.", false).action(async (opts, cmd) => {
28
28
  await handlers2.materialize(opts, cmd.optsWithGlobals());
29
29
  });
30
- program2.command("check").description("Run full verification pipeline for CI.").action(async (opts, cmd) => {
31
- await handlers2.check({}, cmd.optsWithGlobals());
30
+ program2.command("check").description("Run full verification pipeline for CI.").action(async (_opts, cmd) => {
31
+ await handlers2.check(cmd.optsWithGlobals());
32
32
  });
33
33
  program2.command("publish").description("Publish a package in the registry repository.").argument("<path>", "Path to the package directory within the registry repository.").option("--version <semver>", "Override version for this publish.").option("--dry-run", "Show what would be published without making changes.", false).option("--tag-only", "Only create the git tag, skip validation.", false).option("--no-push", "Create the tag locally but do not push to remote.", false).action(async (path, opts, cmd) => {
34
34
  await handlers2.publish(path, opts, cmd.optsWithGlobals());
@@ -36,20 +36,1190 @@ function createProgram(handlers2, version) {
36
36
  return program2;
37
37
  }
38
38
 
39
+ // src/lib/logger.ts
40
+ var _verbose = false;
41
+ function setVerbose(v) {
42
+ _verbose = v;
43
+ }
44
+ var log = {
45
+ info(msg) {
46
+ console.log(msg);
47
+ },
48
+ success(msg) {
49
+ console.log(`\u2713 ${msg}`);
50
+ },
51
+ warn(msg) {
52
+ console.warn(`\u26A0 ${msg}`);
53
+ },
54
+ error(msg) {
55
+ console.error(`\u2717 ${msg}`);
56
+ },
57
+ debug(msg) {
58
+ if (_verbose) console.log(` ${msg}`);
59
+ },
60
+ step(msg) {
61
+ console.log(`\u2192 ${msg}`);
62
+ }
63
+ };
64
+
65
+ // src/lib/commands/init.ts
66
+ import { existsSync } from "fs";
67
+ import { mkdir, writeFile } from "fs/promises";
68
+ import { join } from "path";
69
+
70
+ // src/lib/resolve.ts
71
+ function parsePackageSpec(spec) {
72
+ if (spec.startsWith("github:")) {
73
+ return parseGitHubSpec(spec);
74
+ }
75
+ const atIdx = spec.lastIndexOf("@");
76
+ if (atIdx > 0) {
77
+ return {
78
+ name: spec.slice(0, atIdx),
79
+ version: spec.slice(atIdx + 1)
80
+ };
81
+ }
82
+ return { name: spec };
83
+ }
84
+ function parseGitHubSpec(spec) {
85
+ const rest = spec.slice("github:".length);
86
+ const doubleSlash = rest.indexOf("//");
87
+ if (doubleSlash === -1) {
88
+ throw new Error(`Invalid GitHub specifier: ${spec}. Expected github:<owner>/<repo>//<path>@<version>`);
89
+ }
90
+ const ownerRepo = rest.slice(0, doubleSlash);
91
+ const pathVersion = rest.slice(doubleSlash + 2);
92
+ const [owner, repo] = ownerRepo.split("/");
93
+ if (!owner || !repo) {
94
+ throw new Error(`Invalid owner/repo in specifier: ${spec}`);
95
+ }
96
+ const atIdx = pathVersion.lastIndexOf("@");
97
+ let path;
98
+ let version;
99
+ if (atIdx > 0) {
100
+ path = pathVersion.slice(0, atIdx);
101
+ version = pathVersion.slice(atIdx + 1);
102
+ } else {
103
+ path = pathVersion;
104
+ }
105
+ const name = path.split("/").pop();
106
+ return { name, version, owner, repo, path };
107
+ }
108
+ function parseRegistrySpec(spec) {
109
+ if (!spec.startsWith("github:")) {
110
+ throw new Error(`Invalid registry specifier: ${spec}. Expected github:<owner>/<repo>`);
111
+ }
112
+ const rest = spec.slice("github:".length);
113
+ const [owner, repo] = rest.split("/");
114
+ if (!owner || !repo) {
115
+ throw new Error(`Invalid registry specifier: ${spec}`);
116
+ }
117
+ return { owner, repo };
118
+ }
119
+ function buildTag(packageName, version, tagFormat) {
120
+ const fmt = tagFormat || "{package}/v{version}";
121
+ return fmt.replace("{package}", packageName).replace("{version}", version);
122
+ }
123
+ function parseTagVersion(tag, packageName) {
124
+ const prefix = `${packageName}/v`;
125
+ if (!tag.startsWith(prefix)) return null;
126
+ return tag.slice(prefix.length);
127
+ }
128
+ function resolveRegistryForPackage(config, packageName) {
129
+ const pkg = config.packages[packageName];
130
+ const registryName = pkg?.registry || "default";
131
+ const registry = config.registries[registryName];
132
+ if (!registry) {
133
+ throw new Error(`Registry "${registryName}" not found in ${JSON.stringify(Object.keys(config.registries))}`);
134
+ }
135
+ return registry;
136
+ }
137
+
138
+ // src/lib/types.ts
139
+ var CONFIG_FILE = "agent-pkg.json";
140
+ var LOCK_FILE = "agent-pkg.lock.json";
141
+ var DEFAULT_MODULES_DIR = "agent_modules";
142
+ var DEFAULT_BUILD_DIR = ".agent-pkg/build";
143
+ var DEFAULT_CACHE_DIR = ".agent-pkg/cache";
144
+ var PACKAGE_MANIFEST_FILE = "agent-pkg.package.json";
145
+
146
+ // src/lib/commands/init.ts
147
+ async function runInit(opts, projectDir) {
148
+ const configPath = join(projectDir, CONFIG_FILE);
149
+ if (existsSync(configPath)) {
150
+ throw new Error(`${CONFIG_FILE} already exists. Aborting init.`);
151
+ }
152
+ const modulesDir = opts.modulesDir || DEFAULT_MODULES_DIR;
153
+ const buildDir = opts.buildDir || DEFAULT_BUILD_DIR;
154
+ const cacheDir = DEFAULT_CACHE_DIR;
155
+ const filesCreated = [];
156
+ const dirsCreated = [];
157
+ const registries = {};
158
+ if (opts.registry) {
159
+ const { owner, repo } = parseRegistrySpec(opts.registry);
160
+ registries["default"] = {
161
+ type: "github",
162
+ owner,
163
+ repo,
164
+ packageRoot: "packages",
165
+ tagFormat: "{package}/v{version}"
166
+ };
167
+ }
168
+ const config = {
169
+ schemaVersion: 1,
170
+ registries,
171
+ install: { modulesDir, buildDir, cacheDir },
172
+ packages: {},
173
+ vars: {},
174
+ materialize: {
175
+ writeResolvedDsl: true,
176
+ runValidate: true,
177
+ runLint: true,
178
+ runRuntimeGenerate: true
179
+ }
180
+ };
181
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
182
+ filesCreated.push(CONFIG_FILE);
183
+ log.success(`Created ${CONFIG_FILE}`);
184
+ const lock = {
185
+ schemaVersion: 1,
186
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
187
+ registries: {},
188
+ packages: {}
189
+ };
190
+ const lockPath = join(projectDir, LOCK_FILE);
191
+ await writeFile(lockPath, JSON.stringify(lock, null, 2) + "\n", "utf8");
192
+ filesCreated.push(LOCK_FILE);
193
+ log.success(`Created ${LOCK_FILE}`);
194
+ if (!existsSync(join(projectDir, "agent-contracts.yaml"))) {
195
+ await writeFile(
196
+ join(projectDir, "agent-contracts.yaml"),
197
+ "version: 1\n\nextends: []\n\nvars: {}\n\nsystem:\n id: my-project\n name: My Project Agent Team\n",
198
+ "utf8"
199
+ );
200
+ filesCreated.push("agent-contracts.yaml");
201
+ log.success("Created agent-contracts.yaml");
202
+ }
203
+ if (!existsSync(join(projectDir, "agent-runtime.config.yaml"))) {
204
+ await writeFile(
205
+ join(projectDir, "agent-runtime.config.yaml"),
206
+ `dsl: ./${buildDir}/resolved.agent-contracts.yaml
207
+ generated_dir: ./agent/generated
208
+
209
+ bindings: []
210
+
211
+ active_guardrail_policy: default
212
+ `,
213
+ "utf8"
214
+ );
215
+ filesCreated.push("agent-runtime.config.yaml");
216
+ log.success("Created agent-runtime.config.yaml");
217
+ }
218
+ for (const dir of [modulesDir, "agent_overrides", buildDir, cacheDir]) {
219
+ const full = join(projectDir, dir);
220
+ if (!existsSync(full)) {
221
+ await mkdir(full, { recursive: true });
222
+ dirsCreated.push(dir);
223
+ log.success(`Created ${dir}/`);
224
+ }
225
+ }
226
+ console.log(JSON.stringify({ filesCreated, dirsCreated }, null, 2));
227
+ }
228
+
229
+ // src/lib/commands/add.ts
230
+ import { existsSync as existsSync4 } from "fs";
231
+ import { mkdir as mkdir3, rm, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
232
+ import { join as join5 } from "path";
233
+
234
+ // src/lib/config.ts
235
+ import { readFile, writeFile as writeFile2 } from "fs/promises";
236
+ import { existsSync as existsSync2 } from "fs";
237
+ import { join as join2 } from "path";
238
+ async function readProjectConfig(projectDir) {
239
+ const path = join2(projectDir, CONFIG_FILE);
240
+ if (!existsSync2(path)) {
241
+ throw new Error(`${CONFIG_FILE} not found in ${projectDir}. Run 'agent-pkg init' first.`);
242
+ }
243
+ const raw = await readFile(path, "utf8");
244
+ return JSON.parse(raw);
245
+ }
246
+ async function writeProjectConfig(projectDir, config) {
247
+ const path = join2(projectDir, CONFIG_FILE);
248
+ await writeFile2(path, JSON.stringify(config, null, 2) + "\n", "utf8");
249
+ }
250
+ async function readLockFile(projectDir) {
251
+ const path = join2(projectDir, LOCK_FILE);
252
+ if (!existsSync2(path)) {
253
+ throw new Error(`${LOCK_FILE} not found in ${projectDir}. Run 'agent-pkg add' first.`);
254
+ }
255
+ const raw = await readFile(path, "utf8");
256
+ return JSON.parse(raw);
257
+ }
258
+ async function writeLockFile(projectDir, lock) {
259
+ const path = join2(projectDir, LOCK_FILE);
260
+ await writeFile2(path, JSON.stringify(lock, null, 2) + "\n", "utf8");
261
+ }
262
+ function configExists(projectDir) {
263
+ return existsSync2(join2(projectDir, CONFIG_FILE));
264
+ }
265
+ function lockExists(projectDir) {
266
+ return existsSync2(join2(projectDir, LOCK_FILE));
267
+ }
268
+ async function readPackageManifest(packageDir) {
269
+ const path = join2(packageDir, PACKAGE_MANIFEST_FILE);
270
+ if (!existsSync2(path)) return null;
271
+ const raw = await readFile(path, "utf8");
272
+ return JSON.parse(raw);
273
+ }
274
+ async function readPackageJson(packageDir) {
275
+ const path = join2(packageDir, "package.json");
276
+ if (!existsSync2(path)) return null;
277
+ const raw = await readFile(path, "utf8");
278
+ return JSON.parse(raw);
279
+ }
280
+
281
+ // src/lib/git.ts
282
+ import { execFile as execFileCb, spawn } from "child_process";
283
+ import { existsSync as existsSync3 } from "fs";
284
+ import { mkdir as mkdir2 } from "fs/promises";
285
+ import { homedir } from "os";
286
+ import { join as join3 } from "path";
287
+ function git(args, cwd2) {
288
+ return new Promise((resolve2, reject) => {
289
+ execFileCb("git", args, { cwd: cwd2, maxBuffer: 10 * 1024 * 1024 }, (err, stdout, stderr) => {
290
+ if (err) {
291
+ const msg = stderr?.trim() || err.message;
292
+ reject(new Error(`git ${args.join(" ")} failed: ${msg}`));
293
+ return;
294
+ }
295
+ resolve2(stdout.trim());
296
+ });
297
+ });
298
+ }
299
+ function getCacheBaseDir() {
300
+ return join3(homedir(), ".cache", "agent-pkg", "repos");
301
+ }
302
+ function getRepoCacheDir(owner, repo) {
303
+ return join3(getCacheBaseDir(), "github.com", owner, repo);
304
+ }
305
+ function repoUrl(owner, repo) {
306
+ return `https://github.com/${owner}/${repo}.git`;
307
+ }
308
+ async function ensureCloned(owner, repo) {
309
+ const dir = getRepoCacheDir(owner, repo);
310
+ if (existsSync3(join3(dir, "HEAD"))) {
311
+ log.debug(`Cache hit: ${dir}`);
312
+ await fetchTags(dir);
313
+ return dir;
314
+ }
315
+ const parent = join3(dir, "..");
316
+ await mkdir2(parent, { recursive: true });
317
+ const url = repoUrl(owner, repo);
318
+ log.step(`Cloning ${url}`);
319
+ await git(["clone", "--bare", url, dir]);
320
+ return dir;
321
+ }
322
+ async function fetchTags(repoPath) {
323
+ log.debug(`Fetching tags in ${repoPath}`);
324
+ await git(["fetch", "--tags", "--prune", "--force"], repoPath);
325
+ }
326
+ async function resolveTag(repoPath, tag) {
327
+ log.debug(`Resolving tag: ${tag}`);
328
+ return git(["rev-parse", `${tag}^{commit}`], repoPath);
329
+ }
330
+ async function listTagsForPackage(repoPath, packageName) {
331
+ const prefix = `${packageName}/v`;
332
+ const output = await git(["tag", "--list", `${prefix}*`], repoPath);
333
+ if (!output) return [];
334
+ return output.split("\n").filter((t) => t.startsWith(prefix)).sort();
335
+ }
336
+ async function extractPackageSimple(repoPath, tag, packagePath, destDir) {
337
+ log.debug(`Extracting ${packagePath} at ${tag} \u2192 ${destDir}`);
338
+ await mkdir2(destDir, { recursive: true });
339
+ const commit = await resolveTag(repoPath, tag);
340
+ const stripCount = packagePath.split("/").length;
341
+ return new Promise((resolve2, reject) => {
342
+ const gitProc = spawn(
343
+ "git",
344
+ ["archive", "--format=tar", commit, "--", packagePath],
345
+ { cwd: repoPath, stdio: ["ignore", "pipe", "pipe"] }
346
+ );
347
+ const tarProc = spawn(
348
+ "tar",
349
+ ["xf", "-", "--strip-components", String(stripCount), "-C", destDir],
350
+ { stdio: ["pipe", "pipe", "pipe"] }
351
+ );
352
+ gitProc.stdout.pipe(tarProc.stdin);
353
+ let gitErr = "";
354
+ let tarErr = "";
355
+ gitProc.stderr.on("data", (d) => {
356
+ gitErr += d.toString();
357
+ });
358
+ tarProc.stderr.on("data", (d) => {
359
+ tarErr += d.toString();
360
+ });
361
+ gitProc.on("error", reject);
362
+ tarProc.on("error", reject);
363
+ tarProc.on("close", (code) => {
364
+ if (code === 0) resolve2();
365
+ else reject(new Error(`tar failed (code ${code}): ${tarErr || gitErr}`));
366
+ });
367
+ });
368
+ }
369
+ async function createTag(cwd2, tag) {
370
+ await git(["tag", tag], cwd2);
371
+ }
372
+ async function pushTag(cwd2, tag, remote = "origin") {
373
+ await git(["push", remote, tag], cwd2);
374
+ }
375
+ async function getCurrentCommit(cwd2) {
376
+ return git(["rev-parse", "HEAD"], cwd2);
377
+ }
378
+
379
+ // src/lib/hash.ts
380
+ import { createHash } from "crypto";
381
+ import { readFile as readFile2, readdir } from "fs/promises";
382
+ import { join as join4, relative } from "path";
383
+ async function hashDirectory(dirPath) {
384
+ const files = await collectFiles(dirPath);
385
+ files.sort();
386
+ const hash = createHash("sha256");
387
+ for (const file of files) {
388
+ const rel = relative(dirPath, file);
389
+ hash.update(rel);
390
+ const content = await readFile2(file);
391
+ hash.update(content);
392
+ }
393
+ return `sha256:${hash.digest("hex")}`;
394
+ }
395
+ async function collectFiles(dir) {
396
+ const results = [];
397
+ const entries = await readdir(dir, { withFileTypes: true });
398
+ for (const entry of entries) {
399
+ const full = join4(dir, entry.name);
400
+ if (entry.isDirectory()) {
401
+ results.push(...await collectFiles(full));
402
+ } else if (entry.isFile()) {
403
+ results.push(full);
404
+ }
405
+ }
406
+ return results;
407
+ }
408
+ function hashString(content) {
409
+ return `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`;
410
+ }
411
+
412
+ // src/lib/commands/add.ts
413
+ async function runAdd(input, projectDir) {
414
+ const config = await readProjectConfig(projectDir);
415
+ const spec = parsePackageSpec(input.packageSpec);
416
+ if (!spec.version) {
417
+ throw new Error(`Version is required. Use: agent-pkg add ${spec.name}@<version>`);
418
+ }
419
+ const packageName = input.alias || spec.name;
420
+ let registry;
421
+ let packagePath;
422
+ if (spec.owner && spec.repo) {
423
+ registry = { type: "github", owner: spec.owner, repo: spec.repo };
424
+ packagePath = spec.path || `packages/${spec.name}`;
425
+ } else {
426
+ const registryName2 = input.registry || "default";
427
+ registry = config.registries[registryName2];
428
+ if (!registry) {
429
+ throw new Error(
430
+ `Registry "${registryName2}" not found. Available: ${Object.keys(config.registries).join(", ") || "(none \u2014 run init with --registry)"}`
431
+ );
432
+ }
433
+ const root = registry.packageRoot || "packages";
434
+ packagePath = `${root}/${spec.name}`;
435
+ }
436
+ const tagFormat = registry.tagFormat || "{package}/v{version}";
437
+ const tag = buildTag(spec.name, spec.version, tagFormat);
438
+ log.step(`Resolving ${spec.name}@${spec.version} (tag: ${tag})`);
439
+ const repoDir = await ensureCloned(registry.owner, registry.repo);
440
+ const commit = await resolveTag(repoDir, tag);
441
+ log.step(`Resolved commit: ${commit.slice(0, 12)}`);
442
+ const modulesDir = config.install.modulesDir;
443
+ const installDir = join5(projectDir, modulesDir, packageName);
444
+ if (existsSync4(installDir)) {
445
+ await rm(installDir, { recursive: true, force: true });
446
+ }
447
+ await mkdir3(installDir, { recursive: true });
448
+ log.step(`Extracting ${packagePath} \u2192 ${modulesDir}/${packageName}`);
449
+ await extractPackageSimple(repoDir, tag, packagePath, installDir);
450
+ const contentHash = await hashDirectory(installDir);
451
+ log.debug(`Content hash: ${contentHash}`);
452
+ const registryName = input.registry || "default";
453
+ config.packages[packageName] = {
454
+ registry: registryName,
455
+ path: packagePath,
456
+ version: spec.version
457
+ };
458
+ if (!config.registries[registryName]) {
459
+ config.registries[registryName] = {
460
+ type: "github",
461
+ owner: registry.owner,
462
+ repo: registry.repo,
463
+ packageRoot: registry.packageRoot,
464
+ tagFormat: registry.tagFormat
465
+ };
466
+ }
467
+ await writeProjectConfig(projectDir, config);
468
+ log.success(`Updated ${config} with ${packageName}@${spec.version}`);
469
+ let lock;
470
+ try {
471
+ lock = await readLockFile(projectDir);
472
+ } catch {
473
+ lock = {
474
+ schemaVersion: 1,
475
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
476
+ registries: {},
477
+ packages: {}
478
+ };
479
+ }
480
+ lock.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
481
+ lock.registries[registryName] = {
482
+ type: "github",
483
+ owner: registry.owner,
484
+ repo: registry.repo,
485
+ url: `https://github.com/${registry.owner}/${registry.repo}.git`
486
+ };
487
+ lock.packages[packageName] = {
488
+ registry: registryName,
489
+ path: packagePath,
490
+ version: spec.version,
491
+ tag,
492
+ commit,
493
+ contentHash,
494
+ installedTo: `${modulesDir}/${packageName}`,
495
+ entrypoint: `${modulesDir}/${packageName}/agent-contracts.yaml`
496
+ };
497
+ await writeLockFile(projectDir, lock);
498
+ log.success("Updated lock file");
499
+ await updateExtendsInYaml(projectDir, modulesDir, packageName);
500
+ const result = {
501
+ package: packageName,
502
+ version: spec.version,
503
+ tag,
504
+ commit,
505
+ installedTo: `${modulesDir}/${packageName}`,
506
+ materialized: false
507
+ };
508
+ log.success(`Added ${packageName}@${spec.version}`);
509
+ console.log(JSON.stringify(result, null, 2));
510
+ }
511
+ async function updateExtendsInYaml(projectDir, modulesDir, packageName) {
512
+ const yamlPath = join5(projectDir, "agent-contracts.yaml");
513
+ if (!existsSync4(yamlPath)) return;
514
+ const content = await readFile3(yamlPath, "utf8");
515
+ const extendEntry = `./${modulesDir}/${packageName}/agent-contracts.yaml`;
516
+ if (content.includes(extendEntry)) return;
517
+ const { parse, stringify } = await import("yaml");
518
+ const doc = parse(content);
519
+ if (!doc.extends) doc.extends = [];
520
+ if (Array.isArray(doc.extends) && !doc.extends.includes(extendEntry)) {
521
+ doc.extends.push(extendEntry);
522
+ }
523
+ await writeFile3(yamlPath, stringify(doc, { lineWidth: 0 }), "utf8");
524
+ log.success(`Added extends entry: ${extendEntry}`);
525
+ }
526
+
527
+ // src/lib/commands/sync.ts
528
+ import { existsSync as existsSync5 } from "fs";
529
+ import { mkdir as mkdir4, rm as rm2 } from "fs/promises";
530
+ import { join as join6 } from "path";
531
+ async function runSync(input, projectDir) {
532
+ const config = await readProjectConfig(projectDir);
533
+ const lock = await readLockFile(projectDir);
534
+ const results = [];
535
+ let hasDrift = false;
536
+ for (const [name, entry] of Object.entries(lock.packages)) {
537
+ const regEntry = lock.registries[entry.registry];
538
+ if (!regEntry) {
539
+ throw new Error(`Registry "${entry.registry}" referenced by package "${name}" not found in lock file`);
540
+ }
541
+ const installDir = join6(projectDir, entry.installedTo);
542
+ let currentHash = null;
543
+ if (existsSync5(installDir)) {
544
+ currentHash = await hashDirectory(installDir);
545
+ }
546
+ if (currentHash === entry.contentHash) {
547
+ log.success(`${name}@${entry.version} \u2014 up-to-date`);
548
+ results.push({ name, version: entry.version, status: "up-to-date" });
549
+ continue;
550
+ }
551
+ if (input.check) {
552
+ const expected = entry.contentHash;
553
+ log.error(`${name}@${entry.version} \u2014 drift detected (expected ${expected}, got ${currentHash || "missing"})`);
554
+ results.push({ name, version: entry.version, status: "hash-mismatch" });
555
+ hasDrift = true;
556
+ continue;
557
+ }
558
+ log.step(`Restoring ${name}@${entry.version}`);
559
+ const repoDir = await ensureCloned(regEntry.owner, regEntry.repo);
560
+ if (existsSync5(installDir)) {
561
+ await rm2(installDir, { recursive: true, force: true });
562
+ }
563
+ await mkdir4(installDir, { recursive: true });
564
+ await extractPackageSimple(repoDir, entry.tag, entry.path, installDir);
565
+ const newHash = await hashDirectory(installDir);
566
+ if (newHash !== entry.contentHash) {
567
+ log.warn(`${name}: restored hash ${newHash} differs from lock ${entry.contentHash}`);
568
+ results.push({ name, version: entry.version, status: "hash-mismatch" });
569
+ hasDrift = true;
570
+ } else {
571
+ log.success(`${name}@${entry.version} \u2014 restored`);
572
+ results.push({ name, version: entry.version, status: "restored" });
573
+ }
574
+ }
575
+ const result = {
576
+ packages: results,
577
+ checkMode: !!input.check,
578
+ hasDrift
579
+ };
580
+ console.log(JSON.stringify(result, null, 2));
581
+ if (input.check && hasDrift) {
582
+ process.exit(1);
583
+ }
584
+ }
585
+
586
+ // src/lib/commands/update.ts
587
+ import { existsSync as existsSync6 } from "fs";
588
+ import { mkdir as mkdir5, rm as rm3 } from "fs/promises";
589
+ import { join as join7 } from "path";
590
+ async function runUpdate(input, projectDir) {
591
+ const config = await readProjectConfig(projectDir);
592
+ const lock = await readLockFile(projectDir);
593
+ let targetPackages;
594
+ let targetVersion;
595
+ if (input.packageSpec) {
596
+ const spec = parsePackageSpec(input.packageSpec);
597
+ targetVersion = spec.version;
598
+ if (!config.packages[spec.name]) {
599
+ throw new Error(`Package "${spec.name}" not found in ${Object.keys(config.packages).join(", ")}`);
600
+ }
601
+ targetPackages = [spec.name];
602
+ } else {
603
+ targetPackages = Object.keys(config.packages);
604
+ }
605
+ const updates = [];
606
+ for (const name of targetPackages) {
607
+ const pkg = config.packages[name];
608
+ const registryName = pkg.registry || "default";
609
+ const registry = config.registries[registryName];
610
+ if (!registry) {
611
+ log.warn(`Registry "${registryName}" not found for package "${name}", skipping`);
612
+ continue;
613
+ }
614
+ const repoDir = await ensureCloned(registry.owner, registry.repo);
615
+ const tags = await listTagsForPackage(repoDir, name);
616
+ const versions = tags.map((t) => parseTagVersion(t, name)).filter((v) => v !== null).map((v) => ({ raw: v, parts: parseSemver(v) })).filter((v) => v.parts !== null).sort((a, b) => compareSemver(a.parts, b.parts));
617
+ const currentParts = parseSemver(pkg.version);
618
+ if (!currentParts) {
619
+ log.warn(`Cannot parse current version "${pkg.version}" for ${name}`);
620
+ continue;
621
+ }
622
+ let candidates;
623
+ if (targetVersion) {
624
+ candidates = versions.filter((v) => v.raw === targetVersion);
625
+ } else if (input.patch) {
626
+ candidates = versions.filter(
627
+ (v) => v.parts.major === currentParts.major && v.parts.minor === currentParts.minor && compareSemver(v.parts, currentParts) > 0
628
+ );
629
+ } else if (input.minor) {
630
+ candidates = versions.filter(
631
+ (v) => v.parts.major === currentParts.major && compareSemver(v.parts, currentParts) > 0
632
+ );
633
+ } else {
634
+ candidates = versions.filter((v) => compareSemver(v.parts, currentParts) > 0);
635
+ }
636
+ if (candidates.length === 0) {
637
+ log.info(`${name}@${pkg.version} \u2014 already at latest`);
638
+ continue;
639
+ }
640
+ const latest = candidates[candidates.length - 1];
641
+ const hasBreaking = latest.parts.major > currentParts.major;
642
+ updates.push({
643
+ package: name,
644
+ fromVersion: pkg.version,
645
+ toVersion: latest.raw,
646
+ hasBreakingChanges: hasBreaking
647
+ });
648
+ }
649
+ if (updates.length === 0) {
650
+ log.info("All packages are up to date");
651
+ console.log(JSON.stringify({ updates: [], dryRun: input.dryRun }, null, 2));
652
+ return;
653
+ }
654
+ for (const u of updates) {
655
+ const breaking = u.hasBreakingChanges ? " (BREAKING)" : "";
656
+ log.info(`${u.package}: ${u.fromVersion} \u2192 ${u.toVersion}${breaking}`);
657
+ }
658
+ if (input.dryRun) {
659
+ console.log(JSON.stringify({ updates, dryRun: true }, null, 2));
660
+ return;
661
+ }
662
+ for (const u of updates) {
663
+ const pkg = config.packages[u.package];
664
+ const registryName = pkg.registry || "default";
665
+ const registry = config.registries[registryName];
666
+ const repoDir = await ensureCloned(registry.owner, registry.repo);
667
+ const tag = buildTag(u.package, u.toVersion, registry.tagFormat);
668
+ const commit = await resolveTag(repoDir, tag);
669
+ const installDir = join7(projectDir, config.install.modulesDir, u.package);
670
+ if (existsSync6(installDir)) {
671
+ await rm3(installDir, { recursive: true, force: true });
672
+ }
673
+ await mkdir5(installDir, { recursive: true });
674
+ await extractPackageSimple(repoDir, tag, pkg.path, installDir);
675
+ const contentHash = await hashDirectory(installDir);
676
+ config.packages[u.package].version = u.toVersion;
677
+ lock.packages[u.package] = {
678
+ ...lock.packages[u.package],
679
+ version: u.toVersion,
680
+ tag,
681
+ commit,
682
+ contentHash
683
+ };
684
+ log.success(`Updated ${u.package} to ${u.toVersion}`);
685
+ }
686
+ lock.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
687
+ await writeProjectConfig(projectDir, config);
688
+ await writeLockFile(projectDir, lock);
689
+ console.log(JSON.stringify({ updates, dryRun: false }, null, 2));
690
+ }
691
+ function parseSemver(v) {
692
+ const m = v.match(/^(\d+)\.(\d+)\.(\d+)/);
693
+ if (!m) return null;
694
+ return { major: +m[1], minor: +m[2], patch: +m[3] };
695
+ }
696
+ function compareSemver(a, b) {
697
+ if (a.major !== b.major) return a.major - b.major;
698
+ if (a.minor !== b.minor) return a.minor - b.minor;
699
+ return a.patch - b.patch;
700
+ }
701
+
702
+ // src/lib/commands/diff.ts
703
+ import { existsSync as existsSync7 } from "fs";
704
+ import { readFile as readFile4, mkdtemp, rm as rm4 } from "fs/promises";
705
+ import { join as join8 } from "path";
706
+ import { tmpdir } from "os";
707
+ async function runDiff(input, projectDir) {
708
+ const config = await readProjectConfig(projectDir);
709
+ const lock = await readLockFile(projectDir);
710
+ const spec = parsePackageSpec(input.packageSpec);
711
+ const name = spec.name;
712
+ if (!config.packages[name]) {
713
+ throw new Error(`Package "${name}" not found. Available: ${Object.keys(config.packages).join(", ")}`);
714
+ }
715
+ const pkg = config.packages[name];
716
+ const registry = resolveRegistryForPackage(config, name);
717
+ const repoDir = await ensureCloned(registry.owner, registry.repo);
718
+ let targetVersion;
719
+ if (spec.version) {
720
+ targetVersion = spec.version;
721
+ } else {
722
+ const tags = await listTagsForPackage(repoDir, name);
723
+ const versions = tags.map((t) => parseTagVersion(t, name)).filter((v) => v !== null);
724
+ if (versions.length === 0) {
725
+ throw new Error(`No versions found for ${name}`);
726
+ }
727
+ targetVersion = versions[versions.length - 1];
728
+ }
729
+ if (targetVersion === pkg.version) {
730
+ log.info(`${name} is already at ${targetVersion}`);
731
+ return;
732
+ }
733
+ log.step(`Comparing ${name} ${pkg.version} \u2192 ${targetVersion}`);
734
+ const targetTag = buildTag(name, targetVersion, registry.tagFormat);
735
+ const tmpDir = await mkdtemp(join8(tmpdir(), "agent-pkg-diff-"));
736
+ try {
737
+ const targetDir = join8(tmpDir, "target");
738
+ await extractPackageSimple(repoDir, targetTag, pkg.path, targetDir);
739
+ const currentDir = join8(projectDir, config.install.modulesDir, name);
740
+ if (!existsSync7(currentDir)) {
741
+ throw new Error(`Current package not installed at ${currentDir}. Run sync first.`);
742
+ }
743
+ const currentDsl = await loadYamlSafe(join8(currentDir, "agent-contracts.yaml"));
744
+ const targetDsl = await loadYamlSafe(join8(targetDir, "agent-contracts.yaml"));
745
+ const changes = computeDslDiff(currentDsl, targetDsl);
746
+ if (input.format === "json") {
747
+ console.log(JSON.stringify({
748
+ package: name,
749
+ fromVersion: pkg.version,
750
+ toVersion: targetVersion,
751
+ changes
752
+ }, null, 2));
753
+ } else {
754
+ printTextDiff(name, pkg.version, targetVersion, changes);
755
+ }
756
+ const hasBreaking = changes.some((c) => c.breaking);
757
+ if (hasBreaking) {
758
+ process.exit(2);
759
+ }
760
+ } finally {
761
+ await rm4(tmpDir, { recursive: true, force: true });
762
+ }
763
+ }
764
+ function computeDslDiff(current, target) {
765
+ const changes = [];
766
+ if (!current || !target) return changes;
767
+ const sections = ["agents", "tasks", "workflows", "guardrails", "handoff_types"];
768
+ for (const section of sections) {
769
+ const cur = current[section] || {};
770
+ const tgt = target[section] || {};
771
+ for (const key of Object.keys(tgt)) {
772
+ if (!(key in cur)) {
773
+ changes.push({ section, type: "added", key });
774
+ } else if (JSON.stringify(cur[key]) !== JSON.stringify(tgt[key])) {
775
+ changes.push({ section, type: "modified", key });
776
+ }
777
+ }
778
+ for (const key of Object.keys(cur)) {
779
+ if (!(key in tgt)) {
780
+ changes.push({ section, type: "removed", key, breaking: true });
781
+ }
782
+ }
783
+ }
784
+ return changes;
785
+ }
786
+ function printTextDiff(name, fromVersion, toVersion, changes) {
787
+ console.log(`${name} ${fromVersion} \u2192 ${toVersion}
788
+ `);
789
+ if (changes.length === 0) {
790
+ console.log(" No semantic changes detected.");
791
+ return;
792
+ }
793
+ const grouped = /* @__PURE__ */ new Map();
794
+ for (const c of changes) {
795
+ const list = grouped.get(c.section) || [];
796
+ list.push(c);
797
+ grouped.set(c.section, list);
798
+ }
799
+ for (const [section, items] of grouped) {
800
+ const label = section.charAt(0).toUpperCase() + section.slice(1);
801
+ console.log(`${label}:`);
802
+ for (const item of items) {
803
+ const breaking = item.breaking ? " BREAKING" : "";
804
+ console.log(` ${item.type} ${item.key}${breaking}`);
805
+ }
806
+ console.log();
807
+ }
808
+ const hasBreaking = changes.some((c) => c.breaking);
809
+ if (hasBreaking) {
810
+ console.log("Risk:\n BREAKING CHANGE detected");
811
+ }
812
+ }
813
+ async function loadYamlSafe(path) {
814
+ if (!existsSync7(path)) return null;
815
+ const { parse } = await import("yaml");
816
+ const content = await readFile4(path, "utf8");
817
+ return parse(content) || {};
818
+ }
819
+
820
+ // src/lib/commands/materialize.ts
821
+ import { existsSync as existsSync8 } from "fs";
822
+ import { mkdir as mkdir6, rm as rm5, readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
823
+ import { join as join9 } from "path";
824
+ import { execFile } from "child_process";
825
+ async function runMaterialize(input, projectDir) {
826
+ const config = await readProjectConfig(projectDir);
827
+ const buildDir = join9(projectDir, config.install.buildDir);
828
+ if (input.clean && existsSync8(buildDir)) {
829
+ await rm5(buildDir, { recursive: true, force: true });
830
+ log.step("Cleaned build directory");
831
+ }
832
+ await mkdir6(buildDir, { recursive: true });
833
+ log.step("Resolving agent-contracts.yaml");
834
+ const yamlPath = join9(projectDir, "agent-contracts.yaml");
835
+ if (!existsSync8(yamlPath)) {
836
+ throw new Error("agent-contracts.yaml not found in project root");
837
+ }
838
+ const { parse, stringify } = await import("yaml");
839
+ const rootDoc = parse(await readFile5(yamlPath, "utf8"));
840
+ const resolved = await resolveExtends(rootDoc, projectDir);
841
+ if (config.vars) {
842
+ resolved.vars = { ...resolved.vars || {}, ...config.vars };
843
+ }
844
+ const resolvedYaml = stringify(resolved, { lineWidth: 0 });
845
+ const resolvedPath = join9(buildDir, "resolved.agent-contracts.yaml");
846
+ await writeFile4(resolvedPath, resolvedYaml, "utf8");
847
+ log.success(`Wrote ${resolvedPath}`);
848
+ const resolvedHash = hashString(resolvedYaml);
849
+ let validated = false;
850
+ let linted = false;
851
+ let generated = false;
852
+ if (config.materialize?.runValidate !== false) {
853
+ validated = await runExternalTool("agent-contracts", ["validate", "-f", resolvedPath], projectDir);
854
+ }
855
+ if (!input.noLint && config.materialize?.runLint !== false) {
856
+ linted = await runExternalTool("agent-contracts", ["lint", "--strict", "-f", resolvedPath], projectDir);
857
+ }
858
+ if (!input.noGenerate && config.materialize?.runRuntimeGenerate !== false) {
859
+ generated = await runExternalTool("agent-runtime", ["generate"], projectDir);
860
+ }
861
+ const buildManifest = {
862
+ resolvedDsl: resolvedPath,
863
+ resolvedDslHash: resolvedHash,
864
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
865
+ packages: Object.keys(config.packages)
866
+ };
867
+ await writeFile4(join9(buildDir, "package-manifest.json"), JSON.stringify(buildManifest, null, 2) + "\n", "utf8");
868
+ const result = {
869
+ resolvedDslPath: resolvedPath,
870
+ resolvedDslHash: resolvedHash,
871
+ validated,
872
+ linted,
873
+ generated
874
+ };
875
+ log.success("Materialize completed");
876
+ console.log(JSON.stringify(result, null, 2));
877
+ }
878
+ async function resolveExtends(doc, baseDir) {
879
+ const extends_ = doc.extends;
880
+ if (!extends_ || extends_.length === 0) return doc;
881
+ const { parse } = await import("yaml");
882
+ let merged = {};
883
+ for (const ext of extends_) {
884
+ const extPath = join9(baseDir, ext);
885
+ if (!existsSync8(extPath)) {
886
+ log.warn(`Extended file not found: ${extPath}`);
887
+ continue;
888
+ }
889
+ const extContent = await readFile5(extPath, "utf8");
890
+ const extDoc = parse(extContent);
891
+ if (extDoc) {
892
+ merged = deepMerge(merged, extDoc);
893
+ }
894
+ }
895
+ const { extends: _removed, ...rest } = doc;
896
+ merged = deepMerge(merged, rest);
897
+ const refs = doc["$refs"];
898
+ if (refs) {
899
+ for (const ref of refs) {
900
+ const refPath = join9(baseDir, ref);
901
+ if (!existsSync8(refPath)) {
902
+ log.warn(`Override file not found: ${refPath}`);
903
+ continue;
904
+ }
905
+ const refContent = await readFile5(refPath, "utf8");
906
+ const refDoc = parse(refContent);
907
+ if (refDoc) {
908
+ merged = deepMerge(merged, refDoc);
909
+ }
910
+ }
911
+ delete merged["$refs"];
912
+ }
913
+ return merged;
914
+ }
915
+ function deepMerge(target, source) {
916
+ const result = { ...target };
917
+ for (const key of Object.keys(source)) {
918
+ const tVal = result[key];
919
+ const sVal = source[key];
920
+ if (isPlainObject(tVal) && isPlainObject(sVal)) {
921
+ result[key] = deepMerge(tVal, sVal);
922
+ } else {
923
+ result[key] = sVal;
924
+ }
925
+ }
926
+ return result;
927
+ }
928
+ function isPlainObject(val) {
929
+ return typeof val === "object" && val !== null && !Array.isArray(val);
930
+ }
931
+ function runExternalTool(cmd, args, cwd2) {
932
+ return new Promise((resolve2) => {
933
+ execFile(cmd, args, { cwd: cwd2 }, (err, stdout, stderr) => {
934
+ if (err) {
935
+ log.warn(`${cmd} ${args.join(" ")} \u2014 skipped (not available or failed)`);
936
+ log.debug(stderr || err.message);
937
+ resolve2(false);
938
+ return;
939
+ }
940
+ if (stdout) log.debug(stdout);
941
+ log.success(`${cmd} ${args.join(" ")} \u2014 ok`);
942
+ resolve2(true);
943
+ });
944
+ });
945
+ }
946
+
947
+ // src/lib/commands/check.ts
948
+ import { existsSync as existsSync9 } from "fs";
949
+ import { join as join10 } from "path";
950
+ async function runCheck(projectDir) {
951
+ const checks = [];
952
+ checks.push(await checkConfigSchema(projectDir));
953
+ checks.push(await checkLockSchema(projectDir));
954
+ checks.push(await checkVersionConsistency(projectDir));
955
+ checks.push(...await checkContentHashes(projectDir));
956
+ const allPassed = checks.every((c) => c.status !== "fail");
957
+ for (const check of checks) {
958
+ const icon = check.status === "pass" ? "\u2713" : check.status === "warn" ? "\u26A0" : "\u2717";
959
+ const msg = check.message ? ` \u2014 ${check.message}` : "";
960
+ console.log(`${icon} ${check.name}${msg}`);
961
+ }
962
+ const result = { checks, allPassed };
963
+ console.log(JSON.stringify(result, null, 2));
964
+ if (!allPassed) {
965
+ process.exit(1);
966
+ }
967
+ }
968
+ async function checkConfigSchema(projectDir) {
969
+ if (!configExists(projectDir)) {
970
+ return { name: "config_exists", status: "fail", message: "agent-pkg.json not found" };
971
+ }
972
+ try {
973
+ const config = await readProjectConfig(projectDir);
974
+ if (config.schemaVersion !== 1) {
975
+ return { name: "config_schema", status: "fail", message: `Unsupported schema version: ${config.schemaVersion}` };
976
+ }
977
+ return { name: "config_schema", status: "pass" };
978
+ } catch (e) {
979
+ return { name: "config_schema", status: "fail", message: e.message };
980
+ }
981
+ }
982
+ async function checkLockSchema(projectDir) {
983
+ if (!lockExists(projectDir)) {
984
+ return { name: "lock_exists", status: "fail", message: "agent-pkg.lock.json not found" };
985
+ }
986
+ try {
987
+ const lock = await readLockFile(projectDir);
988
+ if (lock.schemaVersion !== 1) {
989
+ return { name: "lock_schema", status: "fail", message: `Unsupported schema version: ${lock.schemaVersion}` };
990
+ }
991
+ return { name: "lock_schema", status: "pass" };
992
+ } catch (e) {
993
+ return { name: "lock_schema", status: "fail", message: e.message };
994
+ }
995
+ }
996
+ async function checkVersionConsistency(projectDir) {
997
+ try {
998
+ const config = await readProjectConfig(projectDir);
999
+ const lock = await readLockFile(projectDir);
1000
+ const mismatches = [];
1001
+ for (const [name, pkg] of Object.entries(config.packages)) {
1002
+ const lockPkg = lock.packages[name];
1003
+ if (!lockPkg) {
1004
+ mismatches.push(`${name}: in config but not in lock`);
1005
+ continue;
1006
+ }
1007
+ if (lockPkg.version !== pkg.version) {
1008
+ mismatches.push(`${name}: config=${pkg.version}, lock=${lockPkg.version}`);
1009
+ }
1010
+ }
1011
+ for (const name of Object.keys(lock.packages)) {
1012
+ if (!config.packages[name]) {
1013
+ mismatches.push(`${name}: in lock but not in config`);
1014
+ }
1015
+ }
1016
+ if (mismatches.length > 0) {
1017
+ return {
1018
+ name: "version_consistency",
1019
+ status: "fail",
1020
+ message: mismatches.join("; ")
1021
+ };
1022
+ }
1023
+ return { name: "version_consistency", status: "pass" };
1024
+ } catch (e) {
1025
+ return { name: "version_consistency", status: "fail", message: e.message };
1026
+ }
1027
+ }
1028
+ async function checkContentHashes(projectDir) {
1029
+ const items = [];
1030
+ try {
1031
+ const lock = await readLockFile(projectDir);
1032
+ for (const [name, entry] of Object.entries(lock.packages)) {
1033
+ const installDir = join10(projectDir, entry.installedTo);
1034
+ if (!existsSync9(installDir)) {
1035
+ items.push({
1036
+ name: `content_hash:${name}`,
1037
+ status: "fail",
1038
+ message: `${entry.installedTo} does not exist`
1039
+ });
1040
+ continue;
1041
+ }
1042
+ const actualHash = await hashDirectory(installDir);
1043
+ if (actualHash !== entry.contentHash) {
1044
+ items.push({
1045
+ name: `content_hash:${name}`,
1046
+ status: "fail",
1047
+ message: `Expected ${entry.contentHash}, got ${actualHash}. Do not edit files under agent_modules directly.`
1048
+ });
1049
+ } else {
1050
+ items.push({ name: `content_hash:${name}`, status: "pass" });
1051
+ }
1052
+ }
1053
+ } catch (e) {
1054
+ items.push({ name: "content_hash", status: "fail", message: e.message });
1055
+ }
1056
+ return items;
1057
+ }
1058
+
1059
+ // src/lib/commands/publish.ts
1060
+ import { existsSync as existsSync10 } from "fs";
1061
+ import { join as join11 } from "path";
1062
+ async function runPublish(input, projectDir) {
1063
+ const packageDir = join11(projectDir, input.path);
1064
+ if (!existsSync10(packageDir)) {
1065
+ throw new Error(`Package directory not found: ${input.path}`);
1066
+ }
1067
+ const pkgJson = await readPackageJson(packageDir);
1068
+ const manifest = await readPackageManifest(packageDir);
1069
+ const pkgJsonVersion = pkgJson?.version;
1070
+ const manifestVersion = manifest?.version;
1071
+ let version;
1072
+ if (input.version) {
1073
+ version = input.version;
1074
+ } else if (manifestVersion) {
1075
+ version = manifestVersion;
1076
+ } else if (pkgJsonVersion) {
1077
+ version = pkgJsonVersion;
1078
+ } else {
1079
+ throw new Error("Cannot determine version. Specify --version or set version in package.json / " + PACKAGE_MANIFEST_FILE);
1080
+ }
1081
+ if (pkgJsonVersion && manifestVersion && pkgJsonVersion !== manifestVersion) {
1082
+ throw new Error(
1083
+ `Version mismatch: package.json=${pkgJsonVersion}, ${PACKAGE_MANIFEST_FILE}=${manifestVersion}`
1084
+ );
1085
+ }
1086
+ const packageName = manifest?.id || pkgJson?.name?.split("/").pop() || input.path.split("/").pop();
1087
+ const tag = `${packageName}/v${version}`;
1088
+ log.step(`Publishing ${packageName}@${version} (tag: ${tag})`);
1089
+ if (!input.tagOnly) {
1090
+ const changelogPath = join11(packageDir, "CHANGELOG.md");
1091
+ if (!existsSync10(changelogPath)) {
1092
+ log.warn("CHANGELOG.md not found");
1093
+ }
1094
+ const contentHash2 = await hashDirectory(packageDir);
1095
+ log.debug(`Content hash: ${contentHash2}`);
1096
+ if (input.dryRun) {
1097
+ const result2 = {
1098
+ package: packageName,
1099
+ version,
1100
+ tag,
1101
+ contentHash: contentHash2,
1102
+ pushed: false
1103
+ };
1104
+ log.info("Dry run \u2014 no changes made");
1105
+ console.log(JSON.stringify(result2, null, 2));
1106
+ return;
1107
+ }
1108
+ }
1109
+ const commit = await getCurrentCommit(projectDir);
1110
+ if (input.dryRun) {
1111
+ const result2 = {
1112
+ package: packageName,
1113
+ version,
1114
+ tag,
1115
+ commit,
1116
+ pushed: false
1117
+ };
1118
+ log.info("Dry run \u2014 no changes made");
1119
+ console.log(JSON.stringify(result2, null, 2));
1120
+ return;
1121
+ }
1122
+ await createTag(projectDir, tag);
1123
+ log.success(`Created tag: ${tag}`);
1124
+ let pushed = false;
1125
+ if (!input.noPush) {
1126
+ await pushTag(projectDir, tag);
1127
+ pushed = true;
1128
+ log.success(`Pushed tag: ${tag}`);
1129
+ }
1130
+ const contentHash = await hashDirectory(packageDir);
1131
+ const result = {
1132
+ package: packageName,
1133
+ version,
1134
+ tag,
1135
+ commit,
1136
+ contentHash,
1137
+ pushed
1138
+ };
1139
+ log.success(`Published ${packageName}@${version}`);
1140
+ console.log(JSON.stringify(result, null, 2));
1141
+ }
1142
+
39
1143
  // src/cli/index.ts
40
- var notImplemented = () => {
41
- console.error("Not implemented yet");
1144
+ function setupGlobals(globals) {
1145
+ if (globals.verbose) setVerbose(true);
1146
+ }
1147
+ function handleError(err) {
1148
+ const msg = err instanceof Error ? err.message : String(err);
1149
+ console.error(`\u2717 ${msg}`);
42
1150
  process.exit(1);
43
- };
1151
+ }
1152
+ var cwd = process.cwd();
44
1153
  var handlers = {
45
- init: async (_opts, _globals) => notImplemented(),
46
- add: async (_pkg, _opts, _globals) => notImplemented(),
47
- sync: async (_opts, _globals) => notImplemented(),
48
- update: async (_pkg, _opts, _globals) => notImplemented(),
49
- diff: async (_pkg, _opts, _globals) => notImplemented(),
50
- materialize: async (_opts, _globals) => notImplemented(),
51
- check: async (_globals) => notImplemented(),
52
- publish: async (_path, _opts, _globals) => notImplemented()
1154
+ init: async (opts, globals) => {
1155
+ setupGlobals(globals);
1156
+ await runInit(opts, cwd).catch(handleError);
1157
+ },
1158
+ add: async (pkg, opts, globals) => {
1159
+ setupGlobals(globals);
1160
+ if (!pkg) {
1161
+ console.error("\u2717 Package specifier is required. Usage: agent-pkg add <name>@<version>");
1162
+ process.exit(1);
1163
+ }
1164
+ await runAdd({
1165
+ packageSpec: pkg,
1166
+ registry: opts.registry,
1167
+ alias: opts.alias,
1168
+ noMaterialize: opts.noMaterialize
1169
+ }, cwd).catch(handleError);
1170
+ },
1171
+ sync: async (opts, globals) => {
1172
+ setupGlobals(globals);
1173
+ await runSync({ check: opts.check }, cwd).catch(handleError);
1174
+ },
1175
+ update: async (pkg, opts, globals) => {
1176
+ setupGlobals(globals);
1177
+ await runUpdate({
1178
+ packageSpec: pkg || void 0,
1179
+ latest: opts.latest,
1180
+ minor: opts.minor,
1181
+ patch: opts.patch,
1182
+ yes: opts.yes,
1183
+ dryRun: opts.dryRun
1184
+ }, cwd).catch(handleError);
1185
+ },
1186
+ diff: async (pkg, opts, globals) => {
1187
+ setupGlobals(globals);
1188
+ if (!pkg) {
1189
+ console.error("\u2717 Package specifier is required. Usage: agent-pkg diff <name>[@<version>]");
1190
+ process.exit(1);
1191
+ }
1192
+ await runDiff({
1193
+ packageSpec: pkg,
1194
+ format: opts.format
1195
+ }, cwd).catch(handleError);
1196
+ },
1197
+ materialize: async (opts, globals) => {
1198
+ setupGlobals(globals);
1199
+ await runMaterialize({
1200
+ noGenerate: opts.noGenerate,
1201
+ noLint: opts.noLint,
1202
+ clean: opts.clean
1203
+ }, cwd).catch(handleError);
1204
+ },
1205
+ check: async (globals) => {
1206
+ setupGlobals(globals);
1207
+ await runCheck(cwd).catch(handleError);
1208
+ },
1209
+ publish: async (path, opts, globals) => {
1210
+ setupGlobals(globals);
1211
+ if (!path) {
1212
+ console.error("\u2717 Package path is required. Usage: agent-pkg publish <path>");
1213
+ process.exit(1);
1214
+ }
1215
+ await runPublish({
1216
+ path,
1217
+ version: opts.version,
1218
+ dryRun: opts.dryRun,
1219
+ tagOnly: opts.tagOnly,
1220
+ noPush: opts.noPush
1221
+ }, cwd).catch(handleError);
1222
+ }
53
1223
  };
54
1224
  var program = createProgram(handlers, VERSION);
55
1225
  program.parse();