@rbbtsn0w/adg 0.5.0-beta.5 → 0.5.0-beta.7

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.
@@ -1,10 +1,10 @@
1
- import { existsSync } from "node:fs";
2
- import { adaptPlugin } from "./adapt.js";
3
1
  import { listPlugins } from "./list.js";
4
2
  import { agentsForComponents, resolveAgents } from "../agents/index.js";
5
- import { installedPluginDir, lockPath } from "../paths.js";
3
+ import { lockPath, pluginRematerializationSource } from "../paths.js";
6
4
  import { readLock, writeLock } from "../lock.js";
7
5
  import { pluginState } from "../types.js";
6
+ import { ADAPTER_TARGETS } from "../adapters/index.js";
7
+ import { installPlugin } from "./install.js";
8
8
  function selectedLock(opts) {
9
9
  const lock = readLock(lockPath(opts.pluginsDir));
10
10
  const names = [...new Set(opts.names)];
@@ -63,19 +63,25 @@ export function enablePlugins(opts) {
63
63
  const { lock, names } = selectedLock(opts);
64
64
  const order = enableOrder(lock, names);
65
65
  const changed = order.filter((name) => pluginState(lock.plugins[name]) !== "enabled");
66
+ for (const name of changed) {
67
+ const entry = lock.plugins[name];
68
+ installPlugin({
69
+ source: pluginRematerializationSource(opts.pluginsDir, name, entry.origin),
70
+ pluginsDir: opts.pluginsDir,
71
+ origin: entry.origin,
72
+ selection: entry.selection,
73
+ targets: [...ADAPTER_TARGETS],
74
+ forceMaterialize: true,
75
+ });
76
+ }
77
+ const plugins = listPlugins(opts.pluginsDir);
78
+ const updatedLock = readLock(lockPath(opts.pluginsDir));
66
79
  for (const name of order)
67
- lock.plugins[name].state = "enabled";
80
+ updatedLock.plugins[name].state = "enabled";
68
81
  if (changed.length > 0)
69
- writeLock(lockPath(opts.pluginsDir), lock);
70
- const plugins = listPlugins(opts.pluginsDir);
82
+ writeLock(lockPath(opts.pluginsDir), updatedLock);
71
83
  const agents = (opts.agents ?? resolveAgents()).map((agent) => {
72
84
  const compatible = changed.filter((name) => pluginAgentIds(plugins, name).has(agent.id));
73
- for (const name of compatible) {
74
- const entry = lock.plugins[name];
75
- const dir = installedPluginDir(opts.pluginsDir, name, entry.origin);
76
- if (existsSync(dir))
77
- adaptPlugin(dir, [agent.adaptTarget], entry.selection);
78
- }
79
85
  if (compatible.length === 0)
80
86
  return { agent: agent.id, affected: [], skipped: false };
81
87
  return agent.activate({ pluginsDir: opts.pluginsDir, plugins: compatible, scope: opts.scope });
@@ -1,9 +1,9 @@
1
- import { existsSync } from "node:fs";
2
- import { adaptPlugin } from "./adapt.js";
3
- import { selectInstalled } from "./projection.js";
4
- import { installedPluginDir } from "../paths.js";
1
+ import { adaptedFilesForTarget, selectInstalled } from "./projection.js";
2
+ import { pluginRematerializationSource } from "../paths.js";
5
3
  import { getAgent } from "../agents/index.js";
4
+ import { ADAPTER_TARGETS } from "../adapters/index.js";
6
5
  import { pluginState } from "../types.js";
6
+ import { installPlugin } from "./install.js";
7
7
  /** Regenerate manifests for the selected plugins, then refresh them in the agent. */
8
8
  export function syncPlugins(opts) {
9
9
  const agent = opts.agent ?? getAgent(opts.target);
@@ -13,11 +13,15 @@ export function syncPlugins(opts) {
13
13
  const disabled = selected.filter((p) => pluginState(p) === "disabled");
14
14
  const actions = disabled.map((p) => ({ name: p.name, adapted: [], synced: false }));
15
15
  for (const p of enabled) {
16
- const dir = installedPluginDir(opts.pluginsDir, p.name, p.origin);
17
- if (!existsSync(dir))
18
- continue;
19
- const adapted = adaptPlugin(dir, [adaptTarget], p.selection).map((r) => r.file);
20
- actions.push({ name: p.name, adapted, synced: false });
16
+ const result = installPlugin({
17
+ source: pluginRematerializationSource(opts.pluginsDir, p.name, p.origin),
18
+ pluginsDir: opts.pluginsDir,
19
+ origin: p.origin,
20
+ selection: p.selection,
21
+ targets: [...ADAPTER_TARGETS],
22
+ forceMaterialize: true,
23
+ });
24
+ actions.push({ name: p.name, adapted: adaptedFilesForTarget(result.installedTo, result.adapted, adaptTarget), synced: false });
21
25
  }
22
26
  if (!agent)
23
27
  return { target: opts.target, actions };
@@ -1,57 +1,55 @@
1
1
  import { existsSync } from "node:fs";
2
- import { folderHash } from "../hash.js";
3
- import { packageFilter, PROJECTION_DIRS } from "../package.js";
4
- import { lockPath, installedPluginDir } from "../paths.js";
5
- import { readLock, writeLock } from "../lock.js";
6
- import { readManifest } from "../manifest.js";
7
- import { adaptPlugin } from "./adapt.js";
8
- import { ADAPTER_TARGETS } from "../adapters/index.js";
2
+ import { resolve } from "node:path";
9
3
  import { resolveAgents } from "../agents/index.js";
4
+ import { installedPluginDir, lockPath, pluginSourceCacheDir } from "../paths.js";
5
+ import { readLock } from "../lock.js";
6
+ import { installPlugin } from "./install.js";
10
7
  /**
11
- * Re-scan installed plugins in a plugins directory, refreshing each lock
12
- * entry's version and folderHash from disk. Entries whose content or version
13
- * changed are reported as `changed`. A missing plugin directory is reported as
14
- * an issue rather than silently dropped.
15
- *
16
- * Changed plugins always have their runtime manifests regenerated (honoring
17
- * their selection). With `resync`, the regenerated content is additionally
18
- * re-installed into the agents so Claude/Codex reflect the new content.
8
+ * Refresh local sources and repair effective installations from their complete
9
+ * source snapshots. Runtime installations are never treated as upstream input.
19
10
  */
20
11
  export function updateLock(pluginsDir, now = new Date().toISOString(), opts = {}) {
21
- const lockFile = lockPath(pluginsDir);
22
- const lock = readLock(lockFile);
12
+ const snapshot = readLock(lockPath(pluginsDir));
13
+ const only = opts.only ? new Set(opts.only) : undefined;
23
14
  const results = [];
24
15
  const missing = [];
25
16
  const changedNames = [];
26
- const only = opts.only ? new Set(opts.only) : undefined;
27
- for (const [name, entry] of Object.entries(lock.plugins)) {
17
+ for (const [name, entry] of Object.entries(snapshot.plugins)) {
28
18
  if (only && !only.has(name))
29
19
  continue;
30
- const dir = installedPluginDir(pluginsDir, name, entry.origin);
31
- if (!existsSync(dir)) {
20
+ const installedDir = installedPluginDir(pluginsDir, name, entry.origin);
21
+ const resolvedSource = entry.origin.type === "local" ? resolve(pluginsDir, entry.origin.path) : undefined;
22
+ const localSource = resolvedSource && resolvedSource !== resolve(installedDir)
23
+ ? resolvedSource
24
+ : undefined;
25
+ const cache = pluginSourceCacheDir(pluginsDir, name);
26
+ const source = localSource && existsSync(localSource) ? localSource : cache;
27
+ if (!existsSync(source)) {
32
28
  missing.push(name);
33
29
  continue;
34
30
  }
35
- const manifest = readManifest(dir);
36
- const hash = folderHash(dir, PROJECTION_DIRS, packageFilter(manifest, { includeProjections: false }));
37
- const changed = hash !== entry.folderHash || manifest.version !== entry.version;
38
- if (changed) {
39
- entry.folderHash = hash;
40
- entry.version = manifest.version;
41
- entry.updatedAt = now;
42
- // Regenerate runtime manifests from the updated source, honoring selection.
43
- // Covers every registered adapter target (claude/codex/antigravity) so a
44
- // projection can't go stale after an update.
45
- adaptPlugin(dir, [...ADAPTER_TARGETS], entry.selection);
31
+ const result = installPlugin({
32
+ source,
33
+ pluginsDir,
34
+ origin: entry.origin,
35
+ selection: entry.selection,
36
+ skipUnchanged: true,
37
+ now,
38
+ });
39
+ if (result.changed)
46
40
  changedNames.push(name);
47
- }
48
- results.push({ name, changed, version: manifest.version, folderHash: hash });
41
+ results.push({
42
+ name,
43
+ changed: result.changed,
44
+ version: result.version,
45
+ sourceHash: result.sourceHash,
46
+ installedHash: result.installedHash,
47
+ });
49
48
  }
50
- writeLock(lockFile, lock);
51
49
  const out = { results, missing };
52
50
  if (opts.resync && changedNames.length > 0) {
53
51
  const ctx = { pluginsDir, plugins: changedNames, scope: opts.scope ?? "project" };
54
- out.agents = (opts.agents ?? resolveAgents()).map((a) => a.refresh(ctx));
52
+ out.agents = (opts.agents ?? resolveAgents()).map((agent) => agent.refresh(ctx));
55
53
  }
56
54
  return out;
57
55
  }
@@ -1,5 +1,5 @@
1
- import { cpSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { dirname, relative } from "node:path";
1
+ import { cpSync, lstatSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, relative } from "node:path";
3
3
  export function ensureDir(dir) {
4
4
  mkdirSync(dir, { recursive: true });
5
5
  }
@@ -22,12 +22,25 @@ export function writeText(file, value) {
22
22
  */
23
23
  export function copyPluginDir(src, dest, include) {
24
24
  ensureDir(dirname(dest));
25
+ const sourceRoot = realpathSync(src);
25
26
  cpSync(src, dest, {
26
27
  recursive: true,
28
+ dereference: true,
27
29
  filter: (from) => {
28
30
  const base = from.split(/[/\\]/).pop() ?? "";
29
31
  if (base === ".git" || base === "node_modules" || base === ".DS_Store")
30
32
  return false;
33
+ try {
34
+ if (lstatSync(from).isSymbolicLink()) {
35
+ const target = realpathSync(from);
36
+ const relTarget = relative(sourceRoot, target);
37
+ if (relTarget === ".." || relTarget.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(relTarget))
38
+ return false;
39
+ }
40
+ }
41
+ catch {
42
+ return false;
43
+ }
31
44
  if (!include)
32
45
  return true;
33
46
  return include(relative(src, from));
package/dist/src/lock.js CHANGED
@@ -1,20 +1,24 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { recordTelemetryEvent } from "./telemetry.js";
2
3
  import { LOCK_VERSION } from "./types.js";
3
4
  export function emptyLock() {
4
5
  return { version: LOCK_VERSION, plugins: {} };
5
6
  }
6
- export function readLock(file) {
7
+ export function readLock(file, telemetrySpan) {
7
8
  if (!existsSync(file))
8
9
  return emptyLock();
9
10
  const raw = JSON.parse(readFileSync(file, "utf8"));
11
+ if (typeof raw?.version === "number") {
12
+ const observed = raw.version === 2 || raw.version === LOCK_VERSION ? raw.version : -1;
13
+ recordTelemetryEvent("adg.lock.read", { "format.version": observed }, telemetrySpan);
14
+ }
10
15
  if (typeof raw.version !== "number" || typeof raw.plugins !== "object" || raw.plugins === null) {
11
16
  throw new Error(`${file} is not a valid .plugin-lock.json`);
12
17
  }
13
- // Pre-release policy: a lock from an older format version is fully
14
- // regenerable from the plugin directories, so rebuild rather than merge
15
- // incompatible entry shapes.
16
- if (raw.version !== LOCK_VERSION)
17
- return emptyLock();
18
+ if (raw.version !== LOCK_VERSION) {
19
+ throw new Error(`${file} uses unsupported lock version ${raw.version}; expected ${LOCK_VERSION}. ` +
20
+ "Run `adg plugins migrate` with the same scope flag to upgrade it.");
21
+ }
18
22
  return raw;
19
23
  }
20
24
  export function writeLock(file, lock) {
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { ADG_SCHEMA_VERSION } from "./types.js";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { ADG_SCHEMA_VERSION, COMPONENT_TYPES } from "./types.js";
4
+ import { recordTelemetryEvent } from "./telemetry.js";
4
5
  /** Canonical, vendor-neutral source manifest location (a plugin). */
5
6
  export const ADG_MANIFEST_PATH = join(".agents", ".plugin.json");
6
7
  /** Canonical, vendor-neutral source catalog location (a marketplace). */
@@ -32,7 +33,7 @@ export class ManifestError extends Error {
32
33
  }
33
34
  }
34
35
  /** Read and validate a plugin's `.agents/.plugin.json` (or legacy fallback). */
35
- export function readManifest(pluginDir) {
36
+ export function readManifest(pluginDir, telemetrySpan) {
36
37
  const file = findManifestFile(pluginDir);
37
38
  if (!file) {
38
39
  throw new ManifestError([`${ADG_MANIFEST_PATH} not found in ${pluginDir}`]);
@@ -44,6 +45,15 @@ export function readManifest(pluginDir) {
44
45
  catch (err) {
45
46
  throw new ManifestError([`${file} is not valid JSON: ${err.message}`]);
46
47
  }
48
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
49
+ const schemaVersion = raw.schemaVersion;
50
+ if (typeof schemaVersion === "string") {
51
+ recordTelemetryEvent("adg.manifest.read", {
52
+ "schema.version": schemaVersion === ADG_SCHEMA_VERSION ? schemaVersion : "other",
53
+ "manifest.layout": file === join(pluginDir, LEGACY_MANIFEST_PATH) ? "legacy" : "canonical",
54
+ }, telemetrySpan);
55
+ }
56
+ }
47
57
  return validateManifest(raw);
48
58
  }
49
59
  /** Validate an already-parsed manifest object, throwing ManifestError on failure. */
@@ -75,6 +85,11 @@ export function collectIssues(raw) {
75
85
  if (m.skills !== undefined && typeof m.skills !== "string" && !isStringArray(m.skills)) {
76
86
  issues.push("skills must be a string or an array of strings");
77
87
  }
88
+ if (typeof m.skills === "string" && !isSafeRelativePointer(m.skills))
89
+ issues.push("skills must stay within the plugin directory");
90
+ if (isStringArray(m.skills) && m.skills.some((path) => !isSafeRelativePointer(path))) {
91
+ issues.push("skills entries must stay within the plugin directory");
92
+ }
78
93
  if (m.mcp !== undefined) {
79
94
  issues.push("mcp is not supported; use mcpServers");
80
95
  }
@@ -82,6 +97,10 @@ export function collectIssues(raw) {
82
97
  if (m[key] !== undefined && typeof m[key] !== "string") {
83
98
  issues.push(`${key} must be a string`);
84
99
  }
100
+ if (typeof m[key] === "string" && ["agents", "commands", "apps", "hooks", "mcpServers"].includes(key)
101
+ && !isSafeRelativePointer(m[key])) {
102
+ issues.push(`${key} must stay within the plugin directory`);
103
+ }
85
104
  }
86
105
  if (m.strict !== undefined && typeof m.strict !== "boolean") {
87
106
  issues.push("strict must be a boolean");
@@ -104,6 +123,31 @@ export function collectIssues(raw) {
104
123
  });
105
124
  }
106
125
  }
126
+ if (m.selectionDependencies !== undefined) {
127
+ if (typeof m.selectionDependencies !== "object" || m.selectionDependencies === null || Array.isArray(m.selectionDependencies)) {
128
+ issues.push("selectionDependencies must be an object");
129
+ }
130
+ else {
131
+ for (const [component, rawRequirement] of Object.entries(m.selectionDependencies)) {
132
+ if (!COMPONENT_TYPES.includes(component)) {
133
+ issues.push(`selectionDependencies.${component} is not a supported component`);
134
+ continue;
135
+ }
136
+ if (typeof rawRequirement !== "object" || rawRequirement === null || Array.isArray(rawRequirement)) {
137
+ issues.push(`selectionDependencies.${component} must be an object`);
138
+ continue;
139
+ }
140
+ const requirement = rawRequirement;
141
+ if (requirement.components !== undefined && (!isStringArray(requirement.components)
142
+ || requirement.components.some((value) => !COMPONENT_TYPES.includes(value)))) {
143
+ issues.push(`selectionDependencies.${component}.components must contain supported component names`);
144
+ }
145
+ if (requirement.skills !== undefined && !isStringArray(requirement.skills)) {
146
+ issues.push(`selectionDependencies.${component}.skills must be an array of strings`);
147
+ }
148
+ }
149
+ }
150
+ }
107
151
  // `adapters` is no longer part of the DSL. A stray one from an old manifest is
108
152
  // tolerated (ignored) rather than rejected — output paths are ADG-internal.
109
153
  return issues;
@@ -111,3 +155,8 @@ export function collectIssues(raw) {
111
155
  function isStringArray(v) {
112
156
  return Array.isArray(v) && v.every((x) => typeof x === "string");
113
157
  }
158
+ function isSafeRelativePointer(value) {
159
+ if (isAbsolute(value) || /^[A-Za-z]:/.test(value) || /^[/\\]{2}/.test(value))
160
+ return false;
161
+ return !value.replaceAll("\\", "/").split("/").includes("..");
162
+ }
@@ -0,0 +1,176 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, renameSync, rmSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { copyPluginDir, ensureDir, toPosix, writeJson } from "./fsutil.js";
5
+ import { ADG_MANIFEST_PATH } from "./manifest.js";
6
+ import { mcpConfigPath } from "./mcp.js";
7
+ import { packageFilter } from "./package.js";
8
+ const META_RE = /^(README|LICEN[CS]E|CHANGELOG|NOTICE)(\..+)?$/i;
9
+ function normalizeRelative(path) {
10
+ return path.replace(/^\.?[/\\]/, "").replaceAll("\\", "/").replace(/\/+$/, "");
11
+ }
12
+ function pathWithin(relPath, root) {
13
+ return relPath === root || relPath.startsWith(`${root}/`);
14
+ }
15
+ function declaredPaths(manifest, component) {
16
+ const value = component === "mcp" ? mcpConfigPath(manifest) : manifest[component];
17
+ if (!value)
18
+ return [];
19
+ return (Array.isArray(value) ? value : [value]).map(normalizeRelative).filter(Boolean);
20
+ }
21
+ function selectedSkillPaths(manifest, names) {
22
+ const declared = manifest.skills;
23
+ if (Array.isArray(declared)) {
24
+ const wanted = new Set(names);
25
+ const selected = declared
26
+ .map(normalizeRelative)
27
+ .filter((path) => wanted.has(basename(path)));
28
+ const found = new Set(selected.map((path) => basename(path)));
29
+ const missing = names.filter((name) => !found.has(name));
30
+ if (missing.length > 0)
31
+ throw new Error(`selected skill(s) not declared: ${missing.join(", ")}`);
32
+ return selected;
33
+ }
34
+ const root = normalizeRelative(declared ?? "./skills/");
35
+ return names.map((name) => `${root}/${name}`);
36
+ }
37
+ /** The universal manifest that truthfully describes the effective installation. */
38
+ export function applySelectionToManifest(manifest, selection) {
39
+ const effective = structuredClone(manifest);
40
+ if (!selection)
41
+ return effective;
42
+ const selected = new Set(selection.components);
43
+ if (!selected.has("skills"))
44
+ delete effective.skills;
45
+ else if (selection.skills)
46
+ effective.skills = selectedSkillPaths(manifest, selection.skills).map((path) => `./${path}`);
47
+ if (!selected.has("agents"))
48
+ delete effective.agents;
49
+ if (!selected.has("commands"))
50
+ delete effective.commands;
51
+ if (!selected.has("hooks"))
52
+ delete effective.hooks;
53
+ if (!selected.has("apps"))
54
+ delete effective.apps;
55
+ if (!selected.has("mcp"))
56
+ delete effective.mcpServers;
57
+ return effective;
58
+ }
59
+ /**
60
+ * Allow only files that belong to the effective selection. The canonical
61
+ * manifest is generated separately, so authored `.agents` and vendor adapter
62
+ * projections are never copied from the full source snapshot.
63
+ */
64
+ export function effectivePackageFilter(manifest, selection) {
65
+ const selected = new Set(selection?.components ?? ["skills", "agents", "commands", "mcp", "hooks", "apps"]);
66
+ const roots = [];
67
+ for (const component of selected) {
68
+ if (component === "skills" && selection?.skills)
69
+ roots.push(...selectedSkillPaths(manifest, selection.skills));
70
+ else
71
+ roots.push(...declaredPaths(manifest, component));
72
+ }
73
+ return (rawPath) => {
74
+ if (rawPath === "")
75
+ return true;
76
+ const relPath = toPosix(rawPath);
77
+ if (relPath === ".agents" || relPath === ADG_MANIFEST_PATH)
78
+ return true;
79
+ if (relPath.startsWith("../") || relPath === "..")
80
+ return false;
81
+ if (!relPath.includes("/") && META_RE.test(relPath))
82
+ return true;
83
+ return roots.some((root) => pathWithin(relPath, root) || root.startsWith(`${relPath}/`));
84
+ };
85
+ }
86
+ /** Build an effective plugin in a staging directory, then atomically replace it. */
87
+ export function materializePlugin(opts) {
88
+ const destination = resolve(opts.destination);
89
+ const parent = dirname(destination);
90
+ const token = randomUUID();
91
+ const staging = join(parent, `.${basename(destination)}.adg-staging-${token}`);
92
+ const backup = join(parent, `.${basename(destination)}.adg-backup-${token}`);
93
+ const effectiveManifest = applySelectionToManifest(opts.manifest, opts.selection);
94
+ ensureDir(parent);
95
+ if (opts.selection) {
96
+ const requiredPaths = [];
97
+ for (const component of opts.selection.components) {
98
+ if (component === "skills" && opts.selection.skills)
99
+ requiredPaths.push(...selectedSkillPaths(opts.manifest, opts.selection.skills));
100
+ else
101
+ requiredPaths.push(...declaredPaths(opts.manifest, component));
102
+ }
103
+ const missing = requiredPaths.filter((path) => !existsSync(join(opts.source, path)));
104
+ if (missing.length > 0)
105
+ throw new Error(`selected payload path(s) not found: ${missing.join(", ")}`);
106
+ }
107
+ try {
108
+ copyPluginDir(opts.source, staging, effectivePackageFilter(opts.manifest, opts.selection));
109
+ writeJson(join(staging, ADG_MANIFEST_PATH), effectiveManifest);
110
+ opts.build(staging, effectiveManifest);
111
+ if (existsSync(destination))
112
+ renameSync(destination, backup);
113
+ try {
114
+ renameSync(staging, destination);
115
+ }
116
+ catch (error) {
117
+ if (existsSync(backup))
118
+ renameSync(backup, destination);
119
+ throw error;
120
+ }
121
+ rmSync(backup, { recursive: true, force: true });
122
+ return effectiveManifest;
123
+ }
124
+ finally {
125
+ rmSync(staging, { recursive: true, force: true });
126
+ if (existsSync(backup) && !existsSync(destination))
127
+ renameSync(backup, destination);
128
+ else
129
+ rmSync(backup, { recursive: true, force: true });
130
+ }
131
+ }
132
+ /**
133
+ * Atomically expose a new complete source snapshot for a callback. If building
134
+ * the effective installation fails, restore the previous cache as part of the
135
+ * same transaction.
136
+ */
137
+ export function withPluginSourceCache(source, cacheDir, manifest, use) {
138
+ const target = resolve(cacheDir);
139
+ if (resolve(source) === target)
140
+ return use(target);
141
+ const parent = dirname(target);
142
+ const token = randomUUID();
143
+ const staging = join(parent, `.${basename(target)}.adg-cache-${token}`);
144
+ const backup = join(parent, `.${basename(target)}.adg-cache-backup-${token}`);
145
+ ensureDir(parent);
146
+ let committed = false;
147
+ let hadPrevious = false;
148
+ let promoted = false;
149
+ try {
150
+ copyPluginDir(source, staging, packageFilter(manifest, { includeProjections: false }));
151
+ if (existsSync(target)) {
152
+ renameSync(target, backup);
153
+ hadPrevious = true;
154
+ }
155
+ renameSync(staging, target);
156
+ promoted = true;
157
+ const result = use(target);
158
+ committed = true;
159
+ rmSync(backup, { recursive: true, force: true });
160
+ return result;
161
+ }
162
+ catch (error) {
163
+ if (promoted)
164
+ rmSync(target, { recursive: true, force: true });
165
+ if (hadPrevious && existsSync(backup))
166
+ renameSync(backup, target);
167
+ throw error;
168
+ }
169
+ finally {
170
+ rmSync(staging, { recursive: true, force: true });
171
+ if (!committed && hadPrevious && existsSync(backup) && !existsSync(target))
172
+ renameSync(backup, target);
173
+ if (committed)
174
+ rmSync(backup, { recursive: true, force: true });
175
+ }
176
+ }
package/dist/src/paths.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
2
3
  import { homedir } from "node:os";
3
- import { basename, dirname, join, relative } from "node:path";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
4
5
  export const LOCK_FILENAME = ".plugin-lock.json";
5
6
  export const MARKETPLACE_FILENAME = "marketplace.json";
6
7
  /**
@@ -51,6 +52,31 @@ export function lockPath(pluginsDir) {
51
52
  export function marketplacePath(pluginsDir) {
52
53
  return join(pluginsDir, MARKETPLACE_FILENAME);
53
54
  }
55
+ /**
56
+ * Internal full-source cache for a plugin store. The runtime-facing
57
+ * `pluginsDir` contains only effective installations; complete source payloads
58
+ * live in the sibling cache tree and are never registered with an agent.
59
+ */
60
+ export function pluginCacheRoot(pluginsDir) {
61
+ const storeId = createHash("sha1").update(resolve(pluginsDir).split("\\").join("/")).digest("hex").slice(0, 12);
62
+ return join(dirname(pluginsDir), "cache", "plugins", storeId);
63
+ }
64
+ /** One replaceable full-source snapshot per installed plugin. */
65
+ export function pluginSourceCacheDir(pluginsDir, name) {
66
+ return join(pluginCacheRoot(pluginsDir), name);
67
+ }
68
+ /** Resolve a complete payload for rebuilding, falling back to a live local source. */
69
+ export function pluginRematerializationSource(pluginsDir, name, origin) {
70
+ const cache = pluginSourceCacheDir(pluginsDir, name);
71
+ if (existsSync(cache))
72
+ return cache;
73
+ if (origin.type === "local") {
74
+ const localPath = resolve(pluginsDir, origin.path);
75
+ if (existsSync(localPath))
76
+ return localPath;
77
+ }
78
+ throw new Error(`source cache missing for "${name}"; run \`adg plugins update\` or re-add the plugin`);
79
+ }
54
80
  /** True when `pluginsDir` has the canonical `<root>/.agents/plugins` shape. */
55
81
  export function isCanonicalPluginsDir(pluginsDir) {
56
82
  return basename(pluginsDir) === "plugins" && basename(dirname(pluginsDir)) === ".agents";
@@ -20,7 +20,8 @@ export function pluginsListJson(plugins, pluginsDir) {
20
20
  name: plugin.name,
21
21
  version: plugin.version,
22
22
  source: plugin.origin,
23
- folderHash: plugin.folderHash,
23
+ sourceHash: plugin.sourceHash,
24
+ installedHash: plugin.installedHash,
24
25
  installedAt: plugin.installedAt,
25
26
  updatedAt: plugin.updatedAt,
26
27
  path: installedPluginDir(pluginsDir, plugin.name, plugin.origin),
@@ -69,7 +69,7 @@ export function renderPluginList(plugins, pluginsDir, opts = {}) {
69
69
  const name = ui.name(r.label.padEnd(nameW));
70
70
  const path = ui.meta(ellipsizeStart(r.path, pathW).padEnd(pathW));
71
71
  out.push(`${name} ${path} ${ui.meta("Agents:")} ${r.agents}`);
72
- const provenance = `[${r.p.origin.type}] ${(r.p.folderHash ?? "").slice(0, 19)}${partial}`;
72
+ const provenance = `[${r.p.origin.type}] ${(r.p.installedHash ?? "").slice(0, 19)}${partial}`;
73
73
  out.push(ui.meta(` ${[provenance, ...r.counts].join(" ")}`));
74
74
  if (opts.verbose)
75
75
  out.push(...renderContents(r.p.contents, 4));
@@ -6,9 +6,13 @@ import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions"
6
6
  import * as opentelemetry from "@opentelemetry/api";
7
7
  import {} from "@opentelemetry/api";
8
8
  const baseEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
9
+ export function normalizeTraceEndpoint(endpoint) {
10
+ const normalized = endpoint.replace(/\/$/, "");
11
+ return normalized.endsWith("/v1/traces") ? normalized : `${normalized}/v1/traces`;
12
+ }
9
13
  const TELEMETRY_URL = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ||
10
14
  (baseEndpoint
11
- ? `${baseEndpoint.replace(/\/$/, "")}/v1/traces`
15
+ ? normalizeTraceEndpoint(baseEndpoint)
12
16
  : "https://telemetry-gateway.hamiltonsnow.workers.dev/v1/traces");
13
17
  function isEnabled() {
14
18
  return (!process.env.DISABLE_TELEMETRY &&
@@ -74,3 +78,12 @@ export function sanitizeArgs(args) {
74
78
  return arg;
75
79
  });
76
80
  }
81
+ /** Record a privacy-safe event without allowing telemetry to affect CLI behavior. */
82
+ export function recordTelemetryEvent(name, attributes, span = opentelemetry.trace.getActiveSpan()) {
83
+ try {
84
+ span?.addEvent(name, attributes);
85
+ }
86
+ catch {
87
+ // Telemetry must never change CLI behavior.
88
+ }
89
+ }