@ipab/cli 0.1.0-rc.7 → 0.1.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +70 -30
  2. package/dist/app-authoring.d.ts.map +1 -1
  3. package/dist/app-authoring.js +2 -44
  4. package/dist/app-authoring.js.map +1 -1
  5. package/dist/app-prebuild.d.ts +18 -0
  6. package/dist/app-prebuild.d.ts.map +1 -1
  7. package/dist/app-prebuild.js +46 -0
  8. package/dist/app-prebuild.js.map +1 -1
  9. package/dist/builtins/skill.ipab.car +0 -0
  10. package/dist/bundled-skills.d.ts +14 -0
  11. package/dist/bundled-skills.d.ts.map +1 -0
  12. package/dist/bundled-skills.js +34 -0
  13. package/dist/bundled-skills.js.map +1 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +309 -157
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +1 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +9 -4
  20. package/dist/config.js.map +1 -1
  21. package/dist/context.d.ts +4 -0
  22. package/dist/context.d.ts.map +1 -1
  23. package/dist/context.js +11 -2
  24. package/dist/context.js.map +1 -1
  25. package/dist/daemon.d.ts +4 -0
  26. package/dist/daemon.d.ts.map +1 -0
  27. package/dist/daemon.js +200 -0
  28. package/dist/daemon.js.map +1 -0
  29. package/dist/doctor.d.ts +2 -0
  30. package/dist/doctor.d.ts.map +1 -1
  31. package/dist/doctor.js +18 -4
  32. package/dist/doctor.js.map +1 -1
  33. package/dist/errors.d.ts +1 -8
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +1 -20
  36. package/dist/errors.js.map +1 -1
  37. package/dist/host-error.d.ts +9 -0
  38. package/dist/host-error.d.ts.map +1 -0
  39. package/dist/host-error.js +21 -0
  40. package/dist/host-error.js.map +1 -0
  41. package/dist/ipc.d.ts.map +1 -1
  42. package/dist/ipc.js +17 -0
  43. package/dist/ipc.js.map +1 -1
  44. package/dist/kubo-install.js +1 -1
  45. package/dist/kubo-install.js.map +1 -1
  46. package/dist/kubo-peers.d.ts.map +1 -1
  47. package/dist/kubo-peers.js +2 -1
  48. package/dist/kubo-peers.js.map +1 -1
  49. package/dist/kubo-topology.d.ts +19 -0
  50. package/dist/kubo-topology.d.ts.map +1 -0
  51. package/dist/kubo-topology.js +105 -0
  52. package/dist/kubo-topology.js.map +1 -0
  53. package/dist/kubo.d.ts +10 -0
  54. package/dist/kubo.d.ts.map +1 -1
  55. package/dist/kubo.js +96 -15
  56. package/dist/kubo.js.map +1 -1
  57. package/dist/skill-source.d.ts +4 -0
  58. package/dist/skill-source.d.ts.map +1 -1
  59. package/dist/skill-source.js +14 -2
  60. package/dist/skill-source.js.map +1 -1
  61. package/dist/skills.d.ts +18 -1
  62. package/dist/skills.d.ts.map +1 -1
  63. package/dist/skills.js +137 -39
  64. package/dist/skills.js.map +1 -1
  65. package/dist/space-path.d.ts +3 -0
  66. package/dist/space-path.d.ts.map +1 -0
  67. package/dist/space-path.js +17 -0
  68. package/dist/space-path.js.map +1 -0
  69. package/dist/space.d.ts +1 -2
  70. package/dist/space.d.ts.map +1 -1
  71. package/dist/space.js +2 -15
  72. package/dist/space.js.map +1 -1
  73. package/dist/state-storage.js +1 -1
  74. package/dist/state-storage.js.map +1 -1
  75. package/dist/state.d.ts +2 -0
  76. package/dist/state.d.ts.map +1 -1
  77. package/dist/state.js +31 -12
  78. package/dist/state.js.map +1 -1
  79. package/dist/swarm-files.d.ts +1 -1
  80. package/dist/swarm-files.d.ts.map +1 -1
  81. package/dist/swarm-files.js +10 -4
  82. package/dist/swarm-files.js.map +1 -1
  83. package/dist/swarm-meta.d.ts +1 -4
  84. package/dist/swarm-meta.d.ts.map +1 -1
  85. package/dist/swarm-meta.js +3 -34
  86. package/dist/swarm-meta.js.map +1 -1
  87. package/dist/swarm-observations.d.ts +40 -0
  88. package/dist/swarm-observations.d.ts.map +1 -0
  89. package/dist/swarm-observations.js +262 -0
  90. package/dist/swarm-observations.js.map +1 -0
  91. package/dist/swarm.d.ts +121 -6
  92. package/dist/swarm.d.ts.map +1 -1
  93. package/dist/swarm.js +672 -81
  94. package/dist/swarm.js.map +1 -1
  95. package/package.json +4 -4
  96. package/src/app-authoring.ts +12 -53
  97. package/src/app-prebuild.ts +61 -0
  98. package/src/bundled-skills.ts +60 -0
  99. package/src/cli.ts +398 -195
  100. package/src/config.ts +12 -4
  101. package/src/context.ts +15 -2
  102. package/src/daemon.ts +237 -0
  103. package/src/doctor.ts +42 -5
  104. package/src/errors.ts +1 -25
  105. package/src/host-error.ts +26 -0
  106. package/src/ipc.ts +19 -0
  107. package/src/kubo-install.ts +1 -1
  108. package/src/kubo-peers.ts +2 -3
  109. package/src/kubo-topology.ts +135 -0
  110. package/src/kubo.ts +134 -25
  111. package/src/skill-source.ts +16 -2
  112. package/src/skills.ts +195 -53
  113. package/src/space-path.ts +30 -0
  114. package/src/space.ts +2 -28
  115. package/src/state-storage.ts +1 -1
  116. package/src/state.ts +37 -12
  117. package/src/swarm-files.ts +8 -3
  118. package/src/swarm-meta.ts +15 -34
  119. package/src/swarm-observations.ts +374 -0
  120. package/src/swarm.ts +953 -92
