@rbbtsn0w/adg 0.8.1-dev.pr107.f31e5ca → 0.9.0-beta.1

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.
@@ -6,6 +6,7 @@ import { lockPath } from "../paths.js";
6
6
  import { readLock } from "../lock.js";
7
7
  import { resolveInstallOrder } from "../deps.js";
8
8
  import { cloneGitHub, gitRevision, parseGitHubSource, parseSource } from "../sources.js";
9
+ import { materializeSource } from "../remote/index.js";
9
10
  import { pluginState } from "../types.js";
10
11
  import { resolveAgents } from "../agents/index.js";
11
12
  import { installPlugin } from "./install/install-one.js";
@@ -18,7 +19,7 @@ export { installPlugin, contentHash } from "./install/install-one.js";
18
19
  * marketplace update, already on disk), a local directory (no clone, no
19
20
  * cleanup), or a GitHub source (clone to a temp dir, cleaned up by the caller).
20
21
  */
21
- function prepareSource(opts, parsed, sourceRef) {
22
+ async function prepareSource(opts, parsed, sourceRef) {
22
23
  if (opts.preparedSourceDir) {
23
24
  const workRoot = resolve(opts.preparedSourceDir);
24
25
  return {
@@ -44,8 +45,11 @@ function prepareSource(opts, parsed, sourceRef) {
44
45
  }
45
46
  const tmp = mkdtempSync(join(tmpdir(), "adg-clone-"));
46
47
  try {
47
- cloneGitHub({ ...parsed, ref: sourceRef }, tmp, { sparse: opts.sparse, runner: opts.gitRunner });
48
- const resolvedRevision = gitRevision(tmp);
48
+ const mat = await materializeSource({ ...parsed, ref: sourceRef }, tmp, {
49
+ sparse: opts.sparse,
50
+ runner: opts.gitRunner,
51
+ });
52
+ const resolvedRevision = mat.resolvedRevision ?? gitRevision(tmp);
49
53
  return {
50
54
  workRoot: tmp,
51
55
  resolvedRevision,
@@ -103,7 +107,7 @@ export async function addPlugins(opts) {
103
107
  if (parsed.kind === "github" && parsed.path) {
104
108
  throw new Error("GitHub subdirectory sources are not supported; define a marketplace and select with --plugin or --all");
105
109
  }
106
- const prepared = prepareSource(opts, parsed, sourceRef);
110
+ const prepared = await prepareSource(opts, parsed, sourceRef);
107
111
  const { workRoot, buildOrigin, resolvedRevision } = prepared;
108
112
  let cleanup = prepared.cleanup;
109
113
  let originDirOverride;
@@ -1,5 +1,6 @@
1
1
  import { gitRemoteRevision } from "../sources.js";
2
2
  import { cloneGitHub, gitRevision, parseGitHubSource } from "../sources.js";
3
+ import { materializeSource, resolveRemoteRevision } from "../remote/index.js";
3
4
  import { mkdtempSync, rmSync } from "node:fs";
4
5
  import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
@@ -123,7 +124,7 @@ export async function updatePlugins(opts) {
123
124
  opts.onProgress?.({ kind: "check", ...position, source: group.source });
124
125
  const lock = readLock(lockPath(opts.pluginsDir));
125
126
  const revisions = group.installed.map((name) => lock.plugins[name]?.resolvedRevision).filter((revision) => Boolean(revision));
126
- const remoteRevision = (opts.revisionResolver ?? gitRemoteRevision)(group.source, group.ref);
127
+ const remoteRevision = await (opts.revisionResolver ?? resolveRemoteRevision)(group.source, group.ref);
127
128
  if (!opts.all && remoteRevision && revisions.length === group.installed.length && revisions.every((revision) => revision === remoteRevision)) {
128
129
  remote.push({ source: group.source, ...(group.ref ? { ref: group.ref } : {}), updated: [], unchanged: [...group.installed].sort(), deleted: [], available: [] });
129
130
  continue;
@@ -156,8 +157,11 @@ export async function updatePlugins(opts) {
156
157
  try {
157
158
  const parsed = parseGitHubSource(group.source);
158
159
  opts.onProgress?.({ kind: "fetch", ...position, source: group.source, ...(group.ref ? { ref: group.ref } : {}) });
159
- cloneGitHub({ ...parsed, ref: group.ref }, checkout, { runner: opts.gitRunner });
160
- const resolvedRevision = gitRevision(checkout);
160
+ const mat = await materializeSource({ ...parsed, ref: group.ref }, checkout, {
161
+ runner: opts.gitRunner,
162
+ resolvedRevision: remoteRevision,
163
+ });
164
+ const resolvedRevision = mat.resolvedRevision ?? gitRevision(checkout);
161
165
  let requestIndex = 0;
162
166
  for (const request of requests) {
163
167
  opts.onProgress?.({
@@ -0,0 +1,241 @@
1
+ import { Readable } from "node:stream";
2
+ import { pipeline } from "node:stream/promises";
3
+ import * as tar from "tar";
4
+ import { readdirSync, rmSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
7
+ import { getTracer } from "../telemetry.js";
8
+ import { runSubprocessSync } from "../subprocess.js";
9
+ import { cloneGitHub, defaultGitRunner, gitRemoteRevision, gitRevision, parseGitHubSource, } from "../sources.js";
10
+ const GIT_SHA_RE = /^[0-9a-f]{40}$/i;
11
+ const DEFAULT_API_TIMEOUT_MS = 10_000;
12
+ const DEFAULT_DOWNLOAD_TIMEOUT_MS = 60_000;
13
+ let cachedGhToken = undefined;
14
+ /**
15
+ * Resolve a GitHub token from environment variables or the `gh` CLI.
16
+ * Memoizes the result across the process lifetime to avoid spawning `gh` repeatedly.
17
+ */
18
+ export function getGitHubToken() {
19
+ if (cachedGhToken !== undefined) {
20
+ return cachedGhToken;
21
+ }
22
+ const envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
23
+ if (envToken?.trim()) {
24
+ cachedGhToken = envToken.trim();
25
+ return cachedGhToken;
26
+ }
27
+ try {
28
+ const result = runSubprocessSync("gh", ["auth", "token"], {
29
+ encoding: "utf-8",
30
+ stdio: ["ignore", "pipe", "ignore"],
31
+ timeout: 5000,
32
+ });
33
+ if (result.status === 0 && result.stdout?.trim()) {
34
+ cachedGhToken = result.stdout.trim();
35
+ return cachedGhToken;
36
+ }
37
+ }
38
+ catch {
39
+ // gh not installed or not authenticated
40
+ }
41
+ cachedGhToken = null;
42
+ return null;
43
+ }
44
+ /** For tests only: reset cached token state. */
45
+ export function resetGitHubTokenCache() {
46
+ cachedGhToken = undefined;
47
+ }
48
+ /**
49
+ * Format a structured diagnostic message when remote resolution fails across all tiers.
50
+ */
51
+ export function formatRemoteDiagnostic(source, errors) {
52
+ const parts = [`${source} could not be resolved across available transports:`];
53
+ if (errors.api)
54
+ parts.push(` • GitHub API: ${errors.api}`);
55
+ if (errors.gh)
56
+ parts.push(` • GitHub CLI: ${errors.gh}`);
57
+ if (errors.git)
58
+ parts.push(` • Git CLI: ${errors.git}`);
59
+ const hasNetworkError = [errors.api, errors.gh, errors.git].some((e) => e && /(ECONNRESET|SSL_ERROR|framing layer|ETIMEDOUT|fetch failed|Could not resolve host)/i.test(e));
60
+ if (hasNetworkError) {
61
+ parts.push(` 💡 Network reset or blocked connection detected. If in a restricted network environment, configure a proxy (export all_proxy=... or git config http.proxy) or run \`gh auth login\`.`);
62
+ }
63
+ return parts.join("\n");
64
+ }
65
+ /**
66
+ * Resolves the immutable 40-character commit SHA for a remote GitHub repository.
67
+ *
68
+ * Employs a three-tier transport pipeline:
69
+ * 1. HTTPS REST API (api.github.com) - direct, fast, supports token
70
+ * 2. `gh` CLI (gh api) - inherits system credentials and enterprise config
71
+ * 3. Git CLI (git ls-remote) - traditional git transport fallback
72
+ */
73
+ export async function resolveRemoteRevision(source, ref, opts = {}) {
74
+ if (ref && GIT_SHA_RE.test(ref)) {
75
+ return ref.toLowerCase();
76
+ }
77
+ let parsed;
78
+ try {
79
+ parsed = parseGitHubSource(source);
80
+ }
81
+ catch {
82
+ // Not a GitHub source (e.g. generic git URL); delegate straight to gitRemoteRevision
83
+ return gitRemoteRevision(source, ref);
84
+ }
85
+ const effectiveRef = ref || parsed.ref || "HEAD";
86
+ const tracer = getTracer();
87
+ return tracer.startActiveSpan("resolveRemoteRevision", { kind: SpanKind.INTERNAL }, async (span) => {
88
+ span.setAttribute("remote.source", parsed.source);
89
+ span.setAttribute("remote.ref", effectiveRef);
90
+ const errors = {};
91
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_API_TIMEOUT_MS;
92
+ const token = opts.token !== undefined ? opts.token : getGitHubToken();
93
+ // ── Tier 1: HTTPS REST API ──────────────────────────────────────────────
94
+ try {
95
+ const apiUrl = `https://api.github.com/repos/${parsed.owner}/${parsed.repo}/commits/${encodeURIComponent(effectiveRef)}`;
96
+ const headers = {
97
+ Accept: "application/vnd.github+json",
98
+ "User-Agent": "adg-cli",
99
+ "X-GitHub-Api-Version": "2022-11-28",
100
+ };
101
+ if (token) {
102
+ headers.Authorization = `Bearer ${token}`;
103
+ }
104
+ const response = await fetch(apiUrl, {
105
+ headers,
106
+ signal: AbortSignal.timeout(timeoutMs),
107
+ });
108
+ if (response.ok) {
109
+ const body = (await response.json());
110
+ if (typeof body.sha === "string" && GIT_SHA_RE.test(body.sha)) {
111
+ span.setAttribute("remote.transport", "api");
112
+ span.setAttribute("remote.revision", body.sha);
113
+ return body.sha.toLowerCase();
114
+ }
115
+ }
116
+ else {
117
+ errors.api = `HTTP ${response.status} ${response.statusText}`;
118
+ }
119
+ }
120
+ catch (err) {
121
+ errors.api = err instanceof Error ? err.message : String(err);
122
+ }
123
+ // ── Tier 2: gh CLI (GitHub CLI) ─────────────────────────────────────────
124
+ try {
125
+ const endpoint = `repos/${parsed.owner}/${parsed.repo}/commits/${encodeURIComponent(effectiveRef)}`;
126
+ const result = runSubprocessSync("gh", ["api", endpoint, "--jq", ".sha"], {
127
+ encoding: "utf-8",
128
+ stdio: ["ignore", "pipe", "pipe"],
129
+ timeout: timeoutMs,
130
+ });
131
+ if (result.status === 0 && result.stdout?.trim()) {
132
+ const sha = result.stdout.trim();
133
+ if (GIT_SHA_RE.test(sha)) {
134
+ span.setAttribute("remote.transport", "gh");
135
+ span.setAttribute("remote.revision", sha);
136
+ return sha.toLowerCase();
137
+ }
138
+ }
139
+ else {
140
+ const stderr = typeof result.stderr === "string" ? result.stderr.trim() : "";
141
+ errors.gh = stderr || `Exit code ${result.status}`;
142
+ }
143
+ }
144
+ catch (err) {
145
+ errors.gh = err instanceof Error ? err.message : String(err);
146
+ }
147
+ // ── Tier 3: Git CLI (ls-remote) ─────────────────────────────────────────
148
+ try {
149
+ const gitResult = gitRemoteRevision(parsed.source, effectiveRef);
150
+ if (gitResult && GIT_SHA_RE.test(gitResult)) {
151
+ span.setAttribute("remote.transport", "git");
152
+ span.setAttribute("remote.revision", gitResult);
153
+ return gitResult.toLowerCase();
154
+ }
155
+ errors.git = "No ref matched in ls-remote output";
156
+ }
157
+ catch (err) {
158
+ errors.git = err instanceof Error ? err.message : String(err);
159
+ }
160
+ opts.onDiagnostic?.(errors);
161
+ span.setStatus({ code: SpanStatusCode.ERROR, message: "All remote revision resolvers failed" });
162
+ return undefined;
163
+ });
164
+ }
165
+ /**
166
+ * Materializes a remote repository source into a local directory.
167
+ *
168
+ * Prefers streaming GitHub Tarball extraction via `node-tar` when full source is needed,
169
+ * avoiding git smart HTTP transport and SNI blocks. Falls back to `cloneGitHub` when
170
+ * sparse checkout is requested or tarball streaming encounters issues.
171
+ *
172
+ * An injected test `runner` is honored directly to preserve offline mock hermeticity,
173
+ * unless `opts.preferTarball` is explicitly requested.
174
+ */
175
+ export async function materializeSource(source, destDir, opts = {}) {
176
+ const runner = opts.runner ?? defaultGitRunner;
177
+ const isSparse = Boolean(opts.sparse && opts.sparse.filter(Boolean).length > 0);
178
+ const shouldAttemptTarball = !isSparse && (!opts.runner || opts.preferTarball);
179
+ if (!shouldAttemptTarball) {
180
+ cloneGitHub(source, destDir, { sparse: opts.sparse, runner });
181
+ const revision = opts.resolvedRevision ?? gitRevision(destDir);
182
+ return { resolvedRevision: revision, transport: "git" };
183
+ }
184
+ const tracer = getTracer();
185
+ return tracer.startActiveSpan("materializeSource", { kind: SpanKind.INTERNAL }, async (span) => {
186
+ span.setAttribute("remote.source", source.source);
187
+ const effectiveRef = source.ref || "HEAD";
188
+ span.setAttribute("remote.ref", effectiveRef);
189
+ // ── Tier 1: GitHub Tarball Streaming ────────────────────────────────────
190
+ try {
191
+ const token = opts.token !== undefined ? opts.token : getGitHubToken();
192
+ const tarballUrl = `https://api.github.com/repos/${source.owner}/${source.repo}/tarball/${encodeURIComponent(effectiveRef)}`;
193
+ const headers = {
194
+ Accept: "application/vnd.github+json",
195
+ "User-Agent": "adg-cli",
196
+ "X-GitHub-Api-Version": "2022-11-28",
197
+ };
198
+ if (token) {
199
+ headers.Authorization = `Bearer ${token}`;
200
+ }
201
+ const response = await fetch(tarballUrl, {
202
+ headers,
203
+ redirect: "follow",
204
+ signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_DOWNLOAD_TIMEOUT_MS),
205
+ });
206
+ if (response.ok && response.body) {
207
+ await pipeline(Readable.fromWeb(response.body), tar.x({ cwd: destDir, strip: 1 }));
208
+ let resolvedRevision = opts.resolvedRevision;
209
+ if (!resolvedRevision) {
210
+ // Resolve revision if not provided upfront
211
+ resolvedRevision = await resolveRemoteRevision(source.source, effectiveRef, { token });
212
+ }
213
+ span.setAttribute("remote.transport", "tarball");
214
+ if (resolvedRevision)
215
+ span.setAttribute("remote.revision", resolvedRevision);
216
+ return { resolvedRevision, transport: "tarball" };
217
+ }
218
+ }
219
+ catch (error) {
220
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
221
+ // Proceed to fallback
222
+ }
223
+ // ── Tier 2: Fallback to Git Clone ───────────────────────────────────────
224
+ span.setAttribute("remote.transport", "git");
225
+ // Ensure destination directory is completely empty before git clone,
226
+ // avoiding "destination path already exists and is not an empty directory"
227
+ try {
228
+ for (const entry of readdirSync(destDir)) {
229
+ rmSync(join(destDir, entry), { recursive: true, force: true });
230
+ }
231
+ }
232
+ catch {
233
+ // Ignore cleanup error if directory does not exist yet
234
+ }
235
+ cloneGitHub(source, destDir, { runner });
236
+ const revision = opts.resolvedRevision ?? gitRevision(destDir);
237
+ if (revision)
238
+ span.setAttribute("remote.revision", revision);
239
+ return { resolvedRevision: revision, transport: "git" };
240
+ });
241
+ }
@@ -0,0 +1 @@
1
+ export * from "./client.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rbbtsn0w/adg",
3
- "version": "0.8.1-dev.pr107.f31e5ca",
3
+ "version": "0.9.0-beta.1",
4
4
  "description": "Agent Directory Group (ADG) toolkit — two domains: plugins and skills.",
5
5
  "type": "module",
6
6
  "license": "MIT",