nestedgarden 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2804 @@
1
+ #!/usr/bin/env node
2
+
3
+ // packages/cli/src/main.ts
4
+ import * as fs8 from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ // lib/connect/device-types.ts
8
+ var CLI_PACKAGE_NAME = "nestedgarden";
9
+ var CLI_VERSION = "0.1.0";
10
+ var CONNECT_COMMAND = `npx --yes ${CLI_PACKAGE_NAME}@${CLI_VERSION} connect`;
11
+ var DEFAULT_APP_URL = "https://www.nestedgarden.com";
12
+ var GATEWAY_URL = "https://agent.nestedgarden.com";
13
+ var APPROVED_COLLECT_TTL_SECONDS = 600;
14
+ var DEVICE_POLL_INTERVAL_SECONDS = 5;
15
+ var DEVICE_SLOW_DOWN_STEP_SECONDS = 5;
16
+ var DEVICE_MAX_INTERVAL_SECONDS = 30;
17
+ var HOST_LABEL_MAX_LENGTH = 40;
18
+ var PROJECT_NAME_MAX_LENGTH = 60;
19
+ var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
20
+ var USER_CODE_LENGTH = 8;
21
+ function formatUserCode(code) {
22
+ if (code.length !== USER_CODE_LENGTH) {
23
+ return code;
24
+ }
25
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
26
+ }
27
+ function normalizeUserCode(input) {
28
+ if (typeof input !== "string") {
29
+ return null;
30
+ }
31
+ const compact = input.toUpperCase().replace(/[\s-]/g, "");
32
+ if (compact.length !== USER_CODE_LENGTH) {
33
+ return null;
34
+ }
35
+ for (const ch of compact) {
36
+ if (!USER_CODE_ALPHABET.includes(ch)) {
37
+ return null;
38
+ }
39
+ }
40
+ return compact;
41
+ }
42
+ var VERSION_PATTERN = /^(\d{1,4})\.(\d{1,4})\.(\d{1,4})(?:[-+][0-9A-Za-z.-]{1,40})?$/;
43
+ function parseCliVersion(input) {
44
+ if (typeof input !== "string") {
45
+ return null;
46
+ }
47
+ const match = VERSION_PATTERN.exec(input.trim());
48
+ if (!match) {
49
+ return null;
50
+ }
51
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
52
+ }
53
+ function compareCliVersions(a, b) {
54
+ for (let i = 0; i < 3; i += 1) {
55
+ if (a[i] !== b[i]) {
56
+ return a[i] - b[i];
57
+ }
58
+ }
59
+ return 0;
60
+ }
61
+ var DEVICE_TOOLS = ["claude-code"];
62
+
63
+ // packages/cli/src/commands/connect.ts
64
+ import { spawn } from "node:child_process";
65
+ import * as os3 from "node:os";
66
+
67
+ // packages/cli/src/output.ts
68
+ var COMMANDS = {
69
+ connect: CONNECT_COMMAND,
70
+ resume: `${CONNECT_COMMAND} --resume`,
71
+ doctor: `npx --yes ${CLI_PACKAGE_NAME}@${CLI_VERSION} doctor`,
72
+ disconnect: `npx --yes ${CLI_PACKAGE_NAME}@${CLI_VERSION} disconnect`
73
+ };
74
+ function createProcessContext() {
75
+ return {
76
+ env: process.env,
77
+ cwd: process.cwd(),
78
+ io: {
79
+ out: (line) => {
80
+ process.stdout.write(`${line}
81
+ `);
82
+ },
83
+ err: (line) => {
84
+ process.stderr.write(`${line}
85
+ `);
86
+ }
87
+ },
88
+ platform: process.platform,
89
+ now: () => Date.now(),
90
+ sleep: (ms) => new Promise((resolve3) => {
91
+ setTimeout(resolve3, ms);
92
+ })
93
+ };
94
+ }
95
+ function childEnv(env, extra = {}) {
96
+ return { ...env, ...extra };
97
+ }
98
+ function isTestRun(env) {
99
+ return Boolean(process.env.VITEST || env.VITEST);
100
+ }
101
+ function redactSecrets(text) {
102
+ return text.replace(/(Bearer\s+)\S+/gi, "$1\u3008\uD0A4\u3009").replace(/(?<![A-Za-z0-9_-])ng_[A-Za-z0-9_-]+/g, "\u3008\uD0A4\u3009");
103
+ }
104
+ function summarizeForeignOutput(text, max = 300) {
105
+ const oneLine = redactSecrets(text).replace(/\s+/g, " ").trim();
106
+ if (oneLine.length <= max) {
107
+ return oneLine;
108
+ }
109
+ return `${oneLine.slice(0, max)}\u2026`;
110
+ }
111
+ function displayPath(target, home) {
112
+ if (target === home) {
113
+ return "~";
114
+ }
115
+ if (home !== "/" && target.startsWith(`${home}/`)) {
116
+ return `~${target.slice(home.length)}`;
117
+ }
118
+ return target;
119
+ }
120
+ function okLine(ctx, message) {
121
+ ctx.io.out(`\u2713 ${message}`);
122
+ }
123
+ function warnLine(ctx, message) {
124
+ ctx.io.out(`! ${message}`);
125
+ }
126
+ function failLine(ctx, message) {
127
+ ctx.io.err(`\u2717 ${message}`);
128
+ }
129
+ function describeError(error) {
130
+ const message = error instanceof Error ? error.message : String(error);
131
+ return summarizeForeignOutput(message, 400);
132
+ }
133
+
134
+ // packages/cli/src/api.ts
135
+ var REQUEST_TIMEOUT_MS = 15e3;
136
+ var KEY_PATTERN = /^ng_[A-Za-z0-9_-]{43}$/;
137
+ var ApiError = class extends Error {
138
+ constructor(message, code, status) {
139
+ super(message);
140
+ this.name = "ApiError";
141
+ this.code = code;
142
+ this.status = status;
143
+ }
144
+ };
145
+ function isLoopbackHost(hostname2) {
146
+ return hostname2 === "127.0.0.1" || hostname2 === "localhost" || hostname2 === "[::1]" || hostname2 === "::1";
147
+ }
148
+ function assertAllowedUrl(url, env) {
149
+ if (isTestRun(env) && !isLoopbackHost(url.hostname)) {
150
+ throw new ApiError(`\uC2DC\uD5D8 \uC911\uC5D0\uB294 ${url.host} \uB97C \uBD80\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4 (\uAC00\uC9DC \uC11C\uBC84 \uC8FC\uC18C\uB97C \uB123\uC5B4 \uC8FC\uC138\uC694)`, "blocked_in_test", null);
151
+ }
152
+ }
153
+ function normalizeBaseUrl(raw, label, env) {
154
+ let url;
155
+ try {
156
+ url = new URL(raw.trim());
157
+ } catch {
158
+ throw new ApiError(`${label} \uC8FC\uC18C\uAC00 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4: ${raw}`, "invalid_url", null);
159
+ }
160
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
161
+ throw new ApiError(`${label} \uC8FC\uC18C\uB294 http(s) \uC5EC\uC57C \uD569\uB2C8\uB2E4: ${raw}`, "invalid_url", null);
162
+ }
163
+ if (url.protocol === "http:" && !isLoopbackHost(url.hostname)) {
164
+ throw new ApiError(`${label} \uC8FC\uC18C\uB294 https \uC5EC\uC57C \uD569\uB2C8\uB2E4 (http \uB294 \uC774 \uCEF4\uD4E8\uD130 \uC548\uC758 \uC8FC\uC18C\uB9CC): ${raw}`, "invalid_url", null);
165
+ }
166
+ if (url.username || url.password || url.search || url.hash) {
167
+ throw new ApiError(`${label} \uC8FC\uC18C\uC5D0 \uC0AC\uC6A9\uC790 \uC815\uBCF4\xB7\uC9C8\uC758\uB97C \uB123\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4`, "invalid_url", null);
168
+ }
169
+ assertAllowedUrl(url, env);
170
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
171
+ }
172
+ function resolveServerUrl(flag, env) {
173
+ const raw = flag ?? (env.NESTEDGARDEN_SERVER && env.NESTEDGARDEN_SERVER.trim() !== "" ? env.NESTEDGARDEN_SERVER : DEFAULT_APP_URL);
174
+ return normalizeBaseUrl(raw, "\uC571", env);
175
+ }
176
+ function resolveGatewayUrl(env) {
177
+ const raw = env.NESTEDGARDEN_GATEWAY && env.NESTEDGARDEN_GATEWAY.trim() !== "" ? env.NESTEDGARDEN_GATEWAY : GATEWAY_URL;
178
+ return normalizeBaseUrl(raw, "\uAC8C\uC774\uD2B8\uC6E8\uC774", env);
179
+ }
180
+ async function requestJson(method, target, options, env) {
181
+ const url = new URL(target);
182
+ assertAllowedUrl(url, env);
183
+ const headers = {
184
+ accept: "application/json",
185
+ "user-agent": `nestedgarden-cli/${CLI_VERSION}`
186
+ };
187
+ if (options.body !== void 0) {
188
+ headers["content-type"] = "application/json";
189
+ }
190
+ if (options.bearer !== void 0) {
191
+ headers.authorization = `Bearer ${options.bearer}`;
192
+ }
193
+ const controller = new AbortController();
194
+ const timer = setTimeout(() => {
195
+ controller.abort();
196
+ }, REQUEST_TIMEOUT_MS);
197
+ let response;
198
+ try {
199
+ response = await fetch(url, {
200
+ method,
201
+ headers,
202
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
203
+ redirect: "manual",
204
+ signal: controller.signal
205
+ });
206
+ } catch (error) {
207
+ clearTimeout(timer);
208
+ if (controller.signal.aborted) {
209
+ throw new ApiError(`${url.host} \uAC00 ${REQUEST_TIMEOUT_MS / 1e3}\uCD08 \uC548\uC5D0 \uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4`, "timeout", null);
210
+ }
211
+ const cause = error.cause?.code;
212
+ throw new ApiError(`${url.host} \uC5D0 \uB2FF\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4${cause ? ` (${cause})` : ""}`, "network", null);
213
+ }
214
+ try {
215
+ if (response.status >= 300 && response.status < 400) {
216
+ throw new ApiError(
217
+ `${url.host} \uAC00 \uB2E4\uB978 \uC8FC\uC18C\uB85C \uB118\uAE30\uB824 \uD569\uB2C8\uB2E4 (\uC0C1\uD0DC ${response.status}). \uC8FC\uC18C\uB97C \uD655\uC778\uD574 \uC8FC\uC138\uC694`,
218
+ "redirect",
219
+ response.status
220
+ );
221
+ }
222
+ let text;
223
+ try {
224
+ text = await response.text();
225
+ } catch {
226
+ throw new ApiError(`${url.host} \uC758 \uB2F5\uC744 \uB05D\uAE4C\uC9C0 \uBC1B\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4`, controller.signal.aborted ? "timeout" : "network", null);
227
+ }
228
+ let body = null;
229
+ try {
230
+ body = text === "" ? null : JSON.parse(text);
231
+ } catch {
232
+ body = null;
233
+ }
234
+ return { status: response.status, body, finalUrl: response.url || url.toString() };
235
+ } finally {
236
+ clearTimeout(timer);
237
+ }
238
+ }
239
+ function isPlainObject(value) {
240
+ return value !== null && typeof value === "object" && !Array.isArray(value);
241
+ }
242
+ function successData(body) {
243
+ if (isPlainObject(body) && body.success === true && isPlainObject(body.data)) {
244
+ return body.data;
245
+ }
246
+ return null;
247
+ }
248
+ function errorBody(body) {
249
+ if (isPlainObject(body) && body.success === false) {
250
+ return body;
251
+ }
252
+ return {};
253
+ }
254
+ function apiErrorFrom(response, fallback) {
255
+ const envelope = errorBody(response.body);
256
+ const code = typeof envelope.code === "string" ? envelope.code : `http_${response.status}`;
257
+ const serverMessage = typeof envelope.error === "string" ? redactSecrets(envelope.error).slice(0, 300) : "";
258
+ const message = serverMessage ? `${fallback} (${response.status}): ${serverMessage}` : `${fallback} (${response.status})`;
259
+ return new ApiError(message, code, response.status);
260
+ }
261
+ function isString(value, max = 2e3) {
262
+ return typeof value === "string" && value.length > 0 && value.length <= max;
263
+ }
264
+ function positiveNumber(value) {
265
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
266
+ }
267
+ async function startDeviceAuthorization(server, request, env) {
268
+ const response = await requestJson("POST", `${server}/api/connect/device`, { body: request }, env);
269
+ const data = successData(response.body);
270
+ if (response.status !== 201 && response.status !== 200 || !data) {
271
+ throw apiErrorFrom(response, "\uC5F0\uACB0 \uC694\uCCAD\uC744 \uB9CC\uB4E4\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4");
272
+ }
273
+ if (!isString(data.deviceCode, 200) || !isString(data.userCode, 40) || !isString(data.verificationUri) || !isString(data.verificationUriComplete) || positiveNumber(data.expiresIn) === null) {
274
+ throw new ApiError("\uC11C\uBC84\uC758 \uB2F5\uC774 \uC608\uC0C1\uD55C \uAF34\uC774 \uC544\uB2D9\uB2C8\uB2E4", "bad_response", response.status);
275
+ }
276
+ return {
277
+ data: {
278
+ deviceCode: data.deviceCode,
279
+ userCode: data.userCode,
280
+ verificationUri: data.verificationUri,
281
+ verificationUriComplete: data.verificationUriComplete,
282
+ expiresIn: data.expiresIn,
283
+ interval: positiveNumber(data.interval) ?? 5
284
+ },
285
+ origin: new URL(response.finalUrl).origin
286
+ };
287
+ }
288
+ function parseIssued(data) {
289
+ const key = data.key;
290
+ const agent = data.agent;
291
+ const account = data.account;
292
+ if (data.status !== "issued" || typeof data.agentKey !== "string" || !KEY_PATTERN.test(data.agentKey) || !isPlainObject(key) || !isString(key.id, 100) || !isPlainObject(agent) || !isString(agent.id, 100) || !isString(agent.name, 200) || !isString(data.rootTitle, 400)) {
293
+ return null;
294
+ }
295
+ return {
296
+ status: "issued",
297
+ agentKey: data.agentKey,
298
+ key: {
299
+ id: key.id,
300
+ keyPrefix: typeof key.keyPrefix === "string" ? key.keyPrefix : "",
301
+ label: typeof key.label === "string" ? key.label : ""
302
+ },
303
+ agent: { id: agent.id, name: agent.name, vendor: typeof agent.vendor === "string" ? agent.vendor : "" },
304
+ rootTitle: data.rootTitle,
305
+ account: { email: isPlainObject(account) && typeof account.email === "string" ? account.email : "" },
306
+ gatewayUrl: typeof data.gatewayUrl === "string" ? data.gatewayUrl : ""
307
+ };
308
+ }
309
+ async function pollDeviceToken(server, deviceCode, env) {
310
+ const response = await requestJson("POST", `${server}/api/connect/device/token`, { body: { deviceCode } }, env);
311
+ const data = successData(response.body);
312
+ const envelope = errorBody(response.body);
313
+ if (response.status === 200 && data) {
314
+ const issued = parseIssued(data);
315
+ if (!issued) {
316
+ throw new ApiError("\uC11C\uBC84\uAC00 \uC900 \uD0A4\uC758 \uAF34\uC774 \uC608\uC0C1\uACFC \uB2E4\uB985\uB2C8\uB2E4", "bad_response", response.status);
317
+ }
318
+ return { kind: "issued", data: issued };
319
+ }
320
+ if (response.status === 202 && data) {
321
+ const pending = data;
322
+ return { kind: "pending", interval: positiveNumber(pending.interval) };
323
+ }
324
+ switch (envelope.code) {
325
+ case "slow_down": {
326
+ return { kind: "slow_down", interval: positiveNumber(envelope.interval) };
327
+ }
328
+ case "access_denied": {
329
+ return { kind: "denied" };
330
+ }
331
+ case "expired_token": {
332
+ return { kind: "expired" };
333
+ }
334
+ case "invalid_grant": {
335
+ return { kind: "unknown_code" };
336
+ }
337
+ default: {
338
+ throw apiErrorFrom(response, "\uC2B9\uC778 \uC0C1\uD0DC\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4");
339
+ }
340
+ }
341
+ }
342
+ async function whoami(gateway, key, env) {
343
+ const response = await requestJson("GET", `${gateway}/v1/whoami`, { bearer: key }, env);
344
+ if (response.status === 401) {
345
+ return { ok: false, reason: "unauthorized" };
346
+ }
347
+ const data = successData(response.body);
348
+ if (response.status !== 200 || !data) {
349
+ throw apiErrorFrom(response, "\uAC8C\uC774\uD2B8\uC6E8\uC774\uC5D0\uC11C \uD0A4\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4");
350
+ }
351
+ const agent = data.agent;
352
+ const keyInfo = data.key;
353
+ if (!isPlainObject(agent) || !isString(agent.id, 100) || !isString(data.rootTitle, 400)) {
354
+ throw new ApiError("\uAC8C\uC774\uD2B8\uC6E8\uC774\uC758 \uB2F5\uC774 \uC608\uC0C1\uD55C \uAF34\uC774 \uC544\uB2D9\uB2C8\uB2E4", "bad_response", response.status);
355
+ }
356
+ return {
357
+ ok: true,
358
+ data: {
359
+ agent: {
360
+ id: agent.id,
361
+ name: typeof agent.name === "string" ? agent.name : "",
362
+ vendor: typeof agent.vendor === "string" ? agent.vendor : ""
363
+ },
364
+ key: {
365
+ id: isPlainObject(keyInfo) && typeof keyInfo.id === "string" ? keyInfo.id : "",
366
+ keyPrefix: isPlainObject(keyInfo) && typeof keyInfo.keyPrefix === "string" ? keyInfo.keyPrefix : ""
367
+ },
368
+ rootTitle: data.rootTitle
369
+ }
370
+ };
371
+ }
372
+ async function revokeSelf(gateway, key, env) {
373
+ const response = await requestJson("DELETE", `${gateway}/v1/keys/self`, { bearer: key }, env);
374
+ if (response.status === 401) {
375
+ return { ok: false, reason: "unauthorized" };
376
+ }
377
+ if (response.status === 404) {
378
+ return { ok: false, reason: "not_found" };
379
+ }
380
+ const data = successData(response.body);
381
+ if (response.status !== 200 || !data || data.revoked !== true) {
382
+ throw apiErrorFrom(response, "\uD0A4\uB97C \uD68C\uC218\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4");
383
+ }
384
+ return { ok: true, keyId: typeof data.keyId === "string" ? data.keyId : "" };
385
+ }
386
+
387
+ // packages/cli/src/claude-cli.ts
388
+ import { spawnSync } from "node:child_process";
389
+ import * as fs2 from "node:fs";
390
+ import * as os2 from "node:os";
391
+ import * as path2 from "node:path";
392
+
393
+ // packages/cli/src/paths.ts
394
+ import * as crypto from "node:crypto";
395
+ import * as fs from "node:fs";
396
+ import * as os from "node:os";
397
+ import * as path from "node:path";
398
+ var DEFAULT_MANAGED_SETTINGS_FILES = [
399
+ "/Library/Application Support/ClaudeCode/managed-settings.json",
400
+ "/etc/claude-code/managed-settings.json"
401
+ ];
402
+ function absoluteOrNull(value) {
403
+ if (!value || value.trim() === "") {
404
+ return null;
405
+ }
406
+ return path.resolve(value);
407
+ }
408
+ function homeDirOf(env) {
409
+ return absoluteOrNull(env.HOME) ?? os.homedir();
410
+ }
411
+ function isInside(child, parent) {
412
+ if (child === parent) {
413
+ return true;
414
+ }
415
+ const base = parent.endsWith("/") ? parent : `${parent}/`;
416
+ return child.startsWith(base);
417
+ }
418
+ function resolvePaths(env) {
419
+ const home = homeDirOf(env);
420
+ const xdg = absoluteOrNull(env.XDG_CONFIG_HOME);
421
+ const configDir = absoluteOrNull(env.NESTEDGARDEN_CONFIG_DIR) ?? (xdg ? path.join(xdg, "nestedgarden") : path.join(home, ".config", "nestedgarden"));
422
+ const claudeConfigDir = absoluteOrNull(env.CLAUDE_CONFIG_DIR);
423
+ const claudeDir = claudeConfigDir ?? path.join(home, ".claude");
424
+ const claudeGlobalConfigFile = claudeConfigDir ? path.join(claudeConfigDir, ".claude.json") : path.join(home, ".claude.json");
425
+ const managedOverride = env.NESTEDGARDEN_MANAGED_SETTINGS_PATHS;
426
+ const managedSettingsFiles = managedOverride !== void 0 ? managedOverride.split(":").filter((item) => item !== "") : DEFAULT_MANAGED_SETTINGS_FILES;
427
+ const paths = {
428
+ home,
429
+ configDir,
430
+ keysDir: path.join(configDir, "keys"),
431
+ registryFile: path.join(configDir, "projects.tsv"),
432
+ binDir: path.join(configDir, "bin"),
433
+ helperFile: path.join(configDir, "bin", "headers"),
434
+ pendingDir: path.join(configDir, "pending"),
435
+ backupsDir: path.join(configDir, "backups"),
436
+ settingsAddedFile: path.join(configDir, "settings-added.json"),
437
+ legacyHelperFile: path.join(configDir, "otel-headers.sh"),
438
+ claudeDir,
439
+ claudeSettingsFile: path.join(claudeDir, "settings.json"),
440
+ claudeGlobalConfigFile,
441
+ managedSettingsFiles
442
+ };
443
+ assertTestSandbox(paths, env);
444
+ return paths;
445
+ }
446
+ function assertTestSandbox(paths, env) {
447
+ if (!isTestRun(env)) {
448
+ return;
449
+ }
450
+ const realHome = os.userInfo().homedir;
451
+ const targets = [paths.home, paths.configDir, paths.claudeDir, paths.claudeGlobalConfigFile];
452
+ for (const target of targets) {
453
+ if (isInside(target, realHome)) {
454
+ throw new Error(`\uC2DC\uD5D8 \uC911\uC5D0\uB294 \uC9C4\uC9DC \uD648 \uD3F4\uB354 \uC544\uB798\uB97C \uC4F0\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4: ${target}`);
455
+ }
456
+ }
457
+ }
458
+ function safeRealpath(target) {
459
+ try {
460
+ return fs.realpathSync.native(target);
461
+ } catch {
462
+ return null;
463
+ }
464
+ }
465
+ function readTextIfExists(file) {
466
+ try {
467
+ return fs.readFileSync(file, "utf8");
468
+ } catch (error) {
469
+ if (error.code === "ENOENT") {
470
+ return null;
471
+ }
472
+ throw error;
473
+ }
474
+ }
475
+ function fileMode(file) {
476
+ try {
477
+ return fs.statSync(file).mode & 511;
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+ function isExecutableFile(file) {
483
+ try {
484
+ const stat = fs.statSync(file);
485
+ if (!stat.isFile()) {
486
+ return false;
487
+ }
488
+ fs.accessSync(file, fs.constants.X_OK);
489
+ return true;
490
+ } catch {
491
+ return false;
492
+ }
493
+ }
494
+ function ensurePrivateDir(dir) {
495
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
496
+ fs.chmodSync(dir, 448);
497
+ }
498
+ function writeFileAtomic(file, content, mode) {
499
+ const dir = path.dirname(file);
500
+ const temp = path.join(dir, `.${path.basename(file)}.tmp-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
501
+ try {
502
+ fs.writeFileSync(temp, content, { mode });
503
+ fs.chmodSync(temp, mode);
504
+ fs.renameSync(temp, file);
505
+ } catch (error) {
506
+ try {
507
+ fs.unlinkSync(temp);
508
+ } catch {
509
+ }
510
+ throw error;
511
+ }
512
+ }
513
+ function removeIfExists(file) {
514
+ try {
515
+ fs.unlinkSync(file);
516
+ return true;
517
+ } catch (error) {
518
+ if (error.code === "ENOENT") {
519
+ return false;
520
+ }
521
+ throw error;
522
+ }
523
+ }
524
+
525
+ // packages/cli/src/claude-cli.ts
526
+ var MCP_SERVER_NAME = "nestedgarden";
527
+ var STDIN_JSON_SINCE = [2, 1, 327];
528
+ var CLAUDE_TIMEOUT_MS = 3e4;
529
+ var CLAUDE_VERSION_TIMEOUT_MS = 15e3;
530
+ function findOnPath(pathValue) {
531
+ for (const dir of (pathValue ?? "").split(":")) {
532
+ if (dir === "" || !path2.isAbsolute(dir)) {
533
+ continue;
534
+ }
535
+ const candidate = path2.join(dir, "claude");
536
+ if (isExecutableFile(candidate)) {
537
+ return { path: candidate, source: "path" };
538
+ }
539
+ }
540
+ return null;
541
+ }
542
+ function listDirs(dir) {
543
+ try {
544
+ return fs2.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
545
+ } catch {
546
+ return [];
547
+ }
548
+ }
549
+ function findAppBinary(versionDir) {
550
+ const queue = [{ dir: versionDir, depth: 0 }];
551
+ while (queue.length > 0) {
552
+ const { dir, depth } = queue.shift();
553
+ for (const name of listDirs(dir)) {
554
+ const child = path2.join(dir, name);
555
+ if (name === "claude.app") {
556
+ const binary = path2.join(child, "Contents", "MacOS", "claude");
557
+ if (isExecutableFile(binary)) {
558
+ return binary;
559
+ }
560
+ } else if (depth < 2) {
561
+ queue.push({ dir: child, depth: depth + 1 });
562
+ }
563
+ }
564
+ }
565
+ return null;
566
+ }
567
+ function findDesktopCopy(home) {
568
+ const base = path2.join(home, "Library", "Application Support", "Claude", "claude-code");
569
+ const versions = listDirs(base).map((name) => ({ name, version: parseCliVersion(name) })).filter((item) => item.version !== null).sort((a, b) => compareCliVersions(b.version, a.version));
570
+ for (const item of versions) {
571
+ const binary = findAppBinary(path2.join(base, item.name));
572
+ if (binary) {
573
+ return { path: binary, source: "desktop" };
574
+ }
575
+ }
576
+ return null;
577
+ }
578
+ function findClaude(env, platform, home) {
579
+ const found = findOnPath(env.PATH) ?? (platform === "darwin" ? findDesktopCopy(home) : null);
580
+ if (found && isTestRun(env)) {
581
+ const realBinary = safeRealpath(found.path) ?? found.path;
582
+ const realTemp = safeRealpath(os2.tmpdir()) ?? os2.tmpdir();
583
+ if (!isInside(realBinary, realTemp) || isInside(realBinary, os2.userInfo().homedir)) {
584
+ throw new Error("\uC2DC\uD5D8 \uC911\uC5D0\uB294 \uC9C4\uC9DC Claude Code \uB97C \uBD80\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4 (PATH \uB9E8 \uC55E\uC5D0 \uC784\uC2DC \uD3F4\uB354\uC758 \uAC00\uC9DC claude \uB97C \uB450\uC138\uC694)");
585
+ }
586
+ }
587
+ return found;
588
+ }
589
+ function runClaude(binary, args, options) {
590
+ const result = spawnSync(binary.path, args, {
591
+ cwd: options.cwd,
592
+ env: childEnv(options.env),
593
+ input: options.input ?? "",
594
+ encoding: "utf8",
595
+ timeout: CLAUDE_TIMEOUT_MS,
596
+ stdio: ["pipe", "pipe", "pipe"]
597
+ });
598
+ const output = `${typeof result.stderr === "string" ? result.stderr : ""} ${typeof result.stdout === "string" ? result.stdout : ""}`;
599
+ if (result.error) {
600
+ return { ok: false, summary: summarizeForeignOutput(result.error.message) };
601
+ }
602
+ const summary = summarizeForeignOutput(output) || `\uC885\uB8CC \uCF54\uB4DC ${result.status}`;
603
+ return { ok: result.status === 0, summary };
604
+ }
605
+ function claudeVersion(binary, env) {
606
+ const result = spawnSync(binary.path, ["--version"], {
607
+ env: childEnv(env),
608
+ encoding: "utf8",
609
+ timeout: CLAUDE_VERSION_TIMEOUT_MS,
610
+ stdio: ["ignore", "pipe", "pipe"]
611
+ });
612
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
613
+ const match = /(\d+\.\d+\.\d+)/.exec(stdout);
614
+ return match ? parseCliVersion(match[1]) : null;
615
+ }
616
+ function chooseMcpAddMode(env, version) {
617
+ if (env.CLAUDE_CODE_CHILD_SESSION) {
618
+ return "argv";
619
+ }
620
+ if (version !== null && compareCliVersions(version, STDIN_JSON_SINCE) < 0) {
621
+ return "argv";
622
+ }
623
+ return "stdin";
624
+ }
625
+ function mcpUrlFor(gatewayUrl) {
626
+ return `${gatewayUrl.replace(/\/+$/, "")}/mcp`;
627
+ }
628
+ function attachMcp(binary, root, options) {
629
+ const mode = chooseMcpAddMode(options.env, options.version);
630
+ const before = readMcpEntry(options.globalConfigFile, root, { url: mcpUrlFor(options.gatewayUrl), key: null });
631
+ let replaced = false;
632
+ if (before.exists) {
633
+ const removed = runClaude(binary, ["mcp", "remove", MCP_SERVER_NAME, "--scope", "local"], { cwd: root, env: options.env });
634
+ if (!removed.ok) {
635
+ return { ok: false, mode, replaced: false, summary: `\uC788\uB358 nestedgarden MCP \uB97C \uC9C0\uC6B0\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${removed.summary}` };
636
+ }
637
+ replaced = true;
638
+ }
639
+ const json = JSON.stringify({
640
+ type: "http",
641
+ url: mcpUrlFor(options.gatewayUrl),
642
+ headers: { Authorization: `Bearer ${options.key}` }
643
+ });
644
+ const args = ["mcp", "add-json", MCP_SERVER_NAME, mode === "argv" ? json : "-", "--scope", "local"];
645
+ const added = runClaude(binary, args, { cwd: root, env: options.env, input: mode === "stdin" ? json : "" });
646
+ return { ok: added.ok, mode, replaced, summary: added.summary };
647
+ }
648
+ function detachMcp(binary, root, options) {
649
+ const before = readMcpEntry(options.globalConfigFile, root, { url: "", key: null });
650
+ if (!before.exists) {
651
+ return { ok: true, existed: false, summary: "" };
652
+ }
653
+ const removed = runClaude(binary, ["mcp", "remove", MCP_SERVER_NAME, "--scope", "local"], { cwd: root, env: options.env });
654
+ return { ok: removed.ok, existed: true, summary: removed.summary };
655
+ }
656
+ function isPlainObject2(value) {
657
+ return value !== null && typeof value === "object" && !Array.isArray(value);
658
+ }
659
+ function readProjects(globalConfigFile) {
660
+ let text;
661
+ try {
662
+ text = readTextIfExists(globalConfigFile);
663
+ } catch {
664
+ return null;
665
+ }
666
+ if (text === null) {
667
+ return null;
668
+ }
669
+ try {
670
+ const parsed = JSON.parse(text);
671
+ if (isPlainObject2(parsed) && isPlainObject2(parsed.projects)) {
672
+ return parsed.projects;
673
+ }
674
+ } catch {
675
+ return null;
676
+ }
677
+ return null;
678
+ }
679
+ function nestedgardenServerOf(project) {
680
+ if (!isPlainObject2(project) || !isPlainObject2(project.mcpServers)) {
681
+ return null;
682
+ }
683
+ const server = project.mcpServers[MCP_SERVER_NAME];
684
+ return isPlainObject2(server) ? server : null;
685
+ }
686
+ function sameRoot(key, root) {
687
+ if (key === root || key.normalize("NFC") === root.normalize("NFC")) {
688
+ return true;
689
+ }
690
+ const real = safeRealpath(key);
691
+ return real !== null && real === root;
692
+ }
693
+ function stripSlash(value) {
694
+ return value.trim().replace(/\/+$/, "").toLowerCase();
695
+ }
696
+ function readMcpEntry(globalConfigFile, root, expected) {
697
+ const projects = readProjects(globalConfigFile);
698
+ if (!projects) {
699
+ return { exists: false, urlMatches: false, keyMatches: null };
700
+ }
701
+ const key = Object.prototype.hasOwnProperty.call(projects, root) ? root : Object.keys(projects).find((candidate) => nestedgardenServerOf(projects[candidate]) !== null && sameRoot(candidate, root));
702
+ const server = key !== void 0 ? nestedgardenServerOf(projects[key]) : null;
703
+ if (!server) {
704
+ return { exists: false, urlMatches: false, keyMatches: null };
705
+ }
706
+ const urlMatches = typeof server.url === "string" && expected.url !== "" && stripSlash(server.url) === stripSlash(expected.url);
707
+ let keyMatches = null;
708
+ if (expected.key !== null) {
709
+ const headers = isPlainObject2(server.headers) ? server.headers : {};
710
+ const headerName = Object.keys(headers).find((name) => name.toLowerCase() === "authorization");
711
+ const value = headerName ? headers[headerName] : void 0;
712
+ keyMatches = typeof value === "string" && value.trim() === `Bearer ${expected.key}`;
713
+ }
714
+ return { exists: true, urlMatches, keyMatches };
715
+ }
716
+ function listMcpRoots(globalConfigFile) {
717
+ const projects = readProjects(globalConfigFile);
718
+ if (!projects) {
719
+ return [];
720
+ }
721
+ return Object.keys(projects).filter((root) => nestedgardenServerOf(projects[root]) !== null).map((root) => ({ root, exists: fs2.existsSync(root) }));
722
+ }
723
+
724
+ // packages/cli/src/claude-settings.ts
725
+ import * as fs3 from "node:fs";
726
+ import * as path3 from "node:path";
727
+ var ENV_ENABLE_TELEMETRY = "CLAUDE_CODE_ENABLE_TELEMETRY";
728
+ var ENV_METRICS_EXPORTER = "OTEL_METRICS_EXPORTER";
729
+ var ENV_LOGS_EXPORTER = "OTEL_LOGS_EXPORTER";
730
+ var ENV_PROTOCOL = "OTEL_EXPORTER_OTLP_PROTOCOL";
731
+ var ENV_ENDPOINT = "OTEL_EXPORTER_OTLP_ENDPOINT";
732
+ var ENV_TEMPORALITY = "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE";
733
+ var SIGNAL_ENDPOINTS = [
734
+ ["OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "/v1/metrics"],
735
+ ["OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "/v1/logs"]
736
+ ];
737
+ var SIGNAL_PROTOCOLS = ["OTEL_EXPORTER_OTLP_METRICS_PROTOCOL", "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL"];
738
+ var HEADER_KEYS = ["OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_METRICS_HEADERS", "OTEL_EXPORTER_OTLP_LOGS_HEADERS"];
739
+ var ACCEPTED_PROTOCOLS = ["http/json", "http/protobuf"];
740
+ var PROMPT_LOG_KEYS = ["OTEL_LOG_USER_PROMPTS", "OTEL_LOG_TOOL_DETAILS"];
741
+ var MAX_BACKUPS = 3;
742
+ function isPlainObject3(value) {
743
+ return value !== null && typeof value === "object" && !Array.isArray(value);
744
+ }
745
+ function parseSettings(text) {
746
+ if (text === null) {
747
+ return { ok: true, value: {} };
748
+ }
749
+ const body = text.replace(/^\uFEFF/, "");
750
+ if (body.trim() === "") {
751
+ return { ok: true, value: {} };
752
+ }
753
+ let parsed;
754
+ try {
755
+ parsed = JSON.parse(body);
756
+ } catch {
757
+ return {
758
+ ok: false,
759
+ refusal: { code: "invalid_json", message: "JSON \uD615\uC2DD\uC774 \uAE68\uC838 \uC788\uC5B4 \uC77D\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uACE0\uCE5C \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694." }
760
+ };
761
+ }
762
+ if (!isPlainObject3(parsed)) {
763
+ return { ok: false, refusal: { code: "not_object", message: "\uB9E8 \uC704\uAC00 JSON \uAC1D\uCCB4({ \u2026 })\uAC00 \uC544\uB2D9\uB2C8\uB2E4." } };
764
+ }
765
+ return { ok: true, value: parsed };
766
+ }
767
+ function refusalResult(refusal, warnings = []) {
768
+ return { next: null, changes: [], refusal, addedEnv: {}, warnings };
769
+ }
770
+ function envValue(env, key) {
771
+ const value = env[key];
772
+ if (value === void 0 || value === null) {
773
+ return null;
774
+ }
775
+ return String(value).trim();
776
+ }
777
+ function isTruthyFlag(value) {
778
+ return ["1", "true", "yes", "on"].includes(value.toLowerCase());
779
+ }
780
+ function listHas(value, item) {
781
+ return value.split(",").map((part) => part.trim().toLowerCase()).includes(item);
782
+ }
783
+ function canonicalUrl(value) {
784
+ const trimmed = value.trim();
785
+ try {
786
+ const url = new URL(trimmed);
787
+ return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, "")}${url.search}`.toLowerCase();
788
+ } catch {
789
+ return trimmed.replace(/\/+$/, "");
790
+ }
791
+ }
792
+ function sameUrl(a, b) {
793
+ return canonicalUrl(a) === canonicalUrl(b);
794
+ }
795
+ function hostOf(value) {
796
+ try {
797
+ return new URL(value).host || "\uC54C \uC218 \uC5C6\uB294 \uACF3";
798
+ } catch {
799
+ return "\uC54C \uC218 \uC5C6\uB294 \uACF3";
800
+ }
801
+ }
802
+ function normalizeCommandPath(value, home) {
803
+ let command = value.trim();
804
+ if (command.length >= 2 && (command[0] === "'" || command[0] === '"') && command[command.length - 1] === command[0]) {
805
+ command = command.slice(1, -1);
806
+ }
807
+ if (command.startsWith("~/")) {
808
+ command = path3.join(home, command.slice(2));
809
+ } else if (command.startsWith("$HOME/")) {
810
+ command = path3.join(home, command.slice(6));
811
+ } else if (command.startsWith("${HOME}/")) {
812
+ command = path3.join(home, command.slice(8));
813
+ }
814
+ return path3.normalize(command);
815
+ }
816
+ function headerKeyOf(pair) {
817
+ const at = pair.indexOf("=");
818
+ return (at < 0 ? pair : pair.slice(0, at)).trim().toLowerCase();
819
+ }
820
+ function mergeTelemetrySettings(current, options) {
821
+ const parsed = parseSettings(current);
822
+ if (!parsed.ok) {
823
+ return refusalResult(parsed.refusal);
824
+ }
825
+ const settings = parsed.value;
826
+ const rawEnv = settings.env;
827
+ if (rawEnv !== void 0 && !isPlainObject3(rawEnv)) {
828
+ return refusalResult({
829
+ code: "env_not_object",
830
+ message: 'env \uAC00 \uAC1D\uCCB4\uAC00 \uC544\uB2D9\uB2C8\uB2E4. {"env": { \u2026 }} \uAF34\uB85C \uACE0\uCE5C \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.'
831
+ });
832
+ }
833
+ const env = rawEnv ? { ...rawEnv } : {};
834
+ const conflicts = [];
835
+ const changes = [];
836
+ const addedEnv = {};
837
+ const warnings = [];
838
+ const endpoint = options.endpoint.replace(/\/+$/, "");
839
+ const add = (key, value) => {
840
+ env[key] = value;
841
+ addedEnv[key] = value;
842
+ changes.push(`env.${key}=${value} \uCD94\uAC00`);
843
+ };
844
+ const enable = envValue(env, ENV_ENABLE_TELEMETRY);
845
+ if (enable === null) {
846
+ add(ENV_ENABLE_TELEMETRY, "1");
847
+ } else if (!isTruthyFlag(enable)) {
848
+ conflicts.push({
849
+ code: "telemetry_disabled",
850
+ message: `env.${ENV_ENABLE_TELEMETRY} \uAC00 \uAEBC\uC838 \uC788\uC2B5\uB2C8\uB2E4 (\uAC12 "${enable}"). \uC77C\uBD80\uB7EC \uB048 \uAC83\uC774\uBA74 \uC5F0\uACB0\uD558\uC9C0 \uB9C8\uC138\uC694. \uCF1C\uB824\uBA74 \uADF8 \uC904\uC744 \uC9C0\uC6B0\uAC70\uB098 1 \uB85C \uBC14\uAFBC \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`
851
+ });
852
+ }
853
+ for (const key of [ENV_METRICS_EXPORTER, ENV_LOGS_EXPORTER]) {
854
+ const value = envValue(env, key);
855
+ if (value === null) {
856
+ add(key, "otlp");
857
+ } else if (!listHas(value, "otlp")) {
858
+ conflicts.push({
859
+ code: "exporter_without_otlp",
860
+ message: `env.${key} \uC5D0 otlp \uAC00 \uC5C6\uC2B5\uB2C8\uB2E4 (\uAC12 "${value}"). \uC27C\uD45C\uB85C otlp \uB97C \uB354\uD558\uAC70\uB098 \uADF8 \uC904\uC744 \uC9C0\uC6B4 \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`
861
+ });
862
+ }
863
+ }
864
+ const protocol = envValue(env, ENV_PROTOCOL);
865
+ if (protocol === null) {
866
+ add(ENV_PROTOCOL, "http/json");
867
+ } else if (!ACCEPTED_PROTOCOLS.includes(protocol.toLowerCase())) {
868
+ env[ENV_PROTOCOL] = "http/json";
869
+ changes.push(`env.${ENV_PROTOCOL}: ${protocol} \u2192 http/json (\uAC8C\uC774\uD2B8\uC6E8\uC774\uB294 HTTP \uB9CC \uBC1B\uC2B5\uB2C8\uB2E4)`);
870
+ }
871
+ for (const key of SIGNAL_PROTOCOLS) {
872
+ const value = envValue(env, key);
873
+ if (value !== null && !ACCEPTED_PROTOCOLS.includes(value.toLowerCase())) {
874
+ env[key] = "http/json";
875
+ changes.push(`env.${key}: ${value} \u2192 http/json (\uAC8C\uC774\uD2B8\uC6E8\uC774\uB294 HTTP \uB9CC \uBC1B\uC2B5\uB2C8\uB2E4)`);
876
+ }
877
+ }
878
+ const currentEndpoint = envValue(env, ENV_ENDPOINT);
879
+ if (currentEndpoint === null) {
880
+ add(ENV_ENDPOINT, endpoint);
881
+ } else if (!sameUrl(currentEndpoint, endpoint)) {
882
+ conflicts.push({
883
+ code: "other_endpoint",
884
+ message: `env.${ENV_ENDPOINT} \uAC00 \uB2E4\uB978 \uC218\uC9D1 \uC11C\uBC84(${hostOf(currentEndpoint)})\uB97C \uAC00\uB9AC\uD0B5\uB2C8\uB2E4. Claude Code \uB294 \uD154\uB808\uBA54\uD2B8\uB9AC\uB97C \uD55C \uACF3\uC5D0\uB9CC \uBCF4\uB0BC \uC218 \uC788\uC5B4 \uBA48\uCDA5\uB2C8\uB2E4. \uD488\uC740\uC815\uC6D0\uC73C\uB85C \uBCF4\uB0B4\uB824\uBA74 \uADF8 \uC904\uC744 \uC9C0\uC6B4 \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`
885
+ });
886
+ }
887
+ for (const [key, suffix] of SIGNAL_ENDPOINTS) {
888
+ const value = envValue(env, key);
889
+ if (value !== null && !sameUrl(value, `${endpoint}${suffix}`)) {
890
+ conflicts.push({
891
+ code: "other_endpoint",
892
+ message: `env.${key} \uAC00 \uB2E4\uB978 \uC218\uC9D1 \uC11C\uBC84(${hostOf(value)})\uB97C \uAC00\uB9AC\uD0B5\uB2C8\uB2E4. \uD488\uC740\uC815\uC6D0\uC73C\uB85C \uBCF4\uB0B4\uB824\uBA74 \uADF8 \uC904\uC744 \uC9C0\uC6B4 \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`
893
+ });
894
+ }
895
+ }
896
+ if (envValue(env, ENV_TEMPORALITY) === null) {
897
+ add(ENV_TEMPORALITY, "delta");
898
+ }
899
+ for (const key of HEADER_KEYS) {
900
+ const raw = env[key];
901
+ if (typeof raw !== "string") {
902
+ continue;
903
+ }
904
+ const pairs = raw.split(",");
905
+ const kept = pairs.filter((pair) => headerKeyOf(pair) !== "authorization");
906
+ if (kept.length === pairs.length) {
907
+ continue;
908
+ }
909
+ if (kept.every((pair) => pair.trim() === "")) {
910
+ delete env[key];
911
+ } else {
912
+ env[key] = kept.join(",");
913
+ }
914
+ changes.push(`env.${key} \uC758 Authorization \uC9C0\uC6C0 (\uC774\uC81C \uD3F4\uB354\uB9C8\uB2E4 \uB3C4\uC6B0\uBBF8\uAC00 \uD0A4\uB97C \uACE0\uB985\uB2C8\uB2E4)`);
915
+ }
916
+ const helper = settings.otelHeadersHelper;
917
+ let nextHelper = null;
918
+ if (helper === void 0 || helper === null || typeof helper === "string" && helper.trim() === "") {
919
+ nextHelper = options.helperPath;
920
+ changes.push(`otelHeadersHelper \u2192 ${displayPath(options.helperPath, options.home)}`);
921
+ } else if (typeof helper !== "string") {
922
+ conflicts.push({
923
+ code: "other_headers_helper",
924
+ message: "otelHeadersHelper \uAC00 \uAE00\uC790\uAC00 \uC544\uB2CC \uAC12\uC785\uB2C8\uB2E4. \uADF8 \uC904\uC744 \uC9C0\uC6B4 \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
925
+ });
926
+ } else {
927
+ const normalized = normalizeCommandPath(helper, options.home);
928
+ if (normalized === path3.normalize(options.helperPath)) {
929
+ } else if (normalized === path3.normalize(options.legacyHelperPath)) {
930
+ nextHelper = options.helperPath;
931
+ changes.push(
932
+ `otelHeadersHelper: \uC61B \uC190 \uC124\uC815(otel-headers.sh) \u2192 ${displayPath(options.helperPath, options.home)} (\uC0C8 \uB3C4\uC6B0\uBBF8\uAC00 \uBABB \uCC3E\uB294 \uD3F4\uB354\uB294 \uC61B \uB3C4\uC6B0\uBBF8\uC5D0\uAC8C \uB118\uAE41\uB2C8\uB2E4)`
933
+ );
934
+ } else {
935
+ conflicts.push({
936
+ code: "other_headers_helper",
937
+ message: "otelHeadersHelper \uAC00 \uC774\uBBF8 \uB2E4\uB978 \uB3C4\uC6B0\uBBF8\uB97C \uAC00\uB9AC\uD0B5\uB2C8\uB2E4. \uADF8 \uB3C4\uC6B0\uBBF8\uB97C \uC4F0\uACE0 \uC788\uB2E4\uBA74 \uC5F0\uACB0\uD558\uC9C0 \uB9C8\uC138\uC694. \uC544\uB2C8\uBA74 \uADF8 \uC904\uC744 \uC9C0\uC6B4 \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694."
938
+ });
939
+ }
940
+ }
941
+ for (const key of PROMPT_LOG_KEYS) {
942
+ const value = envValue(env, key);
943
+ if (value !== null && isTruthyFlag(value)) {
944
+ warnings.push(`env.${key} \uAC00 \uCF1C\uC838 \uC788\uC2B5\uB2C8\uB2E4. \uD488\uC740\uC815\uC6D0 \uAC8C\uC774\uD2B8\uC6E8\uC774\uB294 \uBCF8\uBB38\uC744 \uC800\uC7A5\uD558\uC9C0 \uC54A\uC9C0\uB9CC, \uB044\uAE30\uB97C \uAD8C\uD569\uB2C8\uB2E4.`);
945
+ }
946
+ }
947
+ if (conflicts.length > 0) {
948
+ return refusalResult(
949
+ { code: conflicts[0].code, message: conflicts.map((conflict) => conflict.message).join("\n") },
950
+ warnings
951
+ );
952
+ }
953
+ if (changes.length === 0) {
954
+ return { next: settings, changes: [], refusal: null, addedEnv: {}, warnings };
955
+ }
956
+ const next = { ...settings, env };
957
+ if (nextHelper !== null) {
958
+ next.otelHeadersHelper = nextHelper;
959
+ }
960
+ return { next, changes, refusal: null, addedEnv, warnings };
961
+ }
962
+ function revertTelemetrySettings(current, options) {
963
+ const parsed = parseSettings(current);
964
+ if (!parsed.ok) {
965
+ return refusalResult(parsed.refusal);
966
+ }
967
+ const next = { ...parsed.value };
968
+ const changes = [];
969
+ const helper = next.otelHeadersHelper;
970
+ if (typeof helper === "string" && normalizeCommandPath(helper, options.home) === path3.normalize(options.helperPath)) {
971
+ if (options.legacyHelperExists) {
972
+ next.otelHeadersHelper = options.legacyHelperPath;
973
+ changes.push(`otelHeadersHelper \u2192 ${displayPath(options.legacyHelperPath, options.home)} (\uC61B \uC190 \uC124\uC815\uC73C\uB85C \uB418\uB3CC\uB9BC)`);
974
+ } else {
975
+ delete next.otelHeadersHelper;
976
+ changes.push("otelHeadersHelper \uC9C0\uC6C0");
977
+ }
978
+ }
979
+ if (isPlainObject3(next.env)) {
980
+ const env = { ...next.env };
981
+ for (const [key, value] of Object.entries(options.addedEnv)) {
982
+ if (env[key] !== void 0 && String(env[key]) === value) {
983
+ delete env[key];
984
+ changes.push(`env.${key} \uC9C0\uC6C0`);
985
+ }
986
+ }
987
+ if (Object.keys(env).length === 0) {
988
+ delete next.env;
989
+ } else {
990
+ next.env = env;
991
+ }
992
+ }
993
+ return { next: changes.length > 0 ? next : parsed.value, changes, refusal: null, addedEnv: {}, warnings: [] };
994
+ }
995
+ function detectIndent(text) {
996
+ if (!text) {
997
+ return 2;
998
+ }
999
+ const match = /\n([ \t]+)\S/.exec(text);
1000
+ if (!match) {
1001
+ return 2;
1002
+ }
1003
+ return match[1].startsWith(" ") ? " " : match[1].length;
1004
+ }
1005
+ function serializeSettings(next, originalText) {
1006
+ return `${JSON.stringify(next, null, detectIndent(originalText))}
1007
+ `;
1008
+ }
1009
+ function readSettingsFile(file) {
1010
+ const realFile = safeRealpath(file) ?? file;
1011
+ return { realFile, text: readTextIfExists(realFile), mode: fileMode(realFile) };
1012
+ }
1013
+ function writeBackup(paths, text, now) {
1014
+ ensurePrivateDir(paths.backupsDir);
1015
+ const stamp = new Date(now).toISOString().replace(/[-:]/g, "").replace("T", "-").replace(/\.(\d{3})Z$/, "-$1");
1016
+ let file = path3.join(paths.backupsDir, `settings.json.${stamp}.bak`);
1017
+ for (let i = 1; fs3.existsSync(file); i += 1) {
1018
+ file = path3.join(paths.backupsDir, `settings.json.${stamp}-${i}.bak`);
1019
+ }
1020
+ writeFileAtomic(file, text, 384);
1021
+ const backups = fs3.readdirSync(paths.backupsDir).filter((name) => /^settings\.json\..+\.bak$/.test(name)).sort();
1022
+ for (const old of backups.slice(0, Math.max(0, backups.length - MAX_BACKUPS))) {
1023
+ removeIfExists(path3.join(paths.backupsDir, old));
1024
+ }
1025
+ return file;
1026
+ }
1027
+ function applySettingsChange(paths, compute, now) {
1028
+ const first = readSettingsFile(paths.claudeSettingsFile);
1029
+ let result = compute(first.text);
1030
+ if (result.refusal || result.changes.length === 0 || !result.next) {
1031
+ return { result, written: false, backupFile: null };
1032
+ }
1033
+ const again = readSettingsFile(paths.claudeSettingsFile);
1034
+ if (again.text !== first.text) {
1035
+ result = compute(again.text);
1036
+ if (result.refusal || result.changes.length === 0 || !result.next) {
1037
+ return { result, written: false, backupFile: null };
1038
+ }
1039
+ }
1040
+ const backupFile = again.text !== null ? writeBackup(paths, again.text, now) : null;
1041
+ fs3.mkdirSync(path3.dirname(again.realFile), { recursive: true });
1042
+ writeFileAtomic(again.realFile, serializeSettings(result.next, again.text), again.mode ?? 384);
1043
+ return { result, written: true, backupFile };
1044
+ }
1045
+ function mergeOptionsFor(paths, endpoint) {
1046
+ return {
1047
+ helperPath: paths.helperFile,
1048
+ legacyHelperPath: paths.legacyHelperFile,
1049
+ endpoint,
1050
+ home: paths.home
1051
+ };
1052
+ }
1053
+ function previewTelemetryMerge(paths, endpoint) {
1054
+ return mergeTelemetrySettings(readSettingsFile(paths.claudeSettingsFile).text, mergeOptionsFor(paths, endpoint));
1055
+ }
1056
+ function applyTelemetrySettings(paths, endpoint, now) {
1057
+ const applied = applySettingsChange(
1058
+ paths,
1059
+ (text) => mergeTelemetrySettings(text, mergeOptionsFor(paths, endpoint)),
1060
+ now
1061
+ );
1062
+ if (applied.written && Object.keys(applied.result.addedEnv).length > 0) {
1063
+ recordAddedEnv(paths, applied.result.addedEnv);
1064
+ }
1065
+ return applied;
1066
+ }
1067
+ function settingsReferencesHelper(paths) {
1068
+ const parsed = parseSettings(readSettingsFile(paths.claudeSettingsFile).text);
1069
+ if (!parsed.ok) {
1070
+ return true;
1071
+ }
1072
+ const helper = parsed.value.otelHeadersHelper;
1073
+ return typeof helper === "string" && normalizeCommandPath(helper, paths.home) === path3.normalize(paths.helperFile);
1074
+ }
1075
+ function readAddedEnv(paths) {
1076
+ const text = readTextIfExists(paths.settingsAddedFile);
1077
+ if (text === null) {
1078
+ return {};
1079
+ }
1080
+ try {
1081
+ const parsed = JSON.parse(text);
1082
+ if (isPlainObject3(parsed) && isPlainObject3(parsed.env)) {
1083
+ const out = {};
1084
+ for (const [key, value] of Object.entries(parsed.env)) {
1085
+ if (typeof value === "string") {
1086
+ out[key] = value;
1087
+ }
1088
+ }
1089
+ return out;
1090
+ }
1091
+ } catch {
1092
+ }
1093
+ return {};
1094
+ }
1095
+ function recordAddedEnv(paths, added) {
1096
+ const merged = { ...readAddedEnv(paths), ...added };
1097
+ ensurePrivateDir(paths.configDir);
1098
+ writeFileAtomic(paths.settingsAddedFile, `${JSON.stringify({ version: 1, env: merged }, null, 2)}
1099
+ `, 384);
1100
+ }
1101
+ function clearAddedEnv(paths) {
1102
+ removeIfExists(paths.settingsAddedFile);
1103
+ }
1104
+ function collectEnvironmentWarnings(paths, shellEnv, endpoint) {
1105
+ const warnings = [];
1106
+ for (const file of paths.managedSettingsFiles) {
1107
+ let text = null;
1108
+ try {
1109
+ text = readTextIfExists(file);
1110
+ } catch {
1111
+ text = null;
1112
+ }
1113
+ if (text === null) {
1114
+ continue;
1115
+ }
1116
+ let parsed = null;
1117
+ try {
1118
+ parsed = JSON.parse(text);
1119
+ } catch {
1120
+ parsed = null;
1121
+ }
1122
+ if (!isPlainObject3(parsed)) {
1123
+ continue;
1124
+ }
1125
+ const managedEnv = isPlainObject3(parsed.env) ? Object.keys(parsed.env) : [];
1126
+ const touchesTelemetry = parsed.otelHeadersHelper !== void 0 || managedEnv.some((key) => key.toUpperCase().startsWith("OTEL_") || key.toUpperCase() === ENV_ENABLE_TELEMETRY);
1127
+ if (touchesTelemetry) {
1128
+ warnings.push(`\uAD00\uB9AC \uC124\uC815 ${file} \uC5D0 \uD154\uB808\uBA54\uD2B8\uB9AC \uC124\uC815\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uADF8 \uAC12\uC774 \uC0AC\uC6A9\uC790 \uC124\uC815\uBCF4\uB2E4 \uC55E\uC11C \uD488\uC740\uC815\uC6D0\uC73C\uB85C \uC548 \uAC08 \uC218 \uC788\uC2B5\uB2C8\uB2E4.`);
1129
+ }
1130
+ }
1131
+ for (const [key, suffix] of [[ENV_ENDPOINT, ""], ...SIGNAL_ENDPOINTS]) {
1132
+ const value = shellEnv[key];
1133
+ if (value && value.trim() !== "" && !sameUrl(value, `${endpoint.replace(/\/+$/, "")}${suffix}`)) {
1134
+ warnings.push(`\uC774 \uC178\uC758 \uD658\uACBD \uBCC0\uC218 ${key} \uAC00 \uB2E4\uB978 \uACF3(${hostOf(value)})\uC744 \uAC00\uB9AC\uD0B5\uB2C8\uB2E4. \uC774 \uC178\uC5D0\uC11C \uCF20 Claude Code \uC5D0\uB294 \uADF8 \uAC12\uC774 \uC11E\uC77C \uC218 \uC788\uC2B5\uB2C8\uB2E4.`);
1135
+ }
1136
+ }
1137
+ const shellEnable = shellEnv[ENV_ENABLE_TELEMETRY];
1138
+ if (shellEnable !== void 0 && shellEnable.trim() !== "" && !isTruthyFlag(shellEnable.trim())) {
1139
+ warnings.push(`\uC774 \uC178\uC758 \uD658\uACBD \uBCC0\uC218 ${ENV_ENABLE_TELEMETRY} \uAC00 \uAEBC\uC838 \uC788\uC2B5\uB2C8\uB2E4. \uC774 \uC178\uC5D0\uC11C \uCF20 Claude Code \uB294 \uD154\uB808\uBA54\uD2B8\uB9AC\uB97C \uBCF4\uB0B4\uC9C0 \uC54A\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4.`);
1140
+ }
1141
+ for (const key of HEADER_KEYS) {
1142
+ const value = shellEnv[key];
1143
+ if (value && value.split(",").some((pair) => headerKeyOf(pair) === "authorization")) {
1144
+ warnings.push(`\uC774 \uC178\uC758 \uD658\uACBD \uBCC0\uC218 ${key} \uC5D0 Authorization \uC774 \uC788\uC2B5\uB2C8\uB2E4. \uC774 \uC178\uC5D0\uC11C \uCF20 \uC138\uC158\uC740 \uD3F4\uB354\uC640 \uC0C1\uAD00\uC5C6\uC774 \uADF8 \uD0A4\uB85C \uBCF4\uB0BC \uC218 \uC788\uC2B5\uB2C8\uB2E4.`);
1145
+ }
1146
+ }
1147
+ return warnings;
1148
+ }
1149
+
1150
+ // packages/cli/src/helper.ts
1151
+ import { spawnSync as spawnSync2 } from "node:child_process";
1152
+ import * as fs4 from "node:fs";
1153
+ import * as path4 from "node:path";
1154
+ var HELPER_EXPLAIN_ENV = "NESTEDGARDEN_HELPER_EXPLAIN";
1155
+ function shellQuote(value) {
1156
+ return `'${value.replace(/'/g, `'\\''`)}'`;
1157
+ }
1158
+ function renderHelperScript(configDir) {
1159
+ return `#!/bin/sh
1160
+ # nestedgarden headers helper v${CLI_VERSION}
1161
+ # 'npx nestedgarden connect' \uAC00 \uB9CC\uB4E0 \uD30C\uC77C\uC785\uB2C8\uB2E4. \uC190\uC73C\uB85C \uACE0\uCE58\uC9C0 \uB9C8\uC138\uC694 (connect\xB7doctor \uAC00 \uB2E4\uC2DC \uC501\uB2C8\uB2E4).
1162
+ # Claude Code \uC758 otelHeadersHelper \uAC00 \uC138\uC158\uC744 \uCF20 \uD3F4\uB354\uC5D0\uC11C \uC774 \uD30C\uC77C\uC744 \uC2E4\uD589\uD569\uB2C8\uB2E4.
1163
+ # \uADF8 \uD3F4\uB354\uB97C \uD488\uC740 \uBFCC\uB9AC\uB97C projects.tsv \uC5D0\uC11C \uCC3E\uC544 \uADF8 \uD0A4\uB85C {"Authorization":"Bearer ..."} \uB97C \uCC0D\uC2B5\uB2C8\uB2E4.
1164
+ # 1) pwd -P \uC640 \uAC19\uAC70\uB098 (tree \uBA74) \uADF8 \uC544\uB798\uC778 \uBFCC\uB9AC \uAC00\uC6B4\uB370 \uAC00\uC7A5 \uAE34 \uAC83
1165
+ # 2) \uC5C6\uC73C\uBA74 \uC704\uB85C \uC62C\uB77C\uAC00\uBA70 .git \uD30C\uC77C(worktree)\uC744 \uCC3E\uC544 \uBCF8 \uC800\uC7A5\uC18C + \uAC19\uC740 \uD558\uC704 \uACBD\uB85C\uB85C 1) \uC744 \uB2E4\uC2DC
1166
+ # 3) \uC5C6\uC73C\uBA74 \uC61B \uC190 \uC124\uC815 otel-headers.sh \uAC00 Bearer \uB97C \uB0B4\uBA74 \uADF8\uB300\uB85C
1167
+ # 4) \uADF8\uB798\uB3C4 \uC5C6\uC73C\uBA74 {}
1168
+ # git \uC744 \uBD80\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uC5B8\uC81C\uB098 \uC885\uB8CC \uCF54\uB4DC 0 \uC785\uB2C8\uB2E4.
1169
+
1170
+ NG_DIR=${shellQuote(configDir)}
1171
+ LC_ALL=C
1172
+ export LC_ALL
1173
+ unset CDPATH
1174
+ cr=$(printf '\\r')
1175
+
1176
+ ng_explain() {
1177
+ if [ -n "\${${HELPER_EXPLAIN_ENV}:-}" ]; then
1178
+ printf 'nestedgarden-helper\\t%s\\t%s\\t%s\\n' "$1" "$2" "$3" >&2
1179
+ fi
1180
+ }
1181
+
1182
+ # $1 = \uCC3E\uC744 \uACBD\uB85C. \uACE0\uB978 \uBFCC\uB9AC\uC640 \uD0A4 \uD30C\uC77C\uC744 ng_root\xB7ng_keyfile \uC5D0 \uB454\uB2E4 (\uC5C6\uC73C\uBA74 \uBE48 \uAC12)
1183
+ ng_lookup() {
1184
+ ng_root=
1185
+ ng_keyfile=
1186
+ ng_len=0
1187
+ if [ ! -f "$NG_DIR/projects.tsv" ] || [ ! -r "$NG_DIR/projects.tsv" ]; then
1188
+ return 0
1189
+ fi
1190
+ while IFS=' ' read -r root mode agent keyfile name remote added || [ -n "$root" ]; do
1191
+ case "$root" in
1192
+ /*) ;;
1193
+ *) continue ;;
1194
+ esac
1195
+ hit=
1196
+ if [ "$1" = "$root" ]; then
1197
+ hit=1
1198
+ elif [ "$mode" = "tree" ]; then
1199
+ case "$1/" in
1200
+ "$root"/*) hit=1 ;;
1201
+ esac
1202
+ fi
1203
+ if [ -n "$hit" ] && [ "\${#root}" -gt "$ng_len" ]; then
1204
+ ng_root=$root
1205
+ ng_keyfile=$keyfile
1206
+ ng_len=\${#root}
1207
+ fi
1208
+ done < "$NG_DIR/projects.tsv"
1209
+ return 0
1210
+ }
1211
+
1212
+ # $1 = \uD0A4 \uD30C\uC77C (\uC0C1\uB300 \uACBD\uB85C\uBA74 NG_DIR \uAE30\uC900), $2 = \uACE0\uB978 \uAE4C\uB2ED
1213
+ ng_emit_key() {
1214
+ case "$1" in
1215
+ /*) kf=$1 ;;
1216
+ *) kf=$NG_DIR/$1 ;;
1217
+ esac
1218
+ k=
1219
+ if [ -f "$kf" ] && [ -r "$kf" ]; then
1220
+ IFS= read -r k < "$kf" || true
1221
+ fi
1222
+ k=\${k%"$cr"}
1223
+ case "$k" in
1224
+ ng_?*) ;;
1225
+ *) k= ;;
1226
+ esac
1227
+ case "$k" in
1228
+ *[!A-Za-z0-9_-]*) k= ;;
1229
+ esac
1230
+ if [ -z "$k" ]; then
1231
+ ng_explain bad_key "$ng_root" "$kf"
1232
+ printf '{}\\n'
1233
+ return 0
1234
+ fi
1235
+ ng_explain "$2" "$ng_root" "$kf"
1236
+ printf '{"Authorization":"Bearer %s"}\\n' "$k"
1237
+ return 0
1238
+ }
1239
+
1240
+ cwd=$(pwd -P 2>/dev/null) || cwd=$PWD
1241
+
1242
+ # 1) \uBAA9\uB85D
1243
+ ng_lookup "$cwd"
1244
+ if [ -n "$ng_root" ]; then
1245
+ ng_emit_key "$ng_keyfile" registry
1246
+ exit 0
1247
+ fi
1248
+
1249
+ # 2) worktree: \uC704\uB85C \uC62C\uB77C\uAC00\uBA70 .git \uD30C\uC77C\uC744 \uCC3E\uB294\uB2E4 (.git \uD3F4\uB354\uB97C \uB9CC\uB098\uBA74 \uBA48\uCD98\uB2E4)
1250
+ d=$cwd
1251
+ while [ -n "$d" ]; do
1252
+ if [ -d "$d/.git" ]; then
1253
+ break
1254
+ fi
1255
+ if [ -f "$d/.git" ]; then
1256
+ line=
1257
+ IFS= read -r line < "$d/.git" || true
1258
+ line=\${line%"$cr"}
1259
+ gd=
1260
+ case "$line" in
1261
+ 'gitdir: '*) gd=\${line#"gitdir: "} ;;
1262
+ esac
1263
+ if [ -n "$gd" ]; then
1264
+ gd=$(cd "$d" 2>/dev/null && cd "$gd" 2>/dev/null && pwd -P) || gd=
1265
+ fi
1266
+ case "$gd" in
1267
+ */.git/worktrees/*)
1268
+ main=\${gd%/.git/worktrees/*}
1269
+ sub=\${cwd#"$d"}
1270
+ ng_lookup "$main$sub"
1271
+ if [ -n "$ng_root" ]; then
1272
+ ng_emit_key "$ng_keyfile" worktree
1273
+ exit 0
1274
+ fi
1275
+ ;;
1276
+ esac
1277
+ break
1278
+ fi
1279
+ if [ "$d" = "/" ]; then
1280
+ break
1281
+ fi
1282
+ d=\${d%/*}
1283
+ if [ -z "$d" ]; then
1284
+ d=/
1285
+ fi
1286
+ done
1287
+
1288
+ # 3) \uC61B \uC190 \uC124\uC815 (\uC190\uC73C\uB85C \uB9CC\uB4E0 otel-headers.sh). \uB450 \uBC88 \uB4E4\uC5B4\uAC00\uC9C0 \uC54A\uAC8C \uD45C\uC2DC\uB97C \uB2EC\uACE0 \uBD80\uB978\uB2E4
1289
+ legacy=$NG_DIR/otel-headers.sh
1290
+ if [ -z "\${NESTEDGARDEN_HELPER_INNER:-}" ] && [ -f "$legacy" ] && [ -x "$legacy" ]; then
1291
+ out=$(NESTEDGARDEN_HELPER_INNER=1 "$legacy" 2>/dev/null) || true
1292
+ case "$out" in
1293
+ *Bearer*)
1294
+ ng_explain legacy - "$legacy"
1295
+ printf '%s\\n' "$out"
1296
+ exit 0
1297
+ ;;
1298
+ esac
1299
+ fi
1300
+
1301
+ # 4) \uC5C6\uC74C
1302
+ ng_explain none - -
1303
+ printf '{}\\n'
1304
+ exit 0
1305
+ `;
1306
+ }
1307
+ function isHelperCurrent(paths) {
1308
+ const current = readTextIfExists(paths.helperFile);
1309
+ return current === renderHelperScript(paths.configDir) && fileMode(paths.helperFile) === 448;
1310
+ }
1311
+ function installHelper(paths) {
1312
+ if (isHelperCurrent(paths)) {
1313
+ return { path: paths.helperFile, changed: false };
1314
+ }
1315
+ ensurePrivateDir(paths.configDir);
1316
+ ensurePrivateDir(paths.binDir);
1317
+ writeFileAtomic(paths.helperFile, renderHelperScript(paths.configDir), 448);
1318
+ return { path: paths.helperFile, changed: true };
1319
+ }
1320
+ function runHelper(cwd, options) {
1321
+ const result = spawnSync2("/bin/sh", [options.helperPath], {
1322
+ cwd,
1323
+ env: childEnv(options.env, { PWD: cwd, [HELPER_EXPLAIN_ENV]: "1" }),
1324
+ encoding: "utf8",
1325
+ timeout: 15e3
1326
+ });
1327
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
1328
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
1329
+ let validJson = false;
1330
+ let hasAuthorization = false;
1331
+ try {
1332
+ const parsed = JSON.parse(stdout.trim());
1333
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
1334
+ const values = Object.values(parsed);
1335
+ validJson = values.every((value) => typeof value === "string");
1336
+ const authorization = parsed.Authorization;
1337
+ hasAuthorization = typeof authorization === "string" && /^Bearer \S+$/.test(authorization);
1338
+ }
1339
+ } catch {
1340
+ validJson = false;
1341
+ }
1342
+ let source = "unknown";
1343
+ let root = null;
1344
+ let keyFile = null;
1345
+ const explainLines = stderr.split("\n").filter((line) => line.startsWith("nestedgarden-helper "));
1346
+ const last = explainLines[explainLines.length - 1];
1347
+ if (last) {
1348
+ const [, kind, rootField, keyField] = last.split(" ");
1349
+ if (kind === "registry" || kind === "worktree" || kind === "legacy" || kind === "none" || kind === "bad_key") {
1350
+ source = kind;
1351
+ }
1352
+ root = rootField && rootField !== "-" ? rootField : null;
1353
+ keyFile = keyField && keyField !== "-" ? keyField : null;
1354
+ }
1355
+ return { exitCode: result.status, validJson, hasAuthorization, source, root, keyFile };
1356
+ }
1357
+ function writeKeyFile(paths, keyId, key) {
1358
+ if (!/^[A-Za-z0-9_-]{1,100}$/.test(keyId)) {
1359
+ throw new Error("\uC11C\uBC84\uAC00 \uC900 \uD0A4 id \uC758 \uAF34\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4");
1360
+ }
1361
+ ensurePrivateDir(paths.configDir);
1362
+ ensurePrivateDir(paths.keysDir);
1363
+ writeFileAtomic(path4.join(paths.keysDir, `${keyId}.key`), `${key}
1364
+ `, 384);
1365
+ return `keys/${keyId}.key`;
1366
+ }
1367
+ function runLegacyHelper(paths, cwd, env) {
1368
+ if (!isExecutableFile(paths.legacyHelperFile)) {
1369
+ return null;
1370
+ }
1371
+ const result = spawnSync2(paths.legacyHelperFile, [], {
1372
+ cwd,
1373
+ env: childEnv(env, { PWD: cwd, NESTEDGARDEN_HELPER_INNER: "1" }),
1374
+ encoding: "utf8",
1375
+ timeout: 15e3,
1376
+ stdio: ["ignore", "pipe", "pipe"]
1377
+ });
1378
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
1379
+ try {
1380
+ const parsed = JSON.parse(stdout.trim());
1381
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1382
+ return null;
1383
+ }
1384
+ const headers = parsed;
1385
+ const name = Object.keys(headers).find((item) => item.toLowerCase() === "authorization");
1386
+ const value = name ? headers[name] : void 0;
1387
+ if (typeof value !== "string") {
1388
+ return null;
1389
+ }
1390
+ const match = /^Bearer\s+(ng_[A-Za-z0-9_-]+)$/.exec(value.trim());
1391
+ return match ? match[1] : null;
1392
+ } catch {
1393
+ return null;
1394
+ }
1395
+ }
1396
+ function findLegacyKeyFile(paths, key) {
1397
+ let names;
1398
+ try {
1399
+ names = fs4.readdirSync(paths.configDir).filter((name) => name.endsWith(".key")).sort();
1400
+ } catch {
1401
+ return null;
1402
+ }
1403
+ for (const name of names) {
1404
+ if (readKeyFile(path4.join(paths.configDir, name)) === key) {
1405
+ return name;
1406
+ }
1407
+ }
1408
+ return null;
1409
+ }
1410
+ function readKeyFile(file) {
1411
+ let text;
1412
+ try {
1413
+ if (!fs4.statSync(file).isFile()) {
1414
+ return null;
1415
+ }
1416
+ text = fs4.readFileSync(file, "utf8");
1417
+ } catch {
1418
+ return null;
1419
+ }
1420
+ const firstLine = (text.split("\n")[0] ?? "").replace(/\r$/, "");
1421
+ return /^ng_[A-Za-z0-9_-]+$/.test(firstLine) ? firstLine : null;
1422
+ }
1423
+
1424
+ // packages/cli/src/pending.ts
1425
+ import * as crypto2 from "node:crypto";
1426
+ import * as path5 from "node:path";
1427
+ function pendingFileFor(paths, root) {
1428
+ const digest = crypto2.createHash("sha256").update(root).digest("hex").slice(0, 16);
1429
+ return path5.join(paths.pendingDir, `${digest}.json`);
1430
+ }
1431
+ function savePending(paths, pending) {
1432
+ ensurePrivateDir(paths.configDir);
1433
+ ensurePrivateDir(paths.pendingDir);
1434
+ writeFileAtomic(pendingFileFor(paths, pending.root), `${JSON.stringify(pending, null, 2)}
1435
+ `, 384);
1436
+ }
1437
+ function isPending(value) {
1438
+ if (value === null || typeof value !== "object") {
1439
+ return false;
1440
+ }
1441
+ const item = value;
1442
+ return typeof item.deviceCode === "string" && typeof item.userCode === "string" && typeof item.server === "string" && typeof item.root === "string" && typeof item.expiresAt === "string" && typeof item.interval === "number" && typeof item.verificationUriComplete === "string";
1443
+ }
1444
+ function loadPending(paths, root, now) {
1445
+ const file = pendingFileFor(paths, root);
1446
+ const text = readTextIfExists(file);
1447
+ if (text === null) {
1448
+ return null;
1449
+ }
1450
+ let parsed = null;
1451
+ try {
1452
+ parsed = JSON.parse(text);
1453
+ } catch {
1454
+ parsed = null;
1455
+ }
1456
+ if (!isPending(parsed) || parsed.root !== root) {
1457
+ removeIfExists(file);
1458
+ return null;
1459
+ }
1460
+ const expiresAt = Date.parse(parsed.expiresAt);
1461
+ if (!Number.isFinite(expiresAt) || expiresAt <= now) {
1462
+ removeIfExists(file);
1463
+ return null;
1464
+ }
1465
+ return parsed;
1466
+ }
1467
+ function deletePending(paths, root) {
1468
+ removeIfExists(pendingFileFor(paths, root));
1469
+ }
1470
+
1471
+ // packages/cli/src/project.ts
1472
+ import * as fs5 from "node:fs";
1473
+ import * as path6 from "node:path";
1474
+ function statOrNull(target) {
1475
+ try {
1476
+ return fs5.statSync(target);
1477
+ } catch {
1478
+ return null;
1479
+ }
1480
+ }
1481
+ function readGitdirFile(dir) {
1482
+ let text;
1483
+ try {
1484
+ text = fs5.readFileSync(path6.join(dir, ".git"), "utf8");
1485
+ } catch {
1486
+ return null;
1487
+ }
1488
+ const firstLine = text.split("\n")[0]?.replace(/\r$/, "") ?? "";
1489
+ const match = /^gitdir:\s*(.+)$/.exec(firstLine);
1490
+ if (!match) {
1491
+ return null;
1492
+ }
1493
+ return path6.resolve(dir, match[1].trim());
1494
+ }
1495
+ function mainRepoFromGitdir(gitdir) {
1496
+ const marker = "/.git/worktrees/";
1497
+ const at = gitdir.lastIndexOf(marker);
1498
+ if (at < 0) {
1499
+ return null;
1500
+ }
1501
+ const main = gitdir.slice(0, at);
1502
+ return main === "" ? "/" : main;
1503
+ }
1504
+ function findGitRoot(start, home) {
1505
+ let dir = start;
1506
+ for (; ; ) {
1507
+ if (dir === home && dir !== start) {
1508
+ return null;
1509
+ }
1510
+ const stat = statOrNull(path6.join(dir, ".git"));
1511
+ if (stat?.isDirectory()) {
1512
+ return { root: dir, kind: "dir" };
1513
+ }
1514
+ if (stat?.isFile()) {
1515
+ return { root: dir, kind: "file" };
1516
+ }
1517
+ const parent = path6.dirname(dir);
1518
+ if (parent === dir) {
1519
+ return null;
1520
+ }
1521
+ dir = parent;
1522
+ }
1523
+ }
1524
+ function mapWorktreePath(cwdReal) {
1525
+ let dir = cwdReal;
1526
+ for (; ; ) {
1527
+ const stat = statOrNull(path6.join(dir, ".git"));
1528
+ if (stat?.isDirectory()) {
1529
+ return null;
1530
+ }
1531
+ if (stat?.isFile()) {
1532
+ const gitdir = readGitdirFile(dir);
1533
+ const gitdirReal = gitdir ? safeRealpath(gitdir) : null;
1534
+ const main = gitdirReal ? mainRepoFromGitdir(gitdirReal) : null;
1535
+ if (!main) {
1536
+ return null;
1537
+ }
1538
+ return `${main}${cwdReal.slice(dir.length)}`;
1539
+ }
1540
+ const parent = path6.dirname(dir);
1541
+ if (parent === dir) {
1542
+ return null;
1543
+ }
1544
+ dir = parent;
1545
+ }
1546
+ }
1547
+ function normalizeRemoteUrl(raw) {
1548
+ const value = raw.trim();
1549
+ if (value === "") {
1550
+ return null;
1551
+ }
1552
+ let host;
1553
+ let repoPath;
1554
+ const withScheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/(.*)$/.exec(value);
1555
+ if (withScheme) {
1556
+ const scheme = withScheme[1].toLowerCase();
1557
+ if (!["http", "https", "ssh", "git", "git+ssh", "ssh+git"].includes(scheme)) {
1558
+ return null;
1559
+ }
1560
+ const rest = withScheme[2];
1561
+ const slash = rest.indexOf("/");
1562
+ if (slash < 0) {
1563
+ return null;
1564
+ }
1565
+ let authority = rest.slice(0, slash);
1566
+ const at = authority.lastIndexOf("@");
1567
+ if (at >= 0) {
1568
+ authority = authority.slice(at + 1);
1569
+ }
1570
+ host = authority.replace(/:\d*$/, "");
1571
+ repoPath = rest.slice(slash + 1);
1572
+ } else {
1573
+ const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(value);
1574
+ if (!scp) {
1575
+ return null;
1576
+ }
1577
+ host = scp[1];
1578
+ repoPath = scp[2];
1579
+ }
1580
+ repoPath = repoPath.replace(/[?#].*$/, "").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
1581
+ if (host === "" || repoPath === "") {
1582
+ return null;
1583
+ }
1584
+ const normalized = `${host}/${repoPath}`.toLowerCase();
1585
+ if (/[\s]/.test(normalized)) {
1586
+ return null;
1587
+ }
1588
+ return normalized;
1589
+ }
1590
+ function parseOriginUrl(configText) {
1591
+ let inOrigin = false;
1592
+ for (const rawLine of configText.split("\n")) {
1593
+ const line = rawLine.trim();
1594
+ if (line === "" || line.startsWith("#") || line.startsWith(";")) {
1595
+ continue;
1596
+ }
1597
+ const section = /^\[\s*([A-Za-z0-9.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]$/.exec(line);
1598
+ if (section) {
1599
+ inOrigin = section[1].toLowerCase() === "remote" && section[2] === "origin";
1600
+ continue;
1601
+ }
1602
+ if (!inOrigin) {
1603
+ continue;
1604
+ }
1605
+ const keyValue = /^([A-Za-z0-9-]+)\s*=\s*(.*)$/.exec(line);
1606
+ if (keyValue && keyValue[1].toLowerCase() === "url") {
1607
+ let url = keyValue[2].trim();
1608
+ if (url.startsWith('"') && url.endsWith('"') && url.length >= 2) {
1609
+ url = url.slice(1, -1);
1610
+ }
1611
+ return url;
1612
+ }
1613
+ }
1614
+ return null;
1615
+ }
1616
+ function readOriginRemote(gitDir) {
1617
+ let text;
1618
+ try {
1619
+ text = fs5.readFileSync(path6.join(gitDir, "config"), "utf8");
1620
+ } catch {
1621
+ return null;
1622
+ }
1623
+ const url = parseOriginUrl(text);
1624
+ return url ? normalizeRemoteUrl(url) : null;
1625
+ }
1626
+ function truncateCodePoints(text, max) {
1627
+ const chars = Array.from(text);
1628
+ return chars.length <= max ? text : chars.slice(0, max).join("");
1629
+ }
1630
+ function projectNameOf(folderName) {
1631
+ const cleaned = folderName.normalize("NFC").replace(/[\u0000-\u001f\u007f]/g, "").trim();
1632
+ const name = truncateCodePoints(cleaned, PROJECT_NAME_MAX_LENGTH).trim();
1633
+ return name === "" ? "project" : name;
1634
+ }
1635
+ function detectProject(cwd, home, options) {
1636
+ const cwdReal = safeRealpath(cwd);
1637
+ if (!cwdReal) {
1638
+ return { ok: false, code: "cwd_missing", message: `\uC9C0\uAE08 \uD3F4\uB354\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${cwd}` };
1639
+ }
1640
+ const homeReal = safeRealpath(home) ?? home;
1641
+ let root = cwdReal;
1642
+ let worktreeRoot = null;
1643
+ let gitDir = null;
1644
+ const hit = findGitRoot(cwdReal, homeReal);
1645
+ if (hit) {
1646
+ root = hit.root;
1647
+ if (hit.kind === "dir") {
1648
+ gitDir = path6.join(hit.root, ".git");
1649
+ } else {
1650
+ const gitdir = readGitdirFile(hit.root);
1651
+ const gitdirReal = gitdir ? safeRealpath(gitdir) : null;
1652
+ const main = gitdirReal ? mainRepoFromGitdir(gitdirReal) : null;
1653
+ const mainReal = main ? safeRealpath(main) : null;
1654
+ if (mainReal && statOrNull(path6.join(mainReal, ".git"))?.isDirectory()) {
1655
+ worktreeRoot = hit.root;
1656
+ root = mainReal;
1657
+ gitDir = path6.join(mainReal, ".git");
1658
+ } else {
1659
+ gitDir = gitdirReal;
1660
+ }
1661
+ }
1662
+ }
1663
+ if (root === "/") {
1664
+ return { ok: false, code: "filesystem_root", message: "\uB9E8 \uC704 \uD3F4\uB354(/)\uB294 \uC5F0\uACB0\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD504\uB85C\uC81D\uD2B8 \uD3F4\uB354\uC5D0\uC11C \uC2E4\uD589\uD574 \uC8FC\uC138\uC694." };
1665
+ }
1666
+ if (/[\t\n\r]/.test(root)) {
1667
+ return { ok: false, code: "unsupported_path", message: "\uD3F4\uB354 \uACBD\uB85C\uC5D0 \uD0ED\uC774\uB098 \uC904\uBC14\uAFC8\uC774 \uC788\uC5B4 \uC5F0\uACB0\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD3F4\uB354 \uC774\uB984\uC744 \uBC14\uAFBC \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694." };
1668
+ }
1669
+ const isHome = root === homeReal;
1670
+ if (isHome && !options.allowHome) {
1671
+ return {
1672
+ ok: false,
1673
+ code: "home",
1674
+ message: "\uD648 \uD3F4\uB354 \uC790\uCCB4\uC5D0\uC11C \uC2E4\uD589\uD588\uC2B5\uB2C8\uB2E4. \uD504\uB85C\uC81D\uD2B8 \uD3F4\uB354\uB85C \uC62E\uACA8 \uC2E4\uD589\uD574 \uC8FC\uC138\uC694. \uC815\uB9D0 \uD648 \uD3F4\uB354\uB97C \uC774\uC73C\uB824\uBA74 --allow-home \uC744 \uBD99\uC774\uC138\uC694 (\uD648 \uD3F4\uB354\uC5D0\uC11C \uCF20 \uC138\uC158\uB9CC, \uD558\uC704 \uD3F4\uB354\uB294 \uBE7C\uACE0)."
1675
+ };
1676
+ }
1677
+ return {
1678
+ ok: true,
1679
+ project: {
1680
+ cwd: cwdReal,
1681
+ root,
1682
+ mode: isHome ? "exact" : "tree",
1683
+ name: projectNameOf(path6.basename(root)),
1684
+ remote: gitDir ? readOriginRemote(gitDir) : null,
1685
+ worktreeRoot,
1686
+ isGit: hit !== null
1687
+ }
1688
+ };
1689
+ }
1690
+
1691
+ // packages/cli/src/registry.ts
1692
+ import * as path7 from "node:path";
1693
+ var REGISTRY_HEADER = "# nestedgarden projects v1";
1694
+ var EMPTY = "-";
1695
+ function assertRegistryValue(label, value) {
1696
+ if (/[\t\n\r]/.test(value)) {
1697
+ throw new Error(`\uBAA9\uB85D\uC5D0 \uC801\uC744 \uC218 \uC5C6\uB294 \uAE00\uC790(\uD0ED\xB7\uC904\uBC14\uAFC8)\uAC00 ${label} \uC5D0 \uC788\uC2B5\uB2C8\uB2E4`);
1698
+ }
1699
+ }
1700
+ function encode(label, value) {
1701
+ if (value === null || value === "") {
1702
+ return EMPTY;
1703
+ }
1704
+ assertRegistryValue(label, value);
1705
+ return value;
1706
+ }
1707
+ function decode(value) {
1708
+ if (value === void 0 || value === "" || value === EMPTY) {
1709
+ return null;
1710
+ }
1711
+ return value;
1712
+ }
1713
+ function parseRegistry(text) {
1714
+ const entries = [];
1715
+ const extraLines = [];
1716
+ for (const rawLine of text.split("\n")) {
1717
+ const line = rawLine.replace(/\r$/, "");
1718
+ if (line === "" || line === REGISTRY_HEADER) {
1719
+ continue;
1720
+ }
1721
+ if (line.startsWith("#")) {
1722
+ extraLines.push(line);
1723
+ continue;
1724
+ }
1725
+ const fields = line.split(/\t+/);
1726
+ const [root, mode, agentId, keyFile, name, remote] = fields;
1727
+ if (!root || !root.startsWith("/") || mode !== "tree" && mode !== "exact" || decode(agentId) === null || decode(keyFile) === null) {
1728
+ extraLines.push(line);
1729
+ continue;
1730
+ }
1731
+ entries.push({
1732
+ root,
1733
+ mode,
1734
+ agentId,
1735
+ keyFile,
1736
+ name: decode(name) ?? path7.basename(root),
1737
+ remote: decode(remote),
1738
+ // sh 의 read 처럼 남는 칸은 마지막 값에 붙인다
1739
+ addedAt: decode(fields.slice(6).join(" ")) ?? ""
1740
+ });
1741
+ }
1742
+ return { entries, extraLines };
1743
+ }
1744
+ function serializeRegistry(entries, extraLines = []) {
1745
+ const lines = [REGISTRY_HEADER, ...extraLines];
1746
+ for (const entry of entries) {
1747
+ lines.push(
1748
+ [
1749
+ encode("root", entry.root),
1750
+ entry.mode,
1751
+ encode("agentId", entry.agentId),
1752
+ encode("keyFile", entry.keyFile),
1753
+ encode("name", entry.name),
1754
+ encode("remote", entry.remote),
1755
+ encode("addedAt", entry.addedAt)
1756
+ ].join(" ")
1757
+ );
1758
+ }
1759
+ return `${lines.join("\n")}
1760
+ `;
1761
+ }
1762
+ function readParsed(paths) {
1763
+ const text = readTextIfExists(paths.registryFile);
1764
+ return text === null ? { entries: [], extraLines: [] } : parseRegistry(text);
1765
+ }
1766
+ function readRegistry(paths) {
1767
+ return readParsed(paths).entries;
1768
+ }
1769
+ function writeParsed(paths, parsed) {
1770
+ ensurePrivateDir(paths.configDir);
1771
+ writeFileAtomic(paths.registryFile, serializeRegistry(parsed.entries, parsed.extraLines), 384);
1772
+ }
1773
+ function upsertRegistryEntry(paths, entry) {
1774
+ serializeRegistry([entry]);
1775
+ const parsed = readParsed(paths);
1776
+ const others = parsed.entries.filter((item) => item.root !== entry.root);
1777
+ writeParsed(paths, { entries: [...others, entry], extraLines: parsed.extraLines });
1778
+ }
1779
+ function removeRegistryEntry(paths, root) {
1780
+ const parsed = readParsed(paths);
1781
+ const kept = parsed.entries.filter((item) => item.root !== root);
1782
+ if (kept.length === parsed.entries.length) {
1783
+ return false;
1784
+ }
1785
+ writeParsed(paths, { entries: kept, extraLines: parsed.extraLines });
1786
+ return true;
1787
+ }
1788
+ function moveRegistryEntry(paths, fromRoot, toEntry) {
1789
+ serializeRegistry([toEntry]);
1790
+ const parsed = readParsed(paths);
1791
+ const others = parsed.entries.filter((item) => item.root !== fromRoot && item.root !== toEntry.root);
1792
+ writeParsed(paths, { entries: [...others, toEntry], extraLines: parsed.extraLines });
1793
+ }
1794
+ function findEntryByRoot(entries, root) {
1795
+ return entries.find((item) => item.root === root) ?? null;
1796
+ }
1797
+ function findEntriesByRemote(entries, remote) {
1798
+ return entries.filter((item) => item.remote === remote);
1799
+ }
1800
+ function findEntryForPath(entries, target) {
1801
+ let best = null;
1802
+ for (const entry of entries) {
1803
+ const hit = target === entry.root || entry.mode === "tree" && `${target}/`.startsWith(`${entry.root}/`);
1804
+ if (hit && (best === null || entry.root.length > best.root.length)) {
1805
+ best = entry;
1806
+ }
1807
+ }
1808
+ return best;
1809
+ }
1810
+ function keyFilePathOf(paths, entry) {
1811
+ return path7.isAbsolute(entry.keyFile) ? entry.keyFile : path7.join(paths.configDir, entry.keyFile);
1812
+ }
1813
+ function isManagedKeyFile(paths, entry) {
1814
+ const absolute = keyFilePathOf(paths, entry);
1815
+ return path7.dirname(absolute) === paths.keysDir;
1816
+ }
1817
+
1818
+ // packages/cli/src/commands/connect.ts
1819
+ var RESUME_WAIT_MS = 9e4;
1820
+ var MAX_POLL_FAILURES = 3;
1821
+ function hostLabelOf(hostname2 = os3.hostname()) {
1822
+ const cleaned = hostname2.replace(/\.local$/i, "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
1823
+ const label = truncateCodePoints(cleaned, HOST_LABEL_MAX_LENGTH);
1824
+ return label === "" ? "computer" : label;
1825
+ }
1826
+ function clampInterval(seconds) {
1827
+ return Math.min(DEVICE_MAX_INTERVAL_SECONDS, Math.max(1, Math.round(seconds)));
1828
+ }
1829
+ function maybeOpenBrowser(ctx, url) {
1830
+ if (ctx.env.NESTEDGARDEN_NO_BROWSER === "1" || ctx.env.SSH_CONNECTION || isTestRun(ctx.env)) {
1831
+ return false;
1832
+ }
1833
+ let command;
1834
+ if (ctx.platform === "darwin") {
1835
+ command = "/usr/bin/open";
1836
+ } else if (ctx.platform === "linux" && (ctx.env.DISPLAY || ctx.env.WAYLAND_DISPLAY)) {
1837
+ command = "xdg-open";
1838
+ } else {
1839
+ return false;
1840
+ }
1841
+ try {
1842
+ const child = spawn(command, [url], { detached: true, stdio: "ignore", env: childEnv(ctx.env) });
1843
+ child.on("error", () => {
1844
+ });
1845
+ child.unref();
1846
+ return true;
1847
+ } catch {
1848
+ return false;
1849
+ }
1850
+ }
1851
+ function isRetryable(error) {
1852
+ if (error instanceof ApiError) {
1853
+ return error.code === "network" || error.code === "timeout" || error.status !== null && error.status >= 500;
1854
+ }
1855
+ return false;
1856
+ }
1857
+ async function waitForApproval(ctx, options) {
1858
+ let interval = clampInterval(options.interval);
1859
+ let failures = 0;
1860
+ let first = true;
1861
+ for (; ; ) {
1862
+ if (!(first && options.immediate)) {
1863
+ await ctx.sleep(interval * 1e3);
1864
+ }
1865
+ first = false;
1866
+ if (ctx.now() > options.deadline) {
1867
+ return { kind: "timeout" };
1868
+ }
1869
+ let poll;
1870
+ try {
1871
+ poll = await pollDeviceToken(options.server, options.deviceCode, ctx.env);
1872
+ failures = 0;
1873
+ } catch (error) {
1874
+ failures += 1;
1875
+ if (!isRetryable(error) || failures >= MAX_POLL_FAILURES) {
1876
+ return { kind: "error", message: describeError(error) };
1877
+ }
1878
+ continue;
1879
+ }
1880
+ if (poll.kind === "pending") {
1881
+ interval = clampInterval(poll.interval ?? interval);
1882
+ continue;
1883
+ }
1884
+ if (poll.kind === "slow_down") {
1885
+ interval = clampInterval(poll.interval ?? interval + DEVICE_SLOW_DOWN_STEP_SECONDS);
1886
+ continue;
1887
+ }
1888
+ return poll;
1889
+ }
1890
+ }
1891
+ function describeHelperRun(run, home) {
1892
+ if (run.exitCode !== 0) {
1893
+ return `\uC885\uB8CC \uCF54\uB4DC ${run.exitCode ?? "\uC5C6\uC74C"} \uB85C \uB05D\uB0A9\uB2C8\uB2E4`;
1894
+ }
1895
+ switch (run.source) {
1896
+ case "none": {
1897
+ return "\uD0A4\uB97C \uACE0\uB974\uC9C0 \uBABB\uD569\uB2C8\uB2E4 ({} \uB97C \uCC0D\uC74C)";
1898
+ }
1899
+ case "bad_key": {
1900
+ return `\uD0A4 \uD30C\uC77C ${run.keyFile ? displayPath(run.keyFile, home) : ""} \uC744 \uC77D\uC9C0 \uBABB\uD569\uB2C8\uB2E4`;
1901
+ }
1902
+ case "legacy": {
1903
+ return "\uC61B \uC190 \uC124\uC815(otel-headers.sh)\uC73C\uB85C \uB118\uC5B4\uAC11\uB2C8\uB2E4";
1904
+ }
1905
+ case "registry":
1906
+ case "worktree": {
1907
+ return `\uB2E4\uB978 \uD0A4 \uD30C\uC77C ${run.keyFile ? displayPath(run.keyFile, home) : ""} \uC744 \uACE0\uB985\uB2C8\uB2E4 (\uBFCC\uB9AC ${run.root ? displayPath(run.root, home) : ""})`;
1908
+ }
1909
+ default: {
1910
+ return "\uBB34\uC5C7\uC744 \uACE8\uB790\uB294\uC9C0 \uC54C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4";
1911
+ }
1912
+ }
1913
+ }
1914
+ function helperPicks(run, keyFile) {
1915
+ return run.exitCode === 0 && run.validJson && run.hasAuthorization && run.keyFile === keyFile;
1916
+ }
1917
+ async function completeConnection(ctx, paths, project, gateway, claude, token) {
1918
+ const home = paths.home;
1919
+ let problems = 0;
1920
+ let keyFile;
1921
+ try {
1922
+ keyFile = writeKeyFile(paths, token.key.id, token.agentKey);
1923
+ } catch (error) {
1924
+ failLine(ctx, `\uD0A4\uB97C \uC800\uC7A5\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${describeError(error)}. \uC6F9\uC758 \uC5D0\uC774\uC804\uD2B8 \uD654\uBA74\uC5D0\uC11C \uC774 \uD0A4(\uC55E\uC790\uB9AC ${token.key.keyPrefix})\uB97C \uD68C\uC218\uD574 \uC8FC\uC138\uC694.`);
1925
+ return 1;
1926
+ }
1927
+ const entry = {
1928
+ root: project.root,
1929
+ mode: project.mode,
1930
+ agentId: token.agent.id,
1931
+ keyFile,
1932
+ name: project.name,
1933
+ remote: project.remote,
1934
+ addedAt: new Date(ctx.now()).toISOString()
1935
+ };
1936
+ const keyFileAbsolute = keyFilePathOf(paths, entry);
1937
+ okLine(ctx, `\uD0A4\uB97C \uBC1B\uC558\uC2B5\uB2C8\uB2E4 \u2014 ${displayPath(keyFileAbsolute, home)} (\uD0A4 \uC55E\uC790\uB9AC ${token.key.keyPrefix})`);
1938
+ upsertRegistryEntry(paths, entry);
1939
+ okLine(ctx, `\uC5F0\uACB0 \uBAA9\uB85D\uC5D0 \uC801\uC5C8\uC2B5\uB2C8\uB2E4 \u2014 ${displayPath(paths.registryFile, home)}`);
1940
+ const installed = installHelper(paths);
1941
+ okLine(ctx, `\uD5E4\uB354 \uB3C4\uC6B0\uBBF8 ${displayPath(installed.path, home)}${installed.changed ? "" : " (\uADF8\uB300\uB85C)"}`);
1942
+ const applied = applyTelemetrySettings(paths, gateway, ctx.now());
1943
+ const settingsLabel = displayPath(paths.claudeSettingsFile, home);
1944
+ if (applied.result.refusal) {
1945
+ failLine(ctx, `${settingsLabel} \uB97C \uBC14\uAFB8\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4:
1946
+ ${applied.result.refusal.message.replace(/\n/g, "\n ")}`);
1947
+ problems += 1;
1948
+ } else if (applied.written) {
1949
+ okLine(ctx, `${settingsLabel}: ${applied.result.changes.join(" \xB7 ")}`);
1950
+ if (applied.backupFile) {
1951
+ ctx.io.out(` (\uBC14\uAFB8\uAE30 \uC804 \uC0AC\uBCF8: ${displayPath(applied.backupFile, home)})`);
1952
+ }
1953
+ } else {
1954
+ okLine(ctx, `${settingsLabel}: \uC774\uBBF8 \uB9DE\uC2B5\uB2C8\uB2E4`);
1955
+ }
1956
+ const attached = attachMcp(claude, project.root, {
1957
+ gatewayUrl: gateway,
1958
+ key: token.agentKey,
1959
+ env: ctx.env,
1960
+ version: claudeVersion(claude, ctx.env),
1961
+ globalConfigFile: paths.claudeGlobalConfigFile
1962
+ });
1963
+ if (attached.ok) {
1964
+ okLine(ctx, `\uC774 \uD3F4\uB354\uC5D0 nestedgarden MCP \uB97C \uBD99\uC600\uC2B5\uB2C8\uB2E4${attached.replaced ? " (\uC788\uB358 \uAC83\uC744 \uC0C8 \uD0A4\uB85C \uBC14\uAFC8)" : ""}`);
1965
+ } else {
1966
+ failLine(ctx, `nestedgarden MCP \uB97C \uBD99\uC774\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${attached.summary}`);
1967
+ problems += 1;
1968
+ }
1969
+ const run = runHelper(project.root, { helperPath: paths.helperFile, env: ctx.env });
1970
+ if (helperPicks(run, keyFileAbsolute)) {
1971
+ okLine(ctx, "\uD655\uC778: \uC774 \uD3F4\uB354\uC5D0\uC11C \uB3C4\uC6B0\uBBF8\uAC00 \uC774 \uD0A4 \uD30C\uC77C\uC744 \uACE0\uB985\uB2C8\uB2E4");
1972
+ } else {
1973
+ failLine(ctx, `\uD655\uC778 \uC2E4\uD328: \uC774 \uD3F4\uB354\uC5D0\uC11C \uB3C4\uC6B0\uBBF8\uAC00 ${describeHelperRun(run, home)}`);
1974
+ problems += 1;
1975
+ }
1976
+ let rootTitle = token.rootTitle;
1977
+ try {
1978
+ const who = await whoami(gateway, token.agentKey, ctx.env);
1979
+ if (who.ok) {
1980
+ rootTitle = who.data.rootTitle;
1981
+ } else {
1982
+ failLine(ctx, "\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC774 \uD0A4\uB97C \uBC1B\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4");
1983
+ problems += 1;
1984
+ }
1985
+ } catch (error) {
1986
+ warnLine(ctx, `\uAC8C\uC774\uD2B8\uC6E8\uC774 \uD655\uC778\uC744 \uAC74\uB108\uB701\uB2C8\uB2E4: ${describeError(error)}`);
1987
+ }
1988
+ deletePending(paths, project.root);
1989
+ if (problems > 0) {
1990
+ failLine(ctx, `\uC5F0\uACB0\uC740 \uB9CC\uB4E4\uC5C8\uC9C0\uB9CC \uACE0\uCE60 \uAC83\uC774 \uB0A8\uC558\uC2B5\uB2C8\uB2E4. \uACE0\uCE5C \uB4A4 ${COMMANDS.doctor} \uB85C \uD655\uC778\uD574 \uC8FC\uC138\uC694.`);
1991
+ return 1;
1992
+ }
1993
+ const email = token.account.email !== "" ? token.account.email : "(\uACC4\uC815 \uBA54\uC77C \uBAA8\uB984)";
1994
+ okLine(ctx, `\u300C${rootTitle}\u300D \xB7 ${email} \xB7 Claude Code \uCC3D\uC744 \uBAA8\uB450 \uB2EB\uACE0 \uB2E4\uC2DC \uCF1C \uC8FC\uC138\uC694`);
1995
+ return 0;
1996
+ }
1997
+ function reportWaitOutcome(ctx, paths, root, outcome) {
1998
+ switch (outcome.kind) {
1999
+ case "denied": {
2000
+ deletePending(paths, root);
2001
+ failLine(ctx, "\uC2B9\uC778 \uD654\uBA74\uC5D0\uC11C \uAC70\uC808\uD588\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uC5F0\uACB0\uD558\uB824\uBA74 \uCC98\uC74C\uBD80\uD130 \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.");
2002
+ return 1;
2003
+ }
2004
+ case "expired": {
2005
+ deletePending(paths, root);
2006
+ failLine(ctx, `\uC694\uCCAD\uC774 \uB9CC\uB8CC\uB410\uAC70\uB098 \uC774\uBBF8 \uBC1B\uC544 \uAC14\uC2B5\uB2C8\uB2E4. \uCC98\uC74C\uBD80\uD130 \uB2E4\uC2DC: ${COMMANDS.connect}`);
2007
+ return 1;
2008
+ }
2009
+ case "unknown_code": {
2010
+ deletePending(paths, root);
2011
+ failLine(ctx, `\uC11C\uBC84\uAC00 \uC774 \uC694\uCCAD\uC744 \uBAA8\uB985\uB2C8\uB2E4. \uCC98\uC74C\uBD80\uD130 \uB2E4\uC2DC: ${COMMANDS.connect}`);
2012
+ return 1;
2013
+ }
2014
+ case "error": {
2015
+ failLine(ctx, `\uC2B9\uC778 \uC0C1\uD0DC\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${outcome.message}`);
2016
+ return 1;
2017
+ }
2018
+ default: {
2019
+ return 1;
2020
+ }
2021
+ }
2022
+ }
2023
+ function startErrorMessage(error, server) {
2024
+ if (error instanceof ApiError) {
2025
+ switch (error.code) {
2026
+ case "upgrade_required": {
2027
+ return `\uC774 CLI \uD310(${CLI_VERSION})\uC740 \uB354 \uBC1B\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uC0C8 \uD310\uC73C\uB85C \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694: npx --yes nestedgarden@latest connect`;
2028
+ }
2029
+ case "rate_limited": {
2030
+ return "\uC694\uCCAD\uC774 \uB108\uBB34 \uB9CE\uC2B5\uB2C8\uB2E4. \uBA87 \uBD84 \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.";
2031
+ }
2032
+ case "wrong_host": {
2033
+ return `\uC774 \uC8FC\uC18C\uC5D0\uC11C\uB294 \uC5F0\uACB0\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 (${server}). \uAE30\uBCF8 \uC8FC\uC18C\uB85C \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`;
2034
+ }
2035
+ case "network":
2036
+ case "timeout": {
2037
+ return `${error.message}. \uC778\uD130\uB137 \uC5F0\uACB0\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694.`;
2038
+ }
2039
+ default: {
2040
+ return error.message;
2041
+ }
2042
+ }
2043
+ }
2044
+ return describeError(error);
2045
+ }
2046
+ function sameOrigin(url, origin) {
2047
+ try {
2048
+ const parsed = new URL(url);
2049
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && parsed.origin === origin;
2050
+ } catch {
2051
+ return false;
2052
+ }
2053
+ }
2054
+ async function runConnect(ctx, options) {
2055
+ let paths;
2056
+ let gateway;
2057
+ try {
2058
+ paths = resolvePaths(ctx.env);
2059
+ gateway = resolveGatewayUrl(ctx.env);
2060
+ } catch (error) {
2061
+ failLine(ctx, describeError(error));
2062
+ return 1;
2063
+ }
2064
+ const home = paths.home;
2065
+ const detected = detectProject(ctx.cwd, home, { allowHome: options.allowHome });
2066
+ if (!detected.ok) {
2067
+ failLine(ctx, detected.message);
2068
+ return detected.code === "cwd_missing" ? 1 : 2;
2069
+ }
2070
+ const project = detected.project;
2071
+ ctx.io.out(`\uD488\uC740\uC815\uC6D0 \uC5F0\uACB0 \u2014 ${project.name}`);
2072
+ const notes = [
2073
+ project.worktreeRoot ? `worktree ${displayPath(project.worktreeRoot, home)} \uC758 \uBCF8 \uC800\uC7A5\uC18C` : null,
2074
+ project.mode === "exact" ? "\uC774 \uD3F4\uB354\uB9CC, \uD558\uC704 \uD3F4\uB354 \uBE7C\uACE0" : null
2075
+ ].filter((note) => note !== null);
2076
+ ctx.io.out(` \uD3F4\uB354 ${displayPath(project.root, home)}${notes.length > 0 ? ` (${notes.join(", ")})` : ""}`);
2077
+ if (findEntryByRoot(readRegistry(paths), project.root)) {
2078
+ deletePending(paths, project.root);
2079
+ okLine(ctx, `\uC774\uBBF8 \uC5F0\uACB0\uB41C \uD3F4\uB354\uC785\uB2C8\uB2E4. \uC0C1\uD0DC \uD655\uC778\xB7\uACE0\uCE58\uAE30: ${COMMANDS.doctor}`);
2080
+ return 0;
2081
+ }
2082
+ if (runLegacyHelper(paths, project.root, ctx.env) !== null) {
2083
+ okLine(ctx, `\uC774 \uD3F4\uB354\uB294 \uC61B \uC190 \uC124\uC815(otel-headers.sh)\uC73C\uB85C \uC774\uBBF8 \uC5F0\uACB0\uB3FC \uC788\uC2B5\uB2C8\uB2E4. \uC0C8 \uD0A4\uB97C \uB9CC\uB4E4\uC9C0 \uC54A\uACE0 \uB118\uACA8\uBC1B\uAE30: ${COMMANDS.doctor}`);
2084
+ return 0;
2085
+ }
2086
+ let claude;
2087
+ try {
2088
+ claude = findClaude(ctx.env, ctx.platform, home);
2089
+ } catch (error) {
2090
+ failLine(ctx, describeError(error));
2091
+ return 1;
2092
+ }
2093
+ if (!claude) {
2094
+ failLine(ctx, "Claude Code(claude)\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uBA3C\uC800 \uC124\uCE58\uD55C \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694. \uB2E4\uB978 \uB3C4\uAD6C\uB294 \uC6F9\uC758 /connect \uC5D0 \uC788\uB294 \uC9C1\uC811 \uC124\uC815\uC744 \uB530\uB974\uC138\uC694.");
2095
+ return 1;
2096
+ }
2097
+ const preview = previewTelemetryMerge(paths, gateway);
2098
+ if (preview.refusal) {
2099
+ failLine(
2100
+ ctx,
2101
+ `${displayPath(paths.claudeSettingsFile, home)} \uC640 \uBD80\uB52A\uD600 \uBA48\uCDA5\uB2C8\uB2E4 (\uD0A4\uB294 \uC544\uC9C1 \uB9CC\uB4E4\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4):
2102
+ ${preview.refusal.message.replace(/\n/g, "\n ")}`
2103
+ );
2104
+ return 2;
2105
+ }
2106
+ for (const warning of [...preview.warnings, ...collectEnvironmentWarnings(paths, ctx.env, gateway)]) {
2107
+ warnLine(ctx, warning);
2108
+ }
2109
+ try {
2110
+ ensurePrivateDir(paths.configDir);
2111
+ } catch (error) {
2112
+ failLine(ctx, `\uC124\uC815 \uD3F4\uB354\uB97C \uB9CC\uB4E4\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4 (${displayPath(paths.configDir, home)}): ${describeError(error)}`);
2113
+ return 1;
2114
+ }
2115
+ if (options.resume) {
2116
+ const pending = loadPending(paths, project.root, ctx.now());
2117
+ if (!pending) {
2118
+ failLine(ctx, `\uC774 \uD3F4\uB354\uC5D0\uC11C \uAE30\uB2E4\uB9AC\uB294 \uC5F0\uACB0 \uC694\uCCAD\uC774 \uC5C6\uC2B5\uB2C8\uB2E4 (\uB9CC\uB8CC\uB410\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4). \uCC98\uC74C\uBD80\uD130: ${COMMANDS.connect}`);
2119
+ return 1;
2120
+ }
2121
+ let pendingServer;
2122
+ try {
2123
+ pendingServer = normalizeBaseUrl(pending.server, "\uC571", ctx.env);
2124
+ } catch (error) {
2125
+ deletePending(paths, project.root);
2126
+ failLine(ctx, `${describeError(error)}. \uCC98\uC74C\uBD80\uD130: ${COMMANDS.connect}`);
2127
+ return 1;
2128
+ }
2129
+ ctx.io.out(`\uC2B9\uC778\uC744 \uD655\uC778\uD569\uB2C8\uB2E4 (\uCF54\uB4DC ${pending.userCode}, \uCD5C\uB300 ${RESUME_WAIT_MS / 1e3}\uCD08)\u2026`);
2130
+ const outcome2 = await waitForApproval(ctx, {
2131
+ server: pendingServer,
2132
+ deviceCode: pending.deviceCode,
2133
+ interval: pending.interval,
2134
+ deadline: Math.min(ctx.now() + RESUME_WAIT_MS, Date.parse(pending.expiresAt)),
2135
+ immediate: true
2136
+ });
2137
+ if (outcome2.kind === "issued") {
2138
+ return completeConnection(ctx, paths, project, gateway, claude, outcome2.data);
2139
+ }
2140
+ if (outcome2.kind === "timeout") {
2141
+ failLine(ctx, "\uC544\uC9C1 \uC2B9\uC778\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.");
2142
+ ctx.io.out(` \uC8FC\uC18C ${pending.verificationUriComplete}`);
2143
+ ctx.io.out(` \uC2B9\uC778\uD55C \uB4A4 \uB2E4\uC2DC: ${COMMANDS.resume}`);
2144
+ return 1;
2145
+ }
2146
+ return reportWaitOutcome(ctx, paths, project.root, outcome2);
2147
+ }
2148
+ let server;
2149
+ try {
2150
+ server = resolveServerUrl(options.server, ctx.env);
2151
+ } catch (error) {
2152
+ failLine(ctx, describeError(error));
2153
+ return 2;
2154
+ }
2155
+ let started;
2156
+ try {
2157
+ started = await startDeviceAuthorization(
2158
+ server,
2159
+ { tool: DEVICE_TOOLS[0], cliVersion: CLI_VERSION, hostLabel: hostLabelOf(), projectName: project.name },
2160
+ ctx.env
2161
+ );
2162
+ } catch (error) {
2163
+ failLine(ctx, startErrorMessage(error, server));
2164
+ return 1;
2165
+ }
2166
+ const start = started.data;
2167
+ if (!sameOrigin(start.verificationUriComplete, started.origin) || !sameOrigin(start.verificationUri, started.origin)) {
2168
+ failLine(ctx, "\uC11C\uBC84\uAC00 \uC900 \uC2B9\uC778 \uC8FC\uC18C\uAC00 \uC694\uCCAD\uD55C \uC11C\uBC84\uC640 \uB2E4\uB985\uB2C8\uB2E4. \uBA48\uCDA5\uB2C8\uB2E4.");
2169
+ return 1;
2170
+ }
2171
+ const minutes = Math.max(1, Math.round(start.expiresIn / 60));
2172
+ const normalizedCode = normalizeUserCode(start.userCode);
2173
+ const userCode = normalizedCode ? formatUserCode(normalizedCode) : start.userCode;
2174
+ ctx.io.out("");
2175
+ ctx.io.out("\uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC774 \uCEF4\uD4E8\uD130\uC758 \uC5F0\uACB0\uC744 \uC2B9\uC778\uD574 \uC8FC\uC138\uC694.");
2176
+ ctx.io.out(` \uC8FC\uC18C ${start.verificationUriComplete}`);
2177
+ ctx.io.out(` \uCF54\uB4DC ${userCode} (${minutes}\uBD84 \uC548\uC5D0)`);
2178
+ savePending(paths, {
2179
+ deviceCode: start.deviceCode,
2180
+ userCode,
2181
+ server,
2182
+ root: project.root,
2183
+ expiresAt: new Date(ctx.now() + (start.expiresIn + APPROVED_COLLECT_TTL_SECONDS) * 1e3).toISOString(),
2184
+ interval: start.interval || DEVICE_POLL_INTERVAL_SECONDS,
2185
+ verificationUriComplete: start.verificationUriComplete
2186
+ });
2187
+ if (maybeOpenBrowser(ctx, start.verificationUriComplete)) {
2188
+ ctx.io.out(" (\uBE0C\uB77C\uC6B0\uC800\uB97C \uC5F4\uC5C8\uC2B5\uB2C8\uB2E4)");
2189
+ }
2190
+ if (ctx.env.CLAUDECODE) {
2191
+ ctx.io.out("");
2192
+ ctx.io.out("Claude Code \uC138\uC158 \uC548\uC774\uB77C \uC5EC\uAE30\uC11C \uAE30\uB2E4\uB9AC\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.");
2193
+ ctx.io.out("\u2192 \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uC704 \uC8FC\uC18C\uB97C \uBCF4\uC5EC \uC8FC\uC138\uC694. \uC0AC\uC6A9\uC790\uAC00 \uC2B9\uC778\uD588\uB2E4\uACE0 \uD558\uBA74 \uC774 \uBA85\uB839\uC744 \uC2E4\uD589\uD558\uC138\uC694:");
2194
+ ctx.io.out(` ${COMMANDS.resume}`);
2195
+ return 0;
2196
+ }
2197
+ ctx.io.out("");
2198
+ ctx.io.out("\uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uB294 \uC911\uC785\uB2C8\uB2E4\u2026 (\uADF8\uB9CC\uB450\uB824\uBA74 Ctrl+C. \uC2B9\uC778\uD55C \uB4A4 \uB04A\uACBC\uB2E4\uBA74 --resume \uC73C\uB85C \uB9C8\uBB34\uB9AC\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4)");
2199
+ const outcome = await waitForApproval(ctx, {
2200
+ server,
2201
+ deviceCode: start.deviceCode,
2202
+ interval: start.interval,
2203
+ deadline: ctx.now() + start.expiresIn * 1e3,
2204
+ immediate: false
2205
+ });
2206
+ if (outcome.kind === "issued") {
2207
+ return completeConnection(ctx, paths, project, gateway, claude, outcome.data);
2208
+ }
2209
+ if (outcome.kind === "timeout") {
2210
+ deletePending(paths, project.root);
2211
+ failLine(ctx, `${minutes}\uBD84 \uC548\uC5D0 \uC2B9\uC778\uB418\uC9C0 \uC54A\uC544 \uC694\uCCAD\uC774 \uB9CC\uB8CC\uB410\uC2B5\uB2C8\uB2E4. \uCC98\uC74C\uBD80\uD130 \uB2E4\uC2DC: ${COMMANDS.connect}`);
2212
+ return 1;
2213
+ }
2214
+ return reportWaitOutcome(ctx, paths, project.root, outcome);
2215
+ }
2216
+
2217
+ // packages/cli/src/commands/disconnect.ts
2218
+ import * as fs6 from "node:fs";
2219
+ async function disconnectOne(ctx, paths, gateway, entry, getClaude) {
2220
+ const home = paths.home;
2221
+ let partial = false;
2222
+ ctx.io.out(`\u2014 ${displayPath(entry.root, home)} (${entry.name})`);
2223
+ const keyFile = keyFilePathOf(paths, entry);
2224
+ const key = readKeyFile(keyFile);
2225
+ if (key !== null) {
2226
+ try {
2227
+ const revoked = await revokeSelf(gateway, key, ctx.env);
2228
+ okLine(ctx, revoked.ok ? "\uD0A4\uB97C \uD68C\uC218\uD588\uC2B5\uB2C8\uB2E4" : "\uD0A4\uB294 \uC774\uBBF8 \uD68C\uC218\uB3FC \uC788\uC2B5\uB2C8\uB2E4");
2229
+ } catch (error) {
2230
+ failLine(
2231
+ ctx,
2232
+ `\uD0A4\uB97C \uD68C\uC218\uD558\uC9C0 \uBABB\uD574 \uC774 \uD3F4\uB354\uC758 \uC5F0\uACB0\uC740 \uADF8\uB300\uB85C \uB461\uB2C8\uB2E4: ${describeError(error)}. \uB2E4\uC2DC \uC2E4\uD589\uD558\uAC70\uB098 \uC6F9\uC758 \uC5D0\uC774\uC804\uD2B8 \uD654\uBA74\uC5D0\uC11C \uD68C\uC218\uD558\uC138\uC694.`
2233
+ );
2234
+ return "kept";
2235
+ }
2236
+ } else {
2237
+ warnLine(ctx, "\uD0A4 \uD30C\uC77C\uC774 \uC5C6\uC5B4 \uD68C\uC218\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uD544\uC694\uD558\uBA74 \uC6F9\uC758 \uC5D0\uC774\uC804\uD2B8 \uD654\uBA74\uC5D0\uC11C \uD68C\uC218\uD558\uC138\uC694.");
2238
+ }
2239
+ const mcp = readMcpEntry(paths.claudeGlobalConfigFile, entry.root, { url: "", key: null });
2240
+ if (mcp.exists) {
2241
+ if (!fs6.existsSync(entry.root)) {
2242
+ warnLine(ctx, "\uD3F4\uB354\uAC00 \uC5C6\uC5B4 nestedgarden MCP \uB294 \uB5BC\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4 (\uADF8\uB300\uB85C \uB46C\uB3C4 \uB429\uB2C8\uB2E4).");
2243
+ } else {
2244
+ const claude = getClaude();
2245
+ if (!claude) {
2246
+ failLine(ctx, "Claude Code(claude)\uB97C \uCC3E\uC9C0 \uBABB\uD574 nestedgarden MCP \uB97C \uB5BC\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.");
2247
+ partial = true;
2248
+ } else {
2249
+ const detached = detachMcp(claude, entry.root, { env: ctx.env, globalConfigFile: paths.claudeGlobalConfigFile });
2250
+ if (detached.ok) {
2251
+ okLine(ctx, "\uC774 \uD3F4\uB354\uC758 nestedgarden MCP \uB97C \uB5D0\uC2B5\uB2C8\uB2E4");
2252
+ } else {
2253
+ failLine(ctx, `nestedgarden MCP \uB97C \uB5BC\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${detached.summary}`);
2254
+ partial = true;
2255
+ }
2256
+ }
2257
+ }
2258
+ }
2259
+ if (isManagedKeyFile(paths, entry)) {
2260
+ if (removeIfExists(keyFile)) {
2261
+ okLine(ctx, `\uD0A4 \uD30C\uC77C\uC744 \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4 \u2014 ${displayPath(keyFile, home)}`);
2262
+ }
2263
+ } else {
2264
+ warnLine(
2265
+ ctx,
2266
+ `\uC61B \uC190 \uC124\uC815\uC758 \uD0A4 \uD30C\uC77C ${displayPath(keyFile, home)} \uB294 \uC9C0\uC6B0\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4 (\uD0A4\uB294 \uD68C\uC218\uB428). \uC61B \uB3C4\uC6B0\uBBF8(otel-headers.sh)\uC758 \uADF8 \uD3F4\uB354 \uC904\uACFC \uD568\uAED8 \uD544\uC694 \uC5C6\uC73C\uBA74 \uC9C1\uC811 \uC9C0\uC6B0\uC138\uC694.`
2267
+ );
2268
+ }
2269
+ removeRegistryEntry(paths, entry.root);
2270
+ deletePending(paths, entry.root);
2271
+ okLine(ctx, "\uC5F0\uACB0 \uBAA9\uB85D\uC5D0\uC11C \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4");
2272
+ return partial ? "partial" : "done";
2273
+ }
2274
+ function revertSettings(ctx, paths) {
2275
+ const home = paths.home;
2276
+ const settingsLabel = displayPath(paths.claudeSettingsFile, home);
2277
+ const applied = applySettingsChange(
2278
+ paths,
2279
+ (text) => revertTelemetrySettings(text, {
2280
+ helperPath: paths.helperFile,
2281
+ legacyHelperPath: paths.legacyHelperFile,
2282
+ legacyHelperExists: isExecutableFile(paths.legacyHelperFile),
2283
+ addedEnv: readAddedEnv(paths),
2284
+ home
2285
+ }),
2286
+ ctx.now()
2287
+ );
2288
+ if (applied.result.refusal) {
2289
+ failLine(ctx, `${settingsLabel} \uB97C \uB418\uB3CC\uB9AC\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4:
2290
+ ${applied.result.refusal.message.replace(/\n/g, "\n ")}`);
2291
+ return false;
2292
+ }
2293
+ if (applied.written) {
2294
+ okLine(ctx, `${settingsLabel} \uB97C \uB418\uB3CC\uB838\uC2B5\uB2C8\uB2E4: ${applied.result.changes.join(" \xB7 ")}`);
2295
+ if (applied.backupFile) {
2296
+ ctx.io.out(` (\uBC14\uAFB8\uAE30 \uC804 \uC0AC\uBCF8: ${displayPath(applied.backupFile, home)})`);
2297
+ }
2298
+ } else {
2299
+ okLine(ctx, `${settingsLabel} \uC5D0 \uB418\uB3CC\uB9B4 \uAC83\uC774 \uC5C6\uC2B5\uB2C8\uB2E4`);
2300
+ }
2301
+ clearAddedEnv(paths);
2302
+ if (settingsReferencesHelper(paths)) {
2303
+ warnLine(ctx, `${settingsLabel} \uAC00 \uC544\uC9C1 \uD5E4\uB354 \uB3C4\uC6B0\uBBF8\uB97C \uAC00\uB9AC\uCF1C \uB3C4\uC6B0\uBBF8 \uD30C\uC77C\uC740 \uB0A8\uACA8 \uB461\uB2C8\uB2E4.`);
2304
+ } else if (removeIfExists(paths.helperFile)) {
2305
+ okLine(ctx, `\uD5E4\uB354 \uB3C4\uC6B0\uBBF8\uB97C \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4 \u2014 ${displayPath(paths.helperFile, home)}`);
2306
+ }
2307
+ return true;
2308
+ }
2309
+ async function runDisconnect(ctx, options) {
2310
+ let paths;
2311
+ let gateway;
2312
+ try {
2313
+ paths = resolvePaths(ctx.env);
2314
+ gateway = resolveGatewayUrl(ctx.env);
2315
+ } catch (error) {
2316
+ failLine(ctx, describeError(error));
2317
+ return 1;
2318
+ }
2319
+ const home = paths.home;
2320
+ const entries = readRegistry(paths);
2321
+ let targets;
2322
+ if (options.all) {
2323
+ targets = entries;
2324
+ ctx.io.out(`\uD488\uC740\uC815\uC6D0 \uC5F0\uACB0 \uB04A\uAE30 \u2014 \uBAA8\uB4E0 \uD3F4\uB354 (${entries.length}\uACF3)`);
2325
+ } else {
2326
+ const detected = detectProject(ctx.cwd, home, { allowHome: true });
2327
+ if (!detected.ok) {
2328
+ failLine(ctx, detected.message);
2329
+ return detected.code === "cwd_missing" ? 1 : 2;
2330
+ }
2331
+ const project = detected.project;
2332
+ const exact = findEntryByRoot(entries, project.root);
2333
+ if (!exact) {
2334
+ const covering = findEntryForPath(entries, project.cwd);
2335
+ if (covering) {
2336
+ failLine(ctx, `\uC774 \uD3F4\uB354\uB294 ${displayPath(covering.root, home)} \uC758 \uC5F0\uACB0\uC5D0 \uB4E4\uC5B4 \uC788\uC2B5\uB2C8\uB2E4. \uADF8 \uD3F4\uB354\uC5D0\uC11C \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`);
2337
+ return 2;
2338
+ }
2339
+ deletePending(paths, project.root);
2340
+ ctx.io.out("\uC774 \uD3F4\uB354\uB294 nestedgarden CLI \uB85C \uC5F0\uACB0\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.");
2341
+ if (readMcpEntry(paths.claudeGlobalConfigFile, project.root, { url: "", key: null }).exists) {
2342
+ warnLine(
2343
+ ctx,
2344
+ `\uC774 \uD3F4\uB354\uC5D0 \uC190\uC73C\uB85C \uBD99\uC778 nestedgarden MCP \uAC00 \uC788\uC2B5\uB2C8\uB2E4. ${COMMANDS.doctor} \uB85C \uB118\uACA8\uBC1B\uC740 \uB4A4 \uB04A\uAC70\uB098, \uC774 \uD3F4\uB354\uC5D0\uC11C claude mcp remove nestedgarden --scope local \uB85C \uB5BC\uC138\uC694.`
2345
+ );
2346
+ }
2347
+ return 0;
2348
+ }
2349
+ ctx.io.out("\uD488\uC740\uC815\uC6D0 \uC5F0\uACB0 \uB04A\uAE30");
2350
+ targets = [exact];
2351
+ }
2352
+ let claude;
2353
+ let claudeError = null;
2354
+ const getClaude = () => {
2355
+ if (claude === void 0) {
2356
+ try {
2357
+ claude = findClaude(ctx.env, ctx.platform, home);
2358
+ } catch (error) {
2359
+ claudeError = describeError(error);
2360
+ claude = null;
2361
+ }
2362
+ }
2363
+ return claude;
2364
+ };
2365
+ let problems = 0;
2366
+ for (const entry of targets) {
2367
+ const outcome = await disconnectOne(ctx, paths, gateway, entry, getClaude);
2368
+ if (outcome !== "done") {
2369
+ problems += 1;
2370
+ }
2371
+ }
2372
+ if (claudeError) {
2373
+ failLine(ctx, claudeError);
2374
+ }
2375
+ if (options.all) {
2376
+ const kept = readRegistry(paths);
2377
+ if (kept.length > 0) {
2378
+ failLine(ctx, `\uB04A\uC9C0 \uBABB\uD55C \uD3F4\uB354\uAC00 ${kept.length}\uACF3 \uC788\uC5B4 settings.json \uC740 \uB418\uB3CC\uB9AC\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694.`);
2379
+ problems += 1;
2380
+ } else if (!revertSettings(ctx, paths)) {
2381
+ problems += 1;
2382
+ }
2383
+ }
2384
+ if (problems > 0) {
2385
+ failLine(ctx, "\uB04A\uC9C0 \uBABB\uD55C \uAC83\uC774 \uB0A8\uC558\uC2B5\uB2C8\uB2E4. \uC704 \uC904\uC744 \uD655\uC778\uD574 \uC8FC\uC138\uC694.");
2386
+ return 1;
2387
+ }
2388
+ okLine(ctx, "\uC5F0\uACB0\uC744 \uB04A\uC5C8\uC2B5\uB2C8\uB2E4. \uC5F4\uB824 \uC788\uB294 Claude Code \uCC3D\uC740 \uB2E4\uC2DC \uCF1C\uC57C \uBC18\uC601\uB429\uB2C8\uB2E4.");
2389
+ return 0;
2390
+ }
2391
+
2392
+ // packages/cli/src/commands/doctor.ts
2393
+ import * as fs7 from "node:fs";
2394
+ function reportStaleMcp(ctx, paths) {
2395
+ for (const item of listMcpRoots(paths.claudeGlobalConfigFile)) {
2396
+ if (!item.exists) {
2397
+ warnLine(
2398
+ ctx,
2399
+ `\uC0AC\uB77C\uC9C4 \uD3F4\uB354 ${displayPath(item.root, paths.home)} \uC5D0 nestedgarden MCP \uAC00 \uB0A8\uC544 \uC788\uC2B5\uB2C8\uB2E4 (\uADF8\uB300\uB85C \uB46C\uB3C4 \uB429\uB2C8\uB2E4 \u2014 \uADF8 \uD3F4\uB354\uB97C \uB2E4\uC2DC \uC5F4 \uC77C\uC774 \uC5C6\uC73C\uBA74 \uC4F0\uC774\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4).`
2400
+ );
2401
+ }
2402
+ }
2403
+ }
2404
+ async function findOrRecoverEntry(ctx, paths, project, gateway, fix) {
2405
+ const home = paths.home;
2406
+ let problems = 0;
2407
+ let reported = false;
2408
+ if (project.remote) {
2409
+ const vanished = findEntriesByRemote(readRegistry(paths), project.remote).filter((item) => !fs7.existsSync(item.root));
2410
+ if (vanished.length === 1) {
2411
+ const old = vanished[0];
2412
+ if (!fix) {
2413
+ failLine(
2414
+ ctx,
2415
+ `\uD3F4\uB354 \uC774\uB984\uC774 \uBC14\uB010 \uAC83 \uAC19\uC2B5\uB2C8\uB2E4: ${displayPath(old.root, home)} \u2192 ${displayPath(project.root, home)}. \uACE0\uCE58\uB824\uBA74 --check \uC5C6\uC774 doctor \uB97C \uC2E4\uD589\uD558\uC138\uC694.`
2416
+ );
2417
+ return { entry: null, reported: true, problems: 1 };
2418
+ }
2419
+ const moved = { ...old, root: project.root, mode: project.mode, name: project.name };
2420
+ moveRegistryEntry(paths, old.root, moved);
2421
+ okLine(ctx, `\uD3F4\uB354 \uC774\uB984\uC774 \uBC14\uB010 \uAC83\uC744 \uACE0\uCCE4\uC2B5\uB2C8\uB2E4: ${displayPath(old.root, home)} \u2192 ${displayPath(project.root, home)}`);
2422
+ return { entry: moved };
2423
+ }
2424
+ if (vanished.length > 1) {
2425
+ failLine(
2426
+ ctx,
2427
+ `\uAC19\uC740 \uC800\uC7A5\uC18C(${project.remote})\uB97C \uAC00\uB9AC\uD0A4\uB358 \uC0AC\uB77C\uC9C4 \uD3F4\uB354\uAC00 \uC5EC\uB7FF\uC774\uB77C \uC5B4\uB290 \uAC83\uC778\uC9C0 \uC815\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ` + vanished.map((item) => displayPath(item.root, home)).join(", ")
2428
+ );
2429
+ problems += 1;
2430
+ reported = true;
2431
+ }
2432
+ }
2433
+ const legacyKey = runLegacyHelper(paths, project.root, ctx.env);
2434
+ if (legacyKey !== null) {
2435
+ const keyFileName = findLegacyKeyFile(paths, legacyKey);
2436
+ if (!keyFileName) {
2437
+ failLine(
2438
+ ctx,
2439
+ "\uC61B \uC190 \uC124\uC815(otel-headers.sh)\uC774 \uC774 \uD3F4\uB354\uC5D0 \uD0A4\uB97C \uB0B4\uC9C0\uB9CC, \uADF8 \uD0A4\uAC00 \uB4E0 \uD0A4 \uD30C\uC77C(*.key)\uC744 \uC124\uC815 \uD3F4\uB354\uC5D0\uC11C \uCC3E\uC9C0 \uBABB\uD574 \uB118\uACA8\uBC1B\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4."
2440
+ );
2441
+ return { entry: null, reported: true, problems: problems + 1 };
2442
+ }
2443
+ let who;
2444
+ try {
2445
+ who = await whoami(gateway, legacyKey, ctx.env);
2446
+ } catch (error) {
2447
+ failLine(ctx, `\uC61B \uD0A4 ${keyFileName} \uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${describeError(error)}`);
2448
+ return { entry: null, reported: true, problems: problems + 1 };
2449
+ }
2450
+ if (!who.ok) {
2451
+ failLine(ctx, `\uC61B \uD0A4 ${keyFileName} \uB294 \uB354 \uC4F8 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 (\uD68C\uC218\uB410\uAC70\uB098 \uB098\uBB34\uAC00 \uC9C0\uC6CC\uC9D0). \uC0C8\uB85C \uC5F0\uACB0: ${COMMANDS.connect}`);
2452
+ return { entry: null, reported: true, problems: problems + 1 };
2453
+ }
2454
+ if (!fix) {
2455
+ failLine(
2456
+ ctx,
2457
+ `\uC61B \uC190 \uC124\uC815\uC758 \uD0A4 ${keyFileName}(\u300C${who.data.rootTitle}\u300D)\uB97C \uB118\uACA8\uBC1B\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uB118\uACA8\uBC1B\uC73C\uB824\uBA74 --check \uC5C6\uC774 doctor \uB97C \uC2E4\uD589\uD558\uC138\uC694.`
2458
+ );
2459
+ return { entry: null, reported: true, problems: problems + 1 };
2460
+ }
2461
+ const adopted = {
2462
+ root: project.root,
2463
+ mode: project.mode,
2464
+ agentId: who.data.agent.id,
2465
+ keyFile: keyFileName,
2466
+ name: project.name,
2467
+ remote: project.remote,
2468
+ addedAt: new Date(ctx.now()).toISOString()
2469
+ };
2470
+ upsertRegistryEntry(paths, adopted);
2471
+ okLine(ctx, `\uC61B \uC190 \uC124\uC815\uC758 \uD0A4 ${keyFileName}(\u300C${who.data.rootTitle}\u300D)\uB97C \uB118\uACA8\uBC1B\uC558\uC2B5\uB2C8\uB2E4. \uC0C8 \uD0A4\uB294 \uB9CC\uB4E4\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.`);
2472
+ return { entry: adopted };
2473
+ }
2474
+ return { entry: null, reported, problems };
2475
+ }
2476
+ async function runDoctor(ctx, options) {
2477
+ let paths;
2478
+ let gateway;
2479
+ try {
2480
+ paths = resolvePaths(ctx.env);
2481
+ gateway = resolveGatewayUrl(ctx.env);
2482
+ } catch (error) {
2483
+ failLine(ctx, describeError(error));
2484
+ return 1;
2485
+ }
2486
+ const home = paths.home;
2487
+ const fix = !options.check;
2488
+ ctx.io.out(`\uD488\uC740\uC815\uC6D0 \uC5F0\uACB0 \uC810\uAC80${fix ? "" : " (\uBCF4\uAE30\uB9CC)"}`);
2489
+ const cwdReal = safeRealpath(ctx.cwd);
2490
+ if (!cwdReal) {
2491
+ failLine(ctx, `\uC9C0\uAE08 \uD3F4\uB354\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${ctx.cwd}`);
2492
+ return 1;
2493
+ }
2494
+ let problems = 0;
2495
+ const entries = readRegistry(paths);
2496
+ const mapped = mapWorktreePath(cwdReal);
2497
+ let entry = findEntryForPath(entries, cwdReal) ?? (mapped ? findEntryForPath(entries, mapped) : null);
2498
+ if (!entry) {
2499
+ const detected = detectProject(ctx.cwd, home, { allowHome: true });
2500
+ if (!detected.ok) {
2501
+ failLine(ctx, detected.message);
2502
+ return 1;
2503
+ }
2504
+ const recovered = await findOrRecoverEntry(ctx, paths, detected.project, gateway, fix);
2505
+ if (recovered.entry === null) {
2506
+ if (!recovered.reported) {
2507
+ failLine(ctx, `\uC774 \uD3F4\uB354\uB294 \uC5F0\uACB0\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uC5F0\uACB0: ${COMMANDS.connect}`);
2508
+ }
2509
+ reportStaleMcp(ctx, paths);
2510
+ return 1;
2511
+ }
2512
+ entry = recovered.entry;
2513
+ }
2514
+ ctx.io.out(` \uD3F4\uB354 ${displayPath(entry.root, home)} \xB7 \uC774\uB984 ${entry.name}`);
2515
+ const keyFile = keyFilePathOf(paths, entry);
2516
+ const key = readKeyFile(keyFile);
2517
+ if (key === null) {
2518
+ failLine(ctx, `\uD0A4 \uD30C\uC77C\uC774 \uC5C6\uAC70\uB098 \uAF34\uC774 \uD2C0\uB9BD\uB2C8\uB2E4: ${displayPath(keyFile, home)}. ${COMMANDS.disconnect} \uB4A4 ${COMMANDS.connect}`);
2519
+ problems += 1;
2520
+ } else {
2521
+ if (fileMode(keyFile) !== 384) {
2522
+ if (fix) {
2523
+ fs7.chmodSync(keyFile, 384);
2524
+ okLine(ctx, `\uD0A4 \uD30C\uC77C \uAD8C\uD55C\uC744 600 \uC73C\uB85C \uACE0\uCCE4\uC2B5\uB2C8\uB2E4 \u2014 ${displayPath(keyFile, home)}`);
2525
+ } else {
2526
+ failLine(ctx, `\uD0A4 \uD30C\uC77C \uAD8C\uD55C\uC774 600 \uC774 \uC544\uB2D9\uB2C8\uB2E4 \u2014 ${displayPath(keyFile, home)}`);
2527
+ problems += 1;
2528
+ }
2529
+ } else {
2530
+ okLine(ctx, `\uD0A4 \uD30C\uC77C ${displayPath(keyFile, home)} (600)`);
2531
+ }
2532
+ try {
2533
+ const who = await whoami(gateway, key, ctx.env);
2534
+ if (who.ok) {
2535
+ okLine(ctx, `\uAC8C\uC774\uD2B8\uC6E8\uC774: \u300C${who.data.rootTitle}\u300D (\uD0A4 \uC55E\uC790\uB9AC ${who.data.key.keyPrefix})`);
2536
+ } else {
2537
+ failLine(ctx, `\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC774 \uD0A4\uB97C \uBC1B\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4 (\uD68C\uC218\uB410\uAC70\uB098 \uB098\uBB34\uAC00 \uC9C0\uC6CC\uC9D0). ${COMMANDS.disconnect} \uB4A4 ${COMMANDS.connect}`);
2538
+ problems += 1;
2539
+ }
2540
+ } catch (error) {
2541
+ failLine(ctx, `\uAC8C\uC774\uD2B8\uC6E8\uC774\uC5D0 \uB2FF\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${describeError(error)}`);
2542
+ problems += 1;
2543
+ }
2544
+ }
2545
+ const settingsLabel = displayPath(paths.claudeSettingsFile, home);
2546
+ const preview = previewTelemetryMerge(paths, gateway);
2547
+ if (preview.refusal) {
2548
+ failLine(ctx, `${settingsLabel} \uC640 \uBD80\uB52A\uD799\uB2C8\uB2E4:
2549
+ ${preview.refusal.message.replace(/\n/g, "\n ")}`);
2550
+ problems += 1;
2551
+ } else if (preview.changes.length > 0) {
2552
+ if (fix) {
2553
+ const applied = applyTelemetrySettings(paths, gateway, ctx.now());
2554
+ if (applied.result.refusal) {
2555
+ failLine(ctx, `${settingsLabel} \uB97C \uACE0\uCE58\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4:
2556
+ ${applied.result.refusal.message.replace(/\n/g, "\n ")}`);
2557
+ problems += 1;
2558
+ } else {
2559
+ okLine(ctx, `${settingsLabel} \uB97C \uACE0\uCCE4\uC2B5\uB2C8\uB2E4: ${applied.result.changes.join(" \xB7 ") || "\uBC14\uAFC0 \uAC83 \uC5C6\uC74C"}`);
2560
+ }
2561
+ } else {
2562
+ failLine(ctx, `${settingsLabel} \uC5D0 \uACE0\uCE60 \uAC83: ${preview.changes.join(" \xB7 ")}`);
2563
+ problems += 1;
2564
+ }
2565
+ } else {
2566
+ okLine(ctx, `${settingsLabel} \uC758 \uD154\uB808\uBA54\uD2B8\uB9AC \uC124\uC815\uC774 \uB9DE\uC2B5\uB2C8\uB2E4`);
2567
+ }
2568
+ for (const warning of [...preview.warnings, ...collectEnvironmentWarnings(paths, ctx.env, gateway)]) {
2569
+ warnLine(ctx, warning);
2570
+ }
2571
+ if (isHelperCurrent(paths)) {
2572
+ okLine(ctx, `\uD5E4\uB354 \uB3C4\uC6B0\uBBF8 ${displayPath(paths.helperFile, home)}`);
2573
+ } else if (fix) {
2574
+ installHelper(paths);
2575
+ okLine(ctx, `\uD5E4\uB354 \uB3C4\uC6B0\uBBF8\uB97C \uB2E4\uC2DC \uAE54\uC558\uC2B5\uB2C8\uB2E4 \u2014 ${displayPath(paths.helperFile, home)}`);
2576
+ } else {
2577
+ failLine(ctx, `\uD5E4\uB354 \uB3C4\uC6B0\uBBF8\uAC00 \uC5C6\uAC70\uB098 \uC61B \uD310\uC785\uB2C8\uB2E4 \u2014 ${displayPath(paths.helperFile, home)}`);
2578
+ problems += 1;
2579
+ }
2580
+ if (fs7.existsSync(paths.helperFile) && fs7.existsSync(entry.root)) {
2581
+ const run = runHelper(entry.root, { helperPath: paths.helperFile, env: ctx.env });
2582
+ if (helperPicks(run, keyFile)) {
2583
+ okLine(ctx, "\uC774 \uD3F4\uB354\uC5D0\uC11C \uB3C4\uC6B0\uBBF8\uAC00 \uC774 \uD0A4 \uD30C\uC77C\uC744 \uACE0\uB985\uB2C8\uB2E4");
2584
+ } else {
2585
+ failLine(ctx, `\uC774 \uD3F4\uB354\uC5D0\uC11C \uB3C4\uC6B0\uBBF8\uAC00 ${describeHelperRun(run, home)}`);
2586
+ problems += 1;
2587
+ }
2588
+ }
2589
+ const state = readMcpEntry(paths.claudeGlobalConfigFile, entry.root, { url: mcpUrlFor(gateway), key });
2590
+ if (state.exists && state.urlMatches && state.keyMatches !== false) {
2591
+ okLine(ctx, "\uC774 \uD3F4\uB354\uC758 nestedgarden MCP \uAC00 \uB9DE\uC2B5\uB2C8\uB2E4");
2592
+ } else {
2593
+ const what = state.exists ? "nestedgarden MCP \uC758 \uC8FC\uC18C\uB098 \uD0A4\uAC00 \uB2E4\uB985\uB2C8\uB2E4" : "\uC774 \uD3F4\uB354\uC5D0 nestedgarden MCP \uAC00 \uC5C6\uC2B5\uB2C8\uB2E4";
2594
+ if (!fix) {
2595
+ failLine(ctx, what);
2596
+ problems += 1;
2597
+ } else if (key === null) {
2598
+ failLine(ctx, `${what} \u2014 \uD0A4\uAC00 \uC5C6\uC5B4 \uB2E4\uC2DC \uBD99\uC77C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4`);
2599
+ problems += 1;
2600
+ } else if (!fs7.existsSync(entry.root)) {
2601
+ failLine(ctx, `${what} \u2014 \uD3F4\uB354\uAC00 \uC5C6\uC5B4 \uB2E4\uC2DC \uBD99\uC77C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4`);
2602
+ problems += 1;
2603
+ } else {
2604
+ let claude = null;
2605
+ try {
2606
+ claude = findClaude(ctx.env, ctx.platform, home);
2607
+ } catch (error) {
2608
+ failLine(ctx, describeError(error));
2609
+ }
2610
+ if (!claude) {
2611
+ failLine(ctx, `${what} \u2014 Claude Code(claude)\uB97C \uCC3E\uC9C0 \uBABB\uD574 \uB2E4\uC2DC \uBD99\uC774\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4`);
2612
+ problems += 1;
2613
+ } else {
2614
+ const attached = attachMcp(claude, entry.root, {
2615
+ gatewayUrl: gateway,
2616
+ key,
2617
+ env: ctx.env,
2618
+ version: claudeVersion(claude, ctx.env),
2619
+ globalConfigFile: paths.claudeGlobalConfigFile
2620
+ });
2621
+ if (attached.ok) {
2622
+ okLine(ctx, "nestedgarden MCP \uB97C \uB2E4\uC2DC \uBD99\uC600\uC2B5\uB2C8\uB2E4 (\uC5F4\uB824 \uC788\uB294 Claude Code \uCC3D\uC740 \uB2E4\uC2DC \uCF1C\uC57C \uBC18\uC601\uB429\uB2C8\uB2E4)");
2623
+ } else {
2624
+ failLine(ctx, `nestedgarden MCP \uB97C \uB2E4\uC2DC \uBD99\uC774\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${attached.summary}`);
2625
+ problems += 1;
2626
+ }
2627
+ }
2628
+ }
2629
+ }
2630
+ reportStaleMcp(ctx, paths);
2631
+ if (problems > 0) {
2632
+ failLine(ctx, fix ? `\uACE0\uCE58\uC9C0 \uBABB\uD55C \uAC83\uC774 ${problems}\uAC1C \uB0A8\uC558\uC2B5\uB2C8\uB2E4.` : `\uACE0\uCE60 \uAC83\uC774 ${problems}\uAC1C \uC788\uC2B5\uB2C8\uB2E4. \uACE0\uCE58\uB824\uBA74 --check \uC5C6\uC774 doctor \uB97C \uC2E4\uD589\uD558\uC138\uC694.`);
2633
+ return 1;
2634
+ }
2635
+ okLine(ctx, "\uBAA8\uB450 \uC815\uC0C1\uC785\uB2C8\uB2E4.");
2636
+ return 0;
2637
+ }
2638
+
2639
+ // packages/cli/src/main.ts
2640
+ function helpText() {
2641
+ return [
2642
+ `nestedgarden ${CLI_VERSION} \u2014 \uC774 \uD3F4\uB354\uC758 Claude Code \uB97C \uD488\uC740\uC815\uC6D0 \uC5D0\uC774\uC804\uD2B8 \uC815\uC6D0\uC5D0 \uC787\uC2B5\uB2C8\uB2E4`,
2643
+ "",
2644
+ "\uC4F0\uB294 \uBC95",
2645
+ ` ${COMMANDS.connect} \uC774 \uD3F4\uB354\uB97C \uC5F0\uACB0 (\uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC2B9\uC778 \uD55C \uBC88)`,
2646
+ ` ${COMMANDS.doctor} \uC5F0\uACB0 \uC0C1\uD0DC\uB97C \uC810\uAC80\uD558\uACE0 \uACE0\uCE60 \uC218 \uC788\uB294 \uAC83\uC740 \uACE0\uCE68`,
2647
+ ` ${COMMANDS.disconnect} \uC774 \uD3F4\uB354\uC758 \uC5F0\uACB0\uC744 \uB04A\uC74C`,
2648
+ "",
2649
+ "connect",
2650
+ " --resume Claude Code \uC138\uC158 \uC548\uC5D0\uC11C \uC2DC\uC791\uD55C \uC5F0\uACB0\uC744, \uC2B9\uC778\uD55C \uB4A4 \uB9C8\uBB34\uB9AC",
2651
+ " --server <\uC8FC\uC18C> \uC571 \uC8FC\uC18C (\uAE30\uBCF8 https://www.nestedgarden.com)",
2652
+ " --allow-home \uD648 \uD3F4\uB354 \uC790\uCCB4\uB97C \uC5F0\uACB0 (\uD648\uC5D0\uC11C \uCF20 \uC138\uC158\uB9CC, \uD558\uC704 \uD3F4\uB354\uB294 \uBE7C\uACE0)",
2653
+ "doctor",
2654
+ " --check \uACE0\uCE58\uC9C0 \uC54A\uACE0 \uBCF4\uAE30\uB9CC",
2655
+ "disconnect",
2656
+ " --all \uC5F0\uACB0\uD55C \uBAA8\uB4E0 \uD3F4\uB354\uB97C \uB04A\uACE0 ~/.claude/settings.json \uC758 \uD154\uB808\uBA54\uD2B8\uB9AC \uC124\uC815\uB3C4 \uB418\uB3CC\uB9BC",
2657
+ "",
2658
+ " --version \uD310",
2659
+ " --help \uC774 \uB3C4\uC6C0\uB9D0",
2660
+ "",
2661
+ "\uBC14\uAFB8\uB294 \uACF3",
2662
+ " ~/.config/nestedgarden \uD0A4(keys/, \uAD8C\uD55C 600)\xB7\uC5F0\uACB0 \uBAA9\uB85D\xB7\uD5E4\uB354 \uB3C4\uC6B0\uBBF8",
2663
+ " ~/.claude/settings.json \uD154\uB808\uBA54\uD2B8\uB9AC env \uC640 otelHeadersHelper (\uBAA8\uB4E0 \uD3F4\uB354 \uACF5\uD1B5)",
2664
+ " ~/.claude.json \uADF8 \uD3F4\uB354\uC758 nestedgarden MCP (claude mcp \uBA85\uB839\uC73C\uB85C\uB9CC)",
2665
+ "\uD504\uB86C\uD504\uD2B8\xB7\uCF54\uB4DC \uB0B4\uC6A9\uC740 \uBCF4\uB0B4\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uD1A0\uD070 \uC218\xB7\uBE44\uC6A9\uACFC \uC791\uC5C5 \uBCF4\uACE0\uB9CC \uAC11\uB2C8\uB2E4."
2666
+ ].join("\n");
2667
+ }
2668
+ function parseArgs(argv) {
2669
+ const [command, ...rest] = argv;
2670
+ if (command === void 0) {
2671
+ return { kind: "usage", message: "\uBA85\uB839\uC744 \uC801\uC5B4 \uC8FC\uC138\uC694." };
2672
+ }
2673
+ if (command === "--help" || command === "-h" || command === "help") {
2674
+ return { kind: "help" };
2675
+ }
2676
+ if (command === "--version" || command === "version") {
2677
+ return { kind: "version" };
2678
+ }
2679
+ if (rest.includes("--help") || rest.includes("-h")) {
2680
+ return { kind: "help" };
2681
+ }
2682
+ switch (command) {
2683
+ case "connect": {
2684
+ let resume = false;
2685
+ let allowHome = false;
2686
+ let server = null;
2687
+ for (let i = 0; i < rest.length; i += 1) {
2688
+ const arg = rest[i];
2689
+ if (arg === "--resume") {
2690
+ resume = true;
2691
+ } else if (arg === "--allow-home") {
2692
+ allowHome = true;
2693
+ } else if (arg === "--server") {
2694
+ const value = rest[i + 1];
2695
+ if (value === void 0 || value.startsWith("--")) {
2696
+ return { kind: "usage", message: "--server \uB4A4\uC5D0 \uC8FC\uC18C\uB97C \uC801\uC5B4 \uC8FC\uC138\uC694." };
2697
+ }
2698
+ server = value;
2699
+ i += 1;
2700
+ } else if (arg.startsWith("--server=")) {
2701
+ server = arg.slice("--server=".length);
2702
+ if (server === "") {
2703
+ return { kind: "usage", message: "--server \uB4A4\uC5D0 \uC8FC\uC18C\uB97C \uC801\uC5B4 \uC8FC\uC138\uC694." };
2704
+ }
2705
+ } else {
2706
+ return { kind: "usage", message: `\uC54C \uC218 \uC5C6\uB294 \uC778\uC790: ${arg}` };
2707
+ }
2708
+ }
2709
+ return { kind: "connect", resume, server, allowHome };
2710
+ }
2711
+ case "doctor": {
2712
+ let check = false;
2713
+ for (const arg of rest) {
2714
+ if (arg === "--check") {
2715
+ check = true;
2716
+ } else {
2717
+ return { kind: "usage", message: `\uC54C \uC218 \uC5C6\uB294 \uC778\uC790: ${arg}` };
2718
+ }
2719
+ }
2720
+ return { kind: "doctor", check };
2721
+ }
2722
+ case "disconnect": {
2723
+ let all = false;
2724
+ for (const arg of rest) {
2725
+ if (arg === "--all") {
2726
+ all = true;
2727
+ } else {
2728
+ return { kind: "usage", message: `\uC54C \uC218 \uC5C6\uB294 \uC778\uC790: ${arg}` };
2729
+ }
2730
+ }
2731
+ return { kind: "disconnect", all };
2732
+ }
2733
+ default: {
2734
+ return { kind: "usage", message: `\uC54C \uC218 \uC5C6\uB294 \uBA85\uB839: ${command}` };
2735
+ }
2736
+ }
2737
+ }
2738
+ async function runCli(argv, ctx) {
2739
+ const parsed = parseArgs(argv);
2740
+ try {
2741
+ switch (parsed.kind) {
2742
+ case "help": {
2743
+ ctx.io.out(helpText());
2744
+ return 0;
2745
+ }
2746
+ case "version": {
2747
+ ctx.io.out(CLI_VERSION);
2748
+ return 0;
2749
+ }
2750
+ case "usage": {
2751
+ ctx.io.err(parsed.message);
2752
+ ctx.io.err("");
2753
+ ctx.io.err(helpText());
2754
+ return 2;
2755
+ }
2756
+ case "connect": {
2757
+ return await runConnect(ctx, { resume: parsed.resume, server: parsed.server, allowHome: parsed.allowHome });
2758
+ }
2759
+ case "doctor": {
2760
+ return await runDoctor(ctx, { check: parsed.check });
2761
+ }
2762
+ case "disconnect": {
2763
+ return await runDisconnect(ctx, { all: parsed.all });
2764
+ }
2765
+ default: {
2766
+ return 2;
2767
+ }
2768
+ }
2769
+ } catch (error) {
2770
+ failLine(ctx, `\uC608\uC0C1\uD558\uC9C0 \uBABB\uD55C \uC624\uB958: ${describeError(error)}`);
2771
+ return 1;
2772
+ }
2773
+ }
2774
+ function isDirectRun() {
2775
+ const entry = process.argv[1];
2776
+ if (!entry) {
2777
+ return false;
2778
+ }
2779
+ try {
2780
+ return fs8.realpathSync(entry) === fs8.realpathSync(fileURLToPath(import.meta.url));
2781
+ } catch {
2782
+ return false;
2783
+ }
2784
+ }
2785
+ if (isDirectRun()) {
2786
+ runCli(process.argv.slice(2), createProcessContext()).then(
2787
+ (code) => {
2788
+ process.exitCode = code;
2789
+ setTimeout(() => {
2790
+ process.exit(code);
2791
+ }, 1e3).unref();
2792
+ },
2793
+ (error) => {
2794
+ process.stderr.write(`\u2717 ${describeError(error)}
2795
+ `);
2796
+ process.exitCode = 1;
2797
+ }
2798
+ );
2799
+ }
2800
+ export {
2801
+ helpText,
2802
+ parseArgs,
2803
+ runCli
2804
+ };