package/src/skills.ts CHANGED
@@ -17,7 +17,8 @@ import { relativePath } from "./space.js";
17
17
  import { swarmUrl } from "./config.js";
18
18
  import type { AgentInfo } from "skills";
19
19
  import { HostError, message, object } from "./errors.js";
20
- import { nodeError } from "./authoring.js";
20
+ import { nodeError, scaffoldFiles } from "./authoring.js";
21
+ import type { bundledSkillSource } from "./skill-source.js";
21
22
  import { getBundle } from "./get.js";
22
23
  import {
23
24
  privateDirectory,
@@ -28,6 +29,7 @@ import {
28
29
  import { swarmSkills, type SharedSkill, type SwarmContext } from "./swarm.js";
29
30
 
30
31
  export const skillsInstaller = "skills@1.9.1";
32
+ export const bundledSkillOrigin = "bundled:ipab";
31
33
  type Fingerprint = Record<string, string>;
32
34
  interface Installation extends SharedSkill {
33
35
  swarm: string;
@@ -454,7 +456,10 @@ export function parseSkillsLedger(value: unknown): Ledger {
454
456
  "Invalid Skills attribution identity/path; refusing to overwrite installs.",
455
457
  );
456
458
  const installation: Installation = {
457
- swarm: swarmUrl(ledgerString(item.swarm, "Swarm URL")),
459
+ swarm:
460
+ item.swarm === bundledSkillOrigin
461
+ ? bundledSkillOrigin
462
+ : swarmUrl(ledgerString(item.swarm, "Swarm URL")),
458
463
  path,
459
464
  identity,
460
465
  name: relativePath(ledgerString(item.name, "shared Name", 256)),
@@ -514,6 +519,7 @@ export interface SkillsOptions {
514
519
  sync: boolean;
515
520
  names: readonly string[];
516
521
  agents: readonly string[];
522
+ overrideExisting: boolean;
517
523
  dryRun: boolean;
518
524
  yes: boolean;
519
525
  tty: boolean;
@@ -576,8 +582,91 @@ export interface SkillsResult {
576
582
  }[];
577
583
  ok: boolean;
578
584
  }
585
+ export async function inspectBundledSkill(
586
+ source: Awaited<ReturnType<typeof bundledSkillSource>>,
587
+ port: SkillsPort,
588
+ ) {
589
+ const catalog = await port.catalog();
590
+ const supported = catalog.supported.filter(
591
+ (agent) => agent.globalSkillsDir !== null,
592
+ );
593
+ const agents = catalog.detected.filter((agent) =>
594
+ supported.some((entry) => entry.id === agent.id),
595
+ );
596
+ if (!agents.length)
597
+ return {
598
+ status: "not-checked" as const,
599
+ repairable: false,
600
+ message:
601
+ "No globally supported Agents detected for the bundled IPAB Skill.",
602
+ guidance: "Install an Agent, then run ipab doctor --fix.",
603
+ };
604
+ const directory = join(port.home, ".ipab", "skills");
605
+ await safeAncestors(directory);
606
+ const ledger = parseSkillsLedger(
607
+ await readPrivate<unknown>(
608
+ directory,
609
+ "installations.json",
610
+ [],
611
+ ledgerBytes,
612
+ ),
613
+ );
614
+ const current = new Map<string, Fingerprint | null>();
615
+ const problems: string[] = [];
616
+ for (const saved of Object.values(ledger.installations))
617
+ if (saved.identity === "ipab" && saved.swarm !== bundledSkillOrigin)
618
+ problems.push(
619
+ `IPAB Skill belongs to ${saved.swarm}; use skills sync for that source.`,
620
+ );
621
+ for (const path of locations(supported, port.home, "ipab")) {
622
+ const files = await skillFingerprint(path);
623
+ current.set(pathKey(path), files);
624
+ const saved = ledger.installations[pathKey(path)];
625
+ if (
626
+ files &&
627
+ (!saved || (!equal(files, saved.files) && !recoverable(files, saved)))
628
+ )
629
+ problems.push(`Custom or locally edited IPAB Skill: ${path}`);
630
+ }
631
+ const targets = agents.map((agent) => {
632
+ const path = targetPath(agent, "ipab", port.home);
633
+ const saved = ledger.installations[pathKey(path)];
634
+ return {
635
+ path,
636
+ id: agent.id,
637
+ current: Boolean(
638
+ current.get(pathKey(path)) &&
639
+ saved?.cid === source.cid &&
640
+ saved.agents.includes(agent.id) &&
641
+ !saved.pending,
642
+ ),
643
+ };
644
+ });
645
+ const description = targets
646
+ .map((target) => `${target.id} (${target.path})`)
647
+ .join(", ");
648
+ return {
649
+ status: problems.length
650
+ ? ("invalid" as const)
651
+ : targets.every((target) => target.current)
652
+ ? ("ok" as const)
653
+ : ("missing" as const),
654
+ repairable: !problems.length && targets.some((target) => !target.current),
655
+ message: `Bundled IPAB Skill ${source.cid}, installer ${skillsInstaller}: ${description}.${problems.length ? ` ${problems.join(" ")}` : ""}`,
656
+ guidance: problems.length
657
+ ? "Preserve the existing installation; resolve its ownership or local edits before retrying. --yes never overrides conflicts."
658
+ : targets.every((target) => target.current)
659
+ ? ""
660
+ : "Run ipab doctor --fix to install/update the CLI-bundled Skill globally for these Agents (no Swarm required; hooks/scripts are not executed).",
661
+ };
662
+ }
579
663
  export async function manageSkills(
580
- context: SwarmContext,
664
+ context:
665
+ | SwarmContext
666
+ | {
667
+ env: NodeJS.ProcessEnv;
668
+ bundledSkill: Awaited<ReturnType<typeof bundledSkillSource>>;
669
+ },
581
670
  swarm: string,
582
671
  options: SkillsOptions,
583
672
  port: SkillsPort = officialSkillsPort,
@@ -587,13 +676,7 @@ export async function manageSkills(
587
676
  (agent) => agent.globalSkillsDir !== null,
588
677
  );
589
678
  const ids = [
590
- ...new Set(
591
- options.agents.length
592
- ? options.agents
593
- : catalog.detected
594
- .filter((agent) => agent.globalSkillsDir !== null)
595
- .map((agent) => agent.id),
596
- ),
679
+ ...new Set(options.agents.length ? options.agents : ["universal"]),
597
680
  ];
598
681
  const agents = ids.map((id) => {
599
682
  const agent = supported.find((agent) => agent.id === id);
@@ -603,10 +686,6 @@ export async function manageSkills(
603
686
  );
604
687
  return agent;
605
688
  });
606
- if (options.sync && !agents.length)
607
- throw new HostError(
608
- "No globally supported agents detected. Select a target with repeatable --agent AGENT.",
609
- );
610
689
  const parent = await privateDirectory(port.home, ".ipab");
611
690
  const directory = await privateDirectory(parent, "skills");
612
691
  await safeAncestors(directory);
@@ -619,8 +698,10 @@ export async function manageSkills(
619
698
  ledgerBytes,
620
699
  ),
621
700
  );
622
- const currentStore = storeIdentity(context);
701
+ const currentStore =
702
+ "bundledSkill" in context ? undefined : storeIdentity(context);
623
703
  const retainInstallation = async (installation: Installation) => {
704
+ if ("bundledSkill" in context) return;
624
705
  const owner = installRetention(installation.path);
625
706
  context.store.registerOwner(owner, [installation.cid]);
626
707
  await context.store.retain(owner, [installation.cid]);
@@ -633,8 +714,10 @@ export async function manageSkills(
633
714
  await retainInstallation(installation);
634
715
  installation.files = files;
635
716
  delete installation.pending;
636
- recordRetention(installation, currentStore, [installation.cid]);
717
+ if (currentStore)
718
+ recordRetention(installation, currentStore, [installation.cid]);
637
719
  await saveLedger(directory, ledger);
720
+ if ("bundledSkill" in context) return;
638
721
  const owner = installRetention(installation.path);
639
722
  await context.store.recoverOwner(owner, [installation.cid]);
640
723
  await context.store.reconcile(owner, [installation.cid]);
@@ -642,16 +725,25 @@ export async function manageSkills(
642
725
  const owner = `skills-discovery:${hash(Buffer.from(swarm))}`;
643
726
  let staging: string | undefined;
644
727
  try {
645
- await context.store.recoverOwner(owner, []);
646
- const discovered = await swarmSkills(
647
- context,
648
- swarm,
649
- options.names,
650
- owner,
651
- );
728
+ if (!("bundledSkill" in context))
729
+ await context.store.recoverOwner(owner, []);
730
+ const discovered =
731
+ "bundledSkill" in context
732
+ ? [{ name: "ipab", identity: "ipab", cid: context.bundledSkill.cid }]
733
+ : await swarmSkills(context, swarm, options.names, owner);
652
734
  const items: SkillStatus[] = [];
735
+ const snapshots = new Map<string, Fingerprint | null>();
653
736
  for (const skill of discovered) {
654
737
  const problems: string[] = [];
738
+ const targets = new Set(
739
+ agents.map((agent) =>
740
+ pathKey(targetPath(agent, skill.identity, port.home)),
741
+ ),
742
+ );
743
+ const canOverride = (path: string) =>
744
+ options.sync &&
745
+ options.overrideExisting &&
746
+ targets.has(pathKey(path));
655
747
  for (const saved of Object.values(ledger.installations).filter(
656
748
  (entry) => entry.identity === skill.identity,
657
749
  ))
@@ -672,12 +764,14 @@ export async function manageSkills(
672
764
  try {
673
765
  const files = await skillFingerprint(path);
674
766
  current.set(pathKey(path), files);
767
+ snapshots.set(pathKey(path), files);
675
768
  const saved = ledger.installations[pathKey(path)];
676
- if (files && !saved)
769
+ if (files && !saved && !canOverride(path))
677
770
  problems.push(`Non-IPAB-managed installation: ${path}`);
678
771
  if (
679
772
  saved &&
680
773
  files &&
774
+ !canOverride(path) &&
681
775
  !equal(files, saved.files) &&
682
776
  !recoverable(files, saved)
683
777
  )
@@ -696,13 +790,17 @@ export async function manageSkills(
696
790
  id: agent.id,
697
791
  path,
698
792
  ...(saved ? { previousCid: saved.cid } : {}),
699
- status: saved?.pending
700
- ? "pending"
701
- : !files
702
- ? "not installed"
703
- : saved?.cid === skill.cid && saved.agents.includes(agent.id)
704
- ? "current"
705
- : "update",
793
+ status: !files
794
+ ? "not installed"
795
+ : canOverride(path) &&
796
+ (!saved ||
797
+ (!equal(files, saved.files) && !recoverable(files, saved)))
798
+ ? "overwrite"
799
+ : saved?.pending
800
+ ? "pending"
801
+ : saved?.cid === skill.cid && saved.agents.includes(agent.id)
802
+ ? "current"
803
+ : "update",
706
804
  };
707
805
  });
708
806
  const own = Object.values(ledger.installations).filter(
@@ -722,7 +820,9 @@ export async function manageSkills(
722
820
  ? "current"
723
821
  : statuses.some(
724
822
  (agent) =>
725
- agent.status === "update" || agent.status === "pending",
823
+ agent.status === "update" ||
824
+ agent.status === "pending" ||
825
+ agent.status === "overwrite",
726
826
  )
727
827
  ? "update"
728
828
  : "not installed"
@@ -769,11 +869,17 @@ export async function manageSkills(
769
869
  await mkdir(staging, { mode: 0o700 });
770
870
  const sources = new Map<string, string>();
771
871
  for (const skill of selected) {
772
- const source = await getBundle(
773
- context.store,
774
- skill.cid,
775
- join(staging, skill.identity),
776
- );
872
+ const source =
873
+ "bundledSkill" in context
874
+ ? await scaffoldFiles(
875
+ join(staging, skill.identity),
876
+ context.bundledSkill.files,
877
+ )
878
+ : await getBundle(
879
+ context.store,
880
+ skill.cid,
881
+ join(staging, skill.identity),
882
+ );
777
883
  sources.set(skill.identity, source);
778
884
  for (const agent of skill.agents) {
779
885
  if (agent.status === "current" || skill.problems.length) continue;
@@ -803,7 +909,7 @@ export async function manageSkills(
803
909
  );
804
910
  options.preview(
805
911
  [
806
- `Source Swarm: ${swarm}`,
912
+ `Source ${swarm === bundledSkillOrigin ? "CLI" : "Swarm"}: ${swarm}`,
807
913
  `Official installer: npx --yes --package ${skillsInstaller} skills add LOCAL --global --copy --yes --json`,
808
914
  `Agents: ${ids.join(", ")}`,
809
915
  ...changes,
@@ -829,16 +935,28 @@ export async function manageSkills(
829
935
  )))
830
936
  )
831
937
  throw new HostError(
832
- "Skill sync requires --yes or interactive consent. --yes authorizes only this preview, never overwriting conflicts.",
938
+ "Skill sync requires --yes or interactive consent. Use --override-existing to authorize replacing existing Skills; source and link conflicts remain protected.",
833
939
  );
834
940
  for (const skill of selected) {
835
941
  const source = sources.get(skill.identity)!;
942
+ const targets = new Set(
943
+ skill.agents.map((agent) => pathKey(agent.path)),
944
+ );
945
+ const canOverride = (path: string) =>
946
+ options.overrideExisting && targets.has(pathKey(path));
836
947
  for (const agent of skill.agents) {
837
948
  const key = pathKey(agent.path);
838
949
  try {
839
950
  await safeAncestors(agent.path);
840
951
  let before = await skillFingerprint(agent.path);
841
952
  const old = ledger.installations[key];
953
+ if (
954
+ canOverride(agent.path) &&
955
+ !equal(before, snapshots.get(key) ?? null)
956
+ )
957
+ throw new HostError(
958
+ `Installation changed since preview: ${agent.path}`,
959
+ );
842
960
  if (agent.status === "current") {
843
961
  if (!old || !before || !equal(before, old.files))
844
962
  throw new HostError(
@@ -873,10 +991,13 @@ export async function manageSkills(
873
991
  }
874
992
  if (
875
993
  before &&
876
- (!old ||
877
- old.swarm !== swarm ||
878
- old.name !== skill.name ||
879
- (!equal(before, old.files) && !recoverable(before, old)))
994
+ ((!old && !canOverride(agent.path)) ||
995
+ (old &&
996
+ (old.swarm !== swarm ||
997
+ old.name !== skill.name ||
998
+ (!canOverride(agent.path) &&
999
+ !equal(before, old.files) &&
1000
+ !recoverable(before, old)))))
880
1001
  )
881
1002
  throw new HostError(
882
1003
  `Installation changed since preview: ${agent.path}`,
@@ -890,18 +1011,35 @@ export async function manageSkills(
890
1011
  )) {
891
1012
  const files = await skillFingerprint(path);
892
1013
  const saved = ledger.installations[pathKey(path)];
1014
+ if (
1015
+ canOverride(path) &&
1016
+ !equal(files, snapshots.get(pathKey(path)) ?? null)
1017
+ )
1018
+ throw new HostError(
1019
+ `Protected installation changed since preview: ${path}`,
1020
+ );
893
1021
  if (
894
1022
  files &&
895
- (!saved ||
896
- saved.swarm !== swarm ||
897
- saved.name !== skill.name ||
898
- (!equal(files, saved.files) && !recoverable(files, saved)))
1023
+ ((!saved && !canOverride(path)) ||
1024
+ (saved &&
1025
+ (saved.swarm !== swarm ||
1026
+ saved.name !== skill.name ||
1027
+ (!canOverride(path) &&
1028
+ !equal(files, saved.files) &&
1029
+ !recoverable(files, saved)))))
899
1030
  )
900
1031
  throw new HostError(
901
1032
  `Protected installation changed since preview: ${path}`,
902
1033
  );
903
1034
  }
904
1035
  before = await skillFingerprint(agent.path);
1036
+ if (
1037
+ canOverride(agent.path) &&
1038
+ !equal(before, snapshots.get(key) ?? null)
1039
+ )
1040
+ throw new HostError(
1041
+ `Installation changed since preview: ${agent.path}`,
1042
+ );
905
1043
  const pending: Installation = {
906
1044
  name: skill.name,
907
1045
  cid: skill.cid,
@@ -920,10 +1058,11 @@ export async function manageSkills(
920
1058
  pending.retentions?.find(
921
1059
  (receipt) => receipt.store === currentStore,
922
1060
  )?.roots ?? [];
923
- recordRetention(pending, currentStore, [
924
- ...previousRoots,
925
- skill.cid,
926
- ]);
1061
+ if (currentStore)
1062
+ recordRetention(pending, currentStore, [
1063
+ ...previousRoots,
1064
+ skill.cid,
1065
+ ]);
927
1066
  ledger.installations[key] = pending;
928
1067
  await retainInstallation(pending);
929
1068
  await saveLedger(directory, ledger);
@@ -963,6 +1102,7 @@ export async function manageSkills(
963
1102
  `Official installer did not confirm the expected installation (exit ${installed.code}). Pending attribution preserved. ${installed.stderr.slice(-1000)}`,
964
1103
  );
965
1104
  await commitInstallation(pending, actual);
1105
+ snapshots.set(key, actual);
966
1106
  agent.status = "current";
967
1107
  skill.status = skill.agents.every(
968
1108
  (entry) => entry.status === "current",
@@ -998,8 +1138,10 @@ export async function manageSkills(
998
1138
  return result;
999
1139
  } finally {
1000
1140
  if (staging) await rm(staging, { recursive: true, force: true });
1001
- await context.store.recoverOwner(owner, []);
1002
- await context.store.reconcile(owner, []);
1141
+ if (!("bundledSkill" in context)) {
1142
+ await context.store.recoverOwner(owner, []);
1143
+ await context.store.reconcile(owner, []);
1144
+ }
1003
1145
  }
1004
1146
  });
1005
1147
  }
@@ -0,0 +1,30 @@
1
+ import { HostError } from "./host-error.js";
2
+
3
+ export const CHUNK_BYTES = 64 * 1024;
4
+
5
+ export function relativePath(path: string): string {
6
+ if (
7
+ path.length > 1024 ||
8
+ !path ||
9
+ path.includes("\\") ||
10
+ path.includes("%") ||
11
+ [...path].some(
12
+ (char) =>
13
+ char.charCodeAt(0) < 32 ||
14
+ char.charCodeAt(0) === 127 ||
15
+ ':*?"<>|'.includes(char),
16
+ ) ||
17
+ path
18
+ .split("/")
19
+ .some(
20
+ (part) => !part || part === "." || part === ".." || /[. ]$/.test(part),
21
+ )
22
+ )
23
+ throw new HostError(
24
+ "Unsafe Space path; use an unambiguous directory-relative / path.",
25
+ 1,
26
+ "PATH_INVALID",
27
+ "execution",
28
+ );
29
+ return path;
30
+ }
package/src/space.ts CHANGED
@@ -12,37 +12,11 @@ import { ReadableStream as NodeReadableStream } from "node:stream/web";
12
12
  import { appDescription, appSchemaCid } from "./app-definition.js";
13
13
  import { readSupportedSchemas } from "./supported-schemas.js";
14
14
  export { appSchema, appSchemaCid } from "./app-definition.js";
15
- export const CHUNK_BYTES = 64 * 1024;
15
+ import { CHUNK_BYTES, relativePath } from "./space-path.js";
16
+ export { CHUNK_BYTES, relativePath } from "./space-path.js";
16
17
  export const OUTPUT_BYTES = 64 * 1024 * 1024;
17
18
  export const MAX_PATHS = 4096;
18
19
 
19
- export function relativePath(path: string): string {
20
- if (
21
- path.length > 1024 ||
22
- !path ||
23
- path.includes("\\") ||
24
- path.includes("%") ||
25
- [...path].some(
26
- (char) =>
27
- char.charCodeAt(0) < 32 ||
28
- char.charCodeAt(0) === 127 ||
29
- ':*?"<>|'.includes(char),
30
- ) ||
31
- path
32
- .split("/")
33
- .some(
34
- (part) => !part || part === "." || part === ".." || /[. ]$/.test(part),
35
- )
36
- )
37
- throw new HostError(
38
- "Unsafe Space path; use an unambiguous directory-relative / path.",
39
- 1,
40
- "PATH_INVALID",
41
- "execution",
42
- );
43
- return path;
44
- }
45
-
46
20
  export async function bytes(
47
21
  stream: ReadableStream<Uint8Array> | NodeReadableStream<Uint8Array>,
48
22
  limit: number,
@@ -13,7 +13,7 @@ import {
13
13
  } from "node:fs";
14
14
  import { homedir, tmpdir } from "node:os";
15
15
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
16
- import { HostError } from "./errors.js";
16
+ import { HostError } from "./host-error.js";
17
17
  import { windowsStateAccess } from "./state-storage-windows.js";
18
18
 
19
19
  // Written only after the existing layout/owner checks, before the first DB
package/src/state.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  type ConfigKey,
11
11
  type ConfigValue,
12
12
  } from "./config.js";
13
- import { HostError, object, syntax } from "./errors.js";
13
+ import { HostError, object, syntax } from "./host-error.js";
14
14
  import { openStateStorage } from "./state-storage.js";
15
15
 
16
16
  export interface Association {
@@ -375,7 +375,7 @@ export class State {
375
375
  const entry = this.swarms().find((entry) => entry.cid === cid);
376
376
  if (!entry)
377
377
  throw new HostError(
378
- `Swarm "${reference}" is not registered. Run ipab swarm add ${cid}.`,
378
+ `Swarm "${reference}" is not registered. Run ipab swarm set ALIAS ${cid}.`,
379
379
  );
380
380
  return entry;
381
381
  }
@@ -384,23 +384,46 @@ export class State {
384
384
  const existing = this.swarms().find((entry) => entry.alias === alias);
385
385
  if (existing && existing.cid !== cid)
386
386
  throw new HostError(
387
- `Swarm alias "${alias}" is already assigned to "${existing.cid}". To keep both Swarms, retry with a different --alias. To replace only this local registration, run ipab swarm remove ${alias} and retry. Removal clears a matching default but preserves credentials and remote membership.`,
387
+ `Swarm alias "${alias}" is already assigned to "${existing.cid}". Choose a different alias, or explicitly retarget it with ipab swarm set ${alias} CONFIG_URL.`,
388
388
  );
389
389
  }
390
390
  registerSwarm(cid: string, alias?: string): RegisteredSwarm {
391
391
  cid = swarmUrl(cid);
392
392
  return this.transaction(() => {
393
393
  if (alias !== undefined) this.checkSwarmAlias(alias, cid);
394
- const previous = this.swarms().find((entry) => entry.cid === cid);
395
- const entry = { cid, alias: alias ?? previous?.alias ?? null };
396
- this.db
397
- .prepare("INSERT OR REPLACE INTO swarms VALUES (?,?)")
398
- .run(cid, entry.alias);
399
- if (this.config({ includeSecrets: false })["swarm.default"] == null)
400
- this.setConfig("swarm.default", cid);
401
- return entry;
394
+ return this.saveSwarmRegistration(cid, alias);
402
395
  });
403
396
  }
397
+ setSwarm(
398
+ alias: string,
399
+ url: string,
400
+ expectedTarget: string | null,
401
+ ): RegisteredSwarm {
402
+ swarmAlias(alias);
403
+ url = swarmUrl(url);
404
+ return this.transaction(() => {
405
+ const current = this.swarms().find((entry) => entry.alias === alias);
406
+ if ((current?.cid ?? null) !== expectedTarget)
407
+ throw new HostError(
408
+ `Swarm alias "${alias}" changed while setting it. Run ipab swarm list and retry.`,
409
+ );
410
+ if (current && current.cid !== url)
411
+ this.db
412
+ .prepare("UPDATE swarms SET alias=NULL WHERE cid=?")
413
+ .run(current.cid);
414
+ return this.saveSwarmRegistration(url, alias);
415
+ });
416
+ }
417
+ private saveSwarmRegistration(cid: string, alias?: string): RegisteredSwarm {
418
+ const previous = this.swarms().find((entry) => entry.cid === cid);
419
+ const entry = { cid, alias: alias ?? previous?.alias ?? null };
420
+ this.db
421
+ .prepare("INSERT OR REPLACE INTO swarms VALUES (?,?)")
422
+ .run(cid, entry.alias);
423
+ if (this.config({ includeSecrets: false })["swarm.default"] == null)
424
+ this.setConfig("swarm.default", cid);
425
+ return entry;
426
+ }
404
427
  useSwarm(reference: string): string {
405
428
  return this.transaction(() => {
406
429
  const entry = this.registeredSwarm(reference);
@@ -725,7 +748,9 @@ export class State {
725
748
  (exactCid(pin.reference) !== pin.reference ||
726
749
  (pin.cid !== null && pin.cid !== pin.reference))) ||
727
750
  (pin.swarm !== null &&
728
- (!pin.name || !pin.reference.startsWith("ipab://"))) ||
751
+ (!pin.reference.startsWith("ipab://") ||
752
+ (pin.name === "" &&
753
+ !/^ipab:\/\/[^/]+\/$/u.test(pin.reference)))) ||
729
754
  (pin.status === "ready" && (!pin.cid || !pin.targetCid))
730
755
  )
731
756
  throw new HostError(
@@ -20,8 +20,12 @@ export async function privateDirectory(
20
20
  await lstat(path);
21
21
  } catch (cause) {
22
22
  if (!nodeError(cause, "ENOENT")) throw cause;
23
- await mkdir(path, { mode: 0o700 });
24
- await secureNew(path, true);
23
+ try {
24
+ await mkdir(path, { mode: 0o700 });
25
+ await secureNew(path, true);
26
+ } catch (error) {
27
+ if (!nodeError(error, "EEXIST")) throw error;
28
+ }
25
29
  }
26
30
  await protectedPath(path, true);
27
31
  return path;
@@ -78,6 +82,7 @@ export async function withPrivateLock<T>(
78
82
  directory: string,
79
83
  operation: () => Promise<T>,
80
84
  signal?: AbortSignal,
85
+ attempts = 300,
81
86
  ): Promise<T> {
82
87
  signal?.throwIfAborted();
83
88
  const path = join(directory, "operation.sqlite");
@@ -93,7 +98,7 @@ export async function withPrivateLock<T>(
93
98
  let locked = false;
94
99
  try {
95
100
  db.exec("PRAGMA busy_timeout=0");
96
- for (let attempt = 0; attempt < 300; attempt++) {
101
+ for (let attempt = 0; attempt < attempts; attempt++) {
97
102
  signal?.throwIfAborted();
98
103
  try {
99
104
  db.exec("BEGIN IMMEDIATE");
package/src/swarm-meta.ts CHANGED
@@ -1,6 +1,20 @@
1
1
  import { encodeSchema, type BundleType } from "@ipab/bundle";
2
2
  import { HostError, object } from "./errors.js";
3
3
  import { relativePath } from "./space.js";
4
+ import {
5
+ swarmStateSchema,
6
+ previousSwarmStateSchema,
7
+ legacySwarmStateSchema,
8
+ } from "@ipab/bundle/swarm-state";
9
+ export {
10
+ swarmStateType,
11
+ swarmStateSchema,
12
+ previousSwarmStateType,
13
+ previousSwarmStateSchema,
14
+ legacySwarmStateType,
15
+ legacySwarmStateSchema,
16
+ parseSwarmState,
17
+ } from "@ipab/bundle/swarm-state";
4
18
 
5
19
  export const legacySwarmMetaType: BundleType = {
6
20
  contentType: "application/json",
@@ -34,43 +48,10 @@ export interface SwarmMeta {
34
48
  registryPath: string;
35
49
  skillPath?: string;
36
50
  }
37
- export const legacySwarmStateType: BundleType = {
38
- contentType: "application/json",
39
- schema: {
40
- type: "object",
41
- required: ["v", "templatePath", "registryPath", "names"],
42
- properties: {
43
- v: { const: 5 },
44
- templatePath: { type: "string", minLength: 1, maxLength: 196 },
45
- registryPath: { type: "string", minLength: 1, maxLength: 196 },
46
- names: {
47
- type: "object",
48
- additionalProperties: { type: "string" },
49
- },
50
- },
51
- additionalProperties: false,
52
- },
53
- };
54
- export const swarmStateType: BundleType = {
55
- contentType: "application/json",
56
- schema: {
57
- type: "object",
58
- required: ["v", "templatePath", "registryPath", "skillPath", "names"],
59
- properties: {
60
- v: { const: 5 },
61
- templatePath: { type: "string", minLength: 1, maxLength: 196 },
62
- registryPath: { type: "string", minLength: 1, maxLength: 196 },
63
- skillPath: { type: "string", minLength: 1, maxLength: 196 },
64
- names: { type: "object", additionalProperties: { type: "string" } },
65
- },
66
- additionalProperties: false,
67
- },
68
- };
69
- export const swarmStateSchema = await encodeSchema(swarmStateType);
70
- export const legacySwarmStateSchema = await encodeSchema(legacySwarmStateType);
71
51
  export function isSwarmStateSchema(cid: string): boolean {
72
52
  return (
73
53
  cid === swarmStateSchema.cid.toString() ||
54
+ cid === previousSwarmStateSchema.cid.toString() ||
74
55
  cid === legacySwarmStateSchema.cid.toString()
75
56
  );
76
57
  }