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