@rulemetric/cli 0.6.9 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base-command.js +4 -3
- package/dist/{chunk-SZ7VDCD6.js → chunk-2HK7RGZB.js} +22 -3
- package/dist/chunk-2HK7RGZB.js.map +7 -0
- package/dist/{chunk-RUCSRN7F.js → chunk-2ORJWTNZ.js} +2 -2
- package/dist/{chunk-SLL3OBKN.js → chunk-37LN5O7M.js} +2 -2
- package/dist/{chunk-RCMXTLQF.js → chunk-3LKVS6W5.js} +5 -5
- package/dist/{chunk-XN23W5HL.js → chunk-4KRMZLQV.js} +91 -7
- package/dist/chunk-4KRMZLQV.js.map +7 -0
- package/dist/{chunk-DAJNO4OI.js → chunk-4LYCDS2N.js} +28 -16
- package/dist/chunk-4LYCDS2N.js.map +7 -0
- package/dist/{chunk-UPXIO7CG.js → chunk-4XAWK6S2.js} +8 -8
- package/dist/{chunk-N5A2IQAK.js → chunk-4YAP7RT7.js} +5 -5
- package/dist/{chunk-QD6X4L4L.js → chunk-5BAOGNUH.js} +4 -4
- package/dist/chunk-5EDMGK3W.js +39 -0
- package/dist/chunk-5EDMGK3W.js.map +7 -0
- package/dist/{chunk-5ADHO5QF.js → chunk-6NBS5XFS.js} +6 -6
- package/dist/chunk-7LVVKQMZ.js +98 -0
- package/dist/chunk-7LVVKQMZ.js.map +7 -0
- package/dist/{chunk-PXVQLD7S.js → chunk-7NNFYWKK.js} +48 -1
- package/dist/chunk-7NNFYWKK.js.map +7 -0
- package/dist/{chunk-BBLTN35F.js → chunk-7UDETV3P.js} +49 -20
- package/dist/chunk-7UDETV3P.js.map +7 -0
- package/dist/{chunk-DTFXCHHI.js → chunk-DNKSVWMD.js} +4 -4
- package/dist/{chunk-6EMZI4Y3.js → chunk-EI5BHWXA.js} +437 -401
- package/dist/chunk-EI5BHWXA.js.map +7 -0
- package/dist/{chunk-HNZLEEG2.js → chunk-EJ3YAFDP.js} +4 -4
- package/dist/{chunk-HNZLEEG2.js.map → chunk-EJ3YAFDP.js.map} +2 -2
- package/dist/{chunk-YSEQWCN4.js → chunk-EYPAAGN5.js} +2 -2
- package/dist/{chunk-JEJ3J5J6.js → chunk-GIUBARWS.js} +2 -2
- package/dist/chunk-GQNJO2P2.js +102 -0
- package/dist/chunk-GQNJO2P2.js.map +7 -0
- package/dist/{chunk-CNMWYYSV.js → chunk-HZK43UCF.js} +6 -6
- package/dist/chunk-ILYDELUE.js +46 -0
- package/dist/chunk-ILYDELUE.js.map +7 -0
- package/dist/chunk-J6QFW4LD.js +55 -0
- package/dist/chunk-J6QFW4LD.js.map +7 -0
- package/dist/{chunk-OTOWLUOJ.js → chunk-JULOLTZS.js} +2 -2
- package/dist/{chunk-DR5WLIOU.js → chunk-KJKBDQ4D.js} +2 -2
- package/dist/{chunk-AHDRN6NE.js → chunk-OO7JDFS4.js} +5 -5
- package/dist/{chunk-N2X35ITW.js → chunk-OQBBVTDG.js} +11 -1
- package/dist/{chunk-N2X35ITW.js.map → chunk-OQBBVTDG.js.map} +2 -2
- package/dist/{chunk-3QH73QOQ.js → chunk-PED7L5GX.js} +2 -2
- package/dist/{chunk-VBGUNFKY.js → chunk-PMI56ED5.js} +5 -5
- package/dist/{chunk-XNNOXGP6.js → chunk-POFTPB33.js} +38 -19
- package/dist/chunk-POFTPB33.js.map +7 -0
- package/dist/{chunk-W4MZXKZ2.js → chunk-UKMLICWS.js} +2 -2
- package/dist/{chunk-3POYC5NA.js → chunk-XK42ZBDE.js} +3 -3
- package/dist/{chunk-ZSGKRCKD.js → chunk-XUV6DDBF.js} +2 -2
- package/dist/{chunk-LAKZUE35.js → chunk-Y3WD5CSW.js} +2 -2
- package/dist/{chunk-3QVMIJUL.js → chunk-YOBA3NAM.js} +5 -5
- package/dist/{chunk-ZRLYHBPN.js → chunk-ZUJBM6HE.js} +20 -2
- package/dist/chunk-ZUJBM6HE.js.map +7 -0
- package/dist/commands/antigravity/backfill.js +5 -4
- package/dist/commands/antigravity/backfill.js.map +1 -1
- package/dist/commands/auth/create-key.js +4 -3
- package/dist/commands/auth/create-key.js.map +1 -1
- package/dist/commands/auth/login.js +13 -9
- package/dist/commands/auth/login.js.map +2 -2
- package/dist/commands/auth/logout.js +4 -3
- package/dist/commands/auth/logout.js.map +1 -1
- package/dist/commands/auth/revoke-key.js +4 -3
- package/dist/commands/auth/revoke-key.js.map +1 -1
- package/dist/commands/auth/signup.js +13 -9
- package/dist/commands/auth/signup.js.map +2 -2
- package/dist/commands/auth/status.js +4 -3
- package/dist/commands/auth/status.js.map +1 -1
- package/dist/commands/catalog/index.js +4 -3
- package/dist/commands/catalog/index.js.map +1 -1
- package/dist/commands/catalog/recommend.js +4 -3
- package/dist/commands/catalog/recommend.js.map +1 -1
- package/dist/commands/convert.js +4 -3
- package/dist/commands/convert.js.map +1 -1
- package/dist/commands/converters.js +4 -3
- package/dist/commands/converters.js.map +1 -1
- package/dist/commands/crons/list.js +4 -3
- package/dist/commands/crons/list.js.map +1 -1
- package/dist/commands/crons/run.js +4 -3
- package/dist/commands/crons/run.js.map +1 -1
- package/dist/commands/dashboard.js +4 -3
- package/dist/commands/dashboard.js.map +1 -1
- package/dist/commands/diagnostics.js +117 -0
- package/dist/commands/diagnostics.js.map +7 -0
- package/dist/commands/eval-targets/create.js +4 -3
- package/dist/commands/eval-targets/create.js.map +1 -1
- package/dist/commands/eval-targets/list.js +4 -3
- package/dist/commands/eval-targets/list.js.map +1 -1
- package/dist/commands/evals/agent.js +44 -23
- package/dist/commands/evals/agent.js.map +2 -2
- package/dist/commands/evals/benchmark.js +5 -4
- package/dist/commands/evals/benchmark.js.map +1 -1
- package/dist/commands/evals/compare.js +4 -3
- package/dist/commands/evals/compare.js.map +1 -1
- package/dist/commands/evals/create.js +4 -3
- package/dist/commands/evals/create.js.map +1 -1
- package/dist/commands/evals/optimize-description.js +4 -3
- package/dist/commands/evals/optimize-description.js.map +1 -1
- package/dist/commands/evals/optimize.js +4 -3
- package/dist/commands/evals/optimize.js.map +1 -1
- package/dist/commands/evals/run.js +4 -3
- package/dist/commands/evals/run.js.map +1 -1
- package/dist/commands/gateway/ensure.js +58 -5
- package/dist/commands/gateway/ensure.js.map +2 -2
- package/dist/commands/hooks/install.js +76 -23
- package/dist/commands/hooks/install.js.map +2 -2
- package/dist/commands/hooks/run.js +4 -3
- package/dist/commands/hooks/run.js.map +1 -1
- package/dist/commands/hooks/uninstall.js +31 -40
- package/dist/commands/hooks/uninstall.js.map +2 -2
- package/dist/commands/import.js +4 -3
- package/dist/commands/import.js.map +1 -1
- package/dist/commands/instructions/create.js +4 -3
- package/dist/commands/instructions/create.js.map +1 -1
- package/dist/commands/instructions/delete.js +4 -3
- package/dist/commands/instructions/delete.js.map +1 -1
- package/dist/commands/instructions/fork.js +4 -3
- package/dist/commands/instructions/fork.js.map +1 -1
- package/dist/commands/instructions/get.js +4 -3
- package/dist/commands/instructions/get.js.map +1 -1
- package/dist/commands/instructions/list.js +4 -3
- package/dist/commands/instructions/list.js.map +1 -1
- package/dist/commands/instructions/promote.js +4 -3
- package/dist/commands/instructions/promote.js.map +1 -1
- package/dist/commands/instructions/pull.js +4 -3
- package/dist/commands/instructions/pull.js.map +1 -1
- package/dist/commands/instructions/upstream.js +4 -3
- package/dist/commands/instructions/upstream.js.map +1 -1
- package/dist/commands/instructions/versions.js +4 -3
- package/dist/commands/instructions/versions.js.map +1 -1
- package/dist/commands/launcher.js +4 -3
- package/dist/commands/launcher.js.map +1 -1
- package/dist/commands/org/current.js +4 -3
- package/dist/commands/org/current.js.map +1 -1
- package/dist/commands/org/list.js +4 -3
- package/dist/commands/org/list.js.map +1 -1
- package/dist/commands/org/switch.js +4 -3
- package/dist/commands/org/switch.js.map +1 -1
- package/dist/commands/packs/add-instruction.js +4 -3
- package/dist/commands/packs/add-instruction.js.map +1 -1
- package/dist/commands/packs/apply.js +4 -3
- package/dist/commands/packs/apply.js.map +1 -1
- package/dist/commands/packs/create.js +4 -3
- package/dist/commands/packs/create.js.map +1 -1
- package/dist/commands/packs/fork.js +4 -3
- package/dist/commands/packs/fork.js.map +1 -1
- package/dist/commands/packs/get.js +4 -3
- package/dist/commands/packs/get.js.map +1 -1
- package/dist/commands/packs/list.js +4 -3
- package/dist/commands/packs/list.js.map +1 -1
- package/dist/commands/packs/remove-instruction.js +4 -3
- package/dist/commands/packs/remove-instruction.js.map +1 -1
- package/dist/commands/proxy/env.js +7 -4
- package/dist/commands/proxy/env.js.map +1 -1
- package/dist/commands/proxy/logs.js +4 -3
- package/dist/commands/proxy/logs.js.map +1 -1
- package/dist/commands/proxy/restart.js +4 -3
- package/dist/commands/proxy/restart.js.map +1 -1
- package/dist/commands/proxy/setup.js +20 -14
- package/dist/commands/proxy/setup.js.map +2 -2
- package/dist/commands/proxy/start.js +18 -14
- package/dist/commands/proxy/start.js.map +2 -2
- package/dist/commands/proxy/status.js +16 -13
- package/dist/commands/proxy/status.js.map +2 -2
- package/dist/commands/proxy/stop.js +21 -12
- package/dist/commands/proxy/stop.js.map +2 -2
- package/dist/commands/research/backfill.js +5 -4
- package/dist/commands/research/backfill.js.map +1 -1
- package/dist/commands/research/tail-transcript.js +5 -4
- package/dist/commands/research/tail-transcript.js.map +1 -1
- package/dist/commands/service/install.js +6 -6
- package/dist/commands/service/status.js +4 -3
- package/dist/commands/service/status.js.map +1 -1
- package/dist/commands/service/uninstall.js +4 -3
- package/dist/commands/service/uninstall.js.map +1 -1
- package/dist/commands/sessions/analyze.js +4 -3
- package/dist/commands/sessions/analyze.js.map +1 -1
- package/dist/commands/sessions/end.js +4 -3
- package/dist/commands/sessions/end.js.map +1 -1
- package/dist/commands/sessions/import.js +4 -3
- package/dist/commands/sessions/import.js.map +1 -1
- package/dist/commands/sessions/list.js +4 -3
- package/dist/commands/sessions/list.js.map +1 -1
- package/dist/commands/sessions/start.js +4 -3
- package/dist/commands/sessions/start.js.map +1 -1
- package/dist/commands/setup.js +10 -6
- package/dist/commands/setup.js.map +1 -1
- package/dist/commands/skills/export-approved.js +4 -3
- package/dist/commands/skills/export-approved.js.map +1 -1
- package/dist/commands/skills/install.js +4 -3
- package/dist/commands/skills/install.js.map +1 -1
- package/dist/commands/skills/list.js +4 -3
- package/dist/commands/skills/list.js.map +1 -1
- package/dist/commands/skills/publish.js +4 -3
- package/dist/commands/skills/publish.js.map +1 -1
- package/dist/commands/skills/search.js +4 -3
- package/dist/commands/skills/search.js.map +1 -1
- package/dist/commands/skills/update.js +4 -3
- package/dist/commands/skills/update.js.map +1 -1
- package/dist/commands/suggestions/accept.js +4 -3
- package/dist/commands/suggestions/accept.js.map +1 -1
- package/dist/commands/suggestions/dismiss.js +4 -3
- package/dist/commands/suggestions/dismiss.js.map +1 -1
- package/dist/commands/suggestions/list.js +4 -3
- package/dist/commands/suggestions/list.js.map +1 -1
- package/dist/commands/suggestions/refresh.js +4 -3
- package/dist/commands/suggestions/refresh.js.map +1 -1
- package/dist/dashboard/Dashboard.js +16 -16
- package/dist/dashboard/data.js +2 -2
- package/dist/dashboard/launcher/ActiveJobsList.js +2 -2
- package/dist/dashboard/launcher/LauncherOverlay.js +7 -7
- package/dist/dashboard/launcher/NewLaunchForm.js +2 -2
- package/dist/dashboard/launcher/api.js +2 -2
- package/dist/dashboard/launcher/useLaunchJobs.js +3 -3
- package/dist/lib/active-org-refresh.js +2 -2
- package/dist/lib/agent-loop.js +20 -18
- package/dist/lib/antigravity-transcript.js +2 -2
- package/dist/lib/api-client.js +1 -1
- package/dist/lib/diagnostics.js +12 -0
- package/dist/lib/diagnostics.js.map +7 -0
- package/dist/lib/ensure-api-key.js +3 -3
- package/dist/lib/eval-benchmark.js +2 -2
- package/dist/lib/eval-conversation-handler.js +2 -2
- package/dist/lib/gateway-entry.js +39 -1
- package/dist/lib/gateway-entry.js.map +2 -2
- package/dist/lib/gateway-identity.js +16 -0
- package/dist/lib/gateway-identity.js.map +7 -0
- package/dist/lib/gateway-lifecycle.js +9 -3
- package/dist/lib/gateway.js +3 -1
- package/dist/lib/handlers/cron-suggest-instructions.js +3 -3
- package/dist/lib/handlers/process-announcement.js +3 -3
- package/dist/lib/handlers/process-changelog.js +3 -3
- package/dist/lib/handlers/process-conversation.js +3 -3
- package/dist/lib/handlers/process-eval.js +3 -3
- package/dist/lib/handlers/process-insights.js +3 -3
- package/dist/lib/handlers/process-launch.js +2 -2
- package/dist/lib/handlers/process-run-cleanup.js +2 -2
- package/dist/lib/handlers/process-session-goal.js +2 -2
- package/dist/lib/hooks-config.js +14 -1
- package/dist/lib/manual-tasks.js +6 -6
- package/dist/lib/pid-identity.js +14 -0
- package/dist/lib/pid-identity.js.map +7 -0
- package/dist/lib/proxy-respawn.js +12 -0
- package/dist/lib/proxy-respawn.js.map +7 -0
- package/dist/lib/research-client.js +2 -2
- package/dist/lib/setup-steps.js +7 -4
- package/dist/lib/statusline-shim.js +3 -1
- package/dist/lib/telemetry.js +4 -2
- package/dist/lib/terminal-target-heartbeat.js +2 -2
- package/oclif.manifest.json +34 -1
- package/package.json +6 -6
- package/dist/chunk-6EMZI4Y3.js.map +0 -7
- package/dist/chunk-BBLTN35F.js.map +0 -7
- package/dist/chunk-DAJNO4OI.js.map +0 -7
- package/dist/chunk-PXVQLD7S.js.map +0 -7
- package/dist/chunk-SZ7VDCD6.js.map +0 -7
- package/dist/chunk-TX2HKJLA.js +0 -55
- package/dist/chunk-TX2HKJLA.js.map +0 -7
- package/dist/chunk-XN23W5HL.js.map +0 -7
- package/dist/chunk-XNNOXGP6.js.map +0 -7
- package/dist/chunk-ZRLYHBPN.js.map +0 -7
- /package/dist/{chunk-RUCSRN7F.js.map → chunk-2ORJWTNZ.js.map} +0 -0
- /package/dist/{chunk-SLL3OBKN.js.map → chunk-37LN5O7M.js.map} +0 -0
- /package/dist/{chunk-RCMXTLQF.js.map → chunk-3LKVS6W5.js.map} +0 -0
- /package/dist/{chunk-UPXIO7CG.js.map → chunk-4XAWK6S2.js.map} +0 -0
- /package/dist/{chunk-N5A2IQAK.js.map → chunk-4YAP7RT7.js.map} +0 -0
- /package/dist/{chunk-QD6X4L4L.js.map → chunk-5BAOGNUH.js.map} +0 -0
- /package/dist/{chunk-5ADHO5QF.js.map → chunk-6NBS5XFS.js.map} +0 -0
- /package/dist/{chunk-DTFXCHHI.js.map → chunk-DNKSVWMD.js.map} +0 -0
- /package/dist/{chunk-YSEQWCN4.js.map → chunk-EYPAAGN5.js.map} +0 -0
- /package/dist/{chunk-JEJ3J5J6.js.map → chunk-GIUBARWS.js.map} +0 -0
- /package/dist/{chunk-CNMWYYSV.js.map → chunk-HZK43UCF.js.map} +0 -0
- /package/dist/{chunk-OTOWLUOJ.js.map → chunk-JULOLTZS.js.map} +0 -0
- /package/dist/{chunk-DR5WLIOU.js.map → chunk-KJKBDQ4D.js.map} +0 -0
- /package/dist/{chunk-AHDRN6NE.js.map → chunk-OO7JDFS4.js.map} +0 -0
- /package/dist/{chunk-3QH73QOQ.js.map → chunk-PED7L5GX.js.map} +0 -0
- /package/dist/{chunk-VBGUNFKY.js.map → chunk-PMI56ED5.js.map} +0 -0
- /package/dist/{chunk-W4MZXKZ2.js.map → chunk-UKMLICWS.js.map} +0 -0
- /package/dist/{chunk-3POYC5NA.js.map → chunk-XK42ZBDE.js.map} +0 -0
- /package/dist/{chunk-ZSGKRCKD.js.map → chunk-XUV6DDBF.js.map} +0 -0
- /package/dist/{chunk-LAKZUE35.js.map → chunk-Y3WD5CSW.js.map} +0 -0
- /package/dist/{chunk-3QVMIJUL.js.map → chunk-YOBA3NAM.js.map} +0 -0
package/dist/base-command.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
BaseCommand
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2HK7RGZB.js";
|
|
4
4
|
import "./chunk-R56PH7YE.js";
|
|
5
|
-
import "./chunk-
|
|
5
|
+
import "./chunk-GQNJO2P2.js";
|
|
6
|
+
import "./chunk-37LN5O7M.js";
|
|
6
7
|
import "./chunk-EKJ2CABV.js";
|
|
7
|
-
import "./chunk-
|
|
8
|
+
import "./chunk-ZUJBM6HE.js";
|
|
8
9
|
import "./chunk-W2YERO7E.js";
|
|
9
10
|
import "./chunk-NSBPE2FW.js";
|
|
10
11
|
export {
|
|
@@ -2,18 +2,29 @@ import {
|
|
|
2
2
|
getUpgradeBanner,
|
|
3
3
|
refreshVersionCacheInBackground
|
|
4
4
|
} from "./chunk-R56PH7YE.js";
|
|
5
|
+
import {
|
|
6
|
+
emitErrorBeacon
|
|
7
|
+
} from "./chunk-GQNJO2P2.js";
|
|
5
8
|
import {
|
|
6
9
|
maybeRefreshActiveOrg
|
|
7
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-37LN5O7M.js";
|
|
8
11
|
import {
|
|
9
12
|
ApiError
|
|
10
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-ZUJBM6HE.js";
|
|
11
14
|
import {
|
|
12
15
|
isAuthenticated
|
|
13
16
|
} from "./chunk-W2YERO7E.js";
|
|
14
17
|
|
|
15
18
|
// src/base-command.ts
|
|
16
19
|
import { Command, Flags } from "@oclif/core";
|
|
20
|
+
function isAvailabilityError(err) {
|
|
21
|
+
if (err instanceof ApiError) {
|
|
22
|
+
return err.statusCode >= 500 || err.statusCode === 408 || err.statusCode === 0;
|
|
23
|
+
}
|
|
24
|
+
return /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|bad gateway|timed out/i.test(
|
|
25
|
+
err.message ?? ""
|
|
26
|
+
);
|
|
27
|
+
}
|
|
17
28
|
var BaseCommand = class extends Command {
|
|
18
29
|
static baseFlags = {
|
|
19
30
|
"api-url": Flags.string({
|
|
@@ -44,6 +55,14 @@ ${banner}
|
|
|
44
55
|
void maybeRefreshActiveOrg();
|
|
45
56
|
}
|
|
46
57
|
async catch(err) {
|
|
58
|
+
if (isAvailabilityError(err)) {
|
|
59
|
+
await emitErrorBeacon({
|
|
60
|
+
command: this.id,
|
|
61
|
+
statusCode: err instanceof ApiError ? err.statusCode : void 0,
|
|
62
|
+
message: err.message,
|
|
63
|
+
cliVersion: this.config.version
|
|
64
|
+
});
|
|
65
|
+
}
|
|
47
66
|
if (err instanceof ApiError) {
|
|
48
67
|
if (err.statusCode === 401) {
|
|
49
68
|
this.error("Session expired. Run `rulemetric auth login` to re-authenticate.");
|
|
@@ -60,4 +79,4 @@ ${banner}
|
|
|
60
79
|
export {
|
|
61
80
|
BaseCommand
|
|
62
81
|
};
|
|
63
|
-
//# sourceMappingURL=chunk-
|
|
82
|
+
//# sourceMappingURL=chunk-2HK7RGZB.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/base-command.ts"],
|
|
4
|
+
"sourcesContent": ["import { Command, Flags } from '@oclif/core';\nimport { isAuthenticated } from './lib/auth.js';\nimport { ApiError } from './lib/api-client.js';\nimport { maybeRefreshActiveOrg } from './lib/active-org-refresh.js';\nimport { getUpgradeBanner, refreshVersionCacheInBackground } from './lib/version-check.js';\nimport { emitErrorBeacon } from './lib/telemetry.js';\n\n/**\n * Is this error an API AVAILABILITY failure (server/edge/proxy unreachable), as\n * opposed to a normal 4xx business error (401/404/409)? These are the failures\n * the unauthenticated error beacon exists to surface \u2014 a 502 from a broken local\n * gateway, a 5xx from the edge, a client timeout (408, added in api-client), or\n * a raw connection failure \u2014 precisely the class that authenticated telemetry\n * can never report because it happens before/instead of auth.\n */\nfunction isAvailabilityError(err: Error): boolean {\n if (err instanceof ApiError) {\n return err.statusCode >= 500 || err.statusCode === 408 || err.statusCode === 0;\n }\n return /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|bad gateway|timed out/i.test(\n err.message ?? '',\n );\n}\n\nexport abstract class BaseCommand extends Command {\n static override baseFlags = {\n 'api-url': Flags.string({\n description: 'Override API base URL',\n env: 'RULEMETRIC_API_URL',\n hidden: true,\n }),\n };\n\n protected override async init(): Promise<void> {\n await super.init();\n const { flags } = await this.parse(this.constructor as typeof BaseCommand);\n if (flags['api-url']) {\n process.env.RULEMETRIC_API_URL = flags['api-url'];\n }\n // Print the upgrade banner from the cache (populated by the previous\n // command). To stderr so it doesn't pollute scriptable stdout. Then\n // kick off a background refresh for the *next* invocation. Suppressed\n // on commands meant to be machine-readable (`hooks run`, etc.) since\n // a banner there would corrupt JSON output piped to other tools.\n const banner = getUpgradeBanner(this.config.version);\n if (banner && !this.argv.includes('--quiet') && !process.env.RULEMETRIC_QUIET) {\n process.stderr.write(`\\n${banner}\\n\\n`);\n }\n refreshVersionCacheInBackground();\n }\n\n protected requireAuth(): void {\n if (!isAuthenticated()) {\n this.error('Not logged in. Run `rulemetric auth login` to authenticate.');\n }\n // Fire-and-forget refresh of the local active-org cache. Doesn't block\n // the command \u2014 its only side effect is rewriting the cache file.\n void maybeRefreshActiveOrg();\n }\n\n protected override async catch(err: Error & { exitCode?: number }): Promise<void> {\n // Surface availability failures (5xx / 502 / timeout / connection refused) to\n // the unauthenticated, proxy-bypassing error beacon FIRST \u2014 this is the only\n // path that makes a pre-auth / broken-gateway onboarding failure visible\n // server-side. Best-effort + bounded internally; awaited so it lands before\n // this.error() exits the process.\n if (isAvailabilityError(err)) {\n await emitErrorBeacon({\n command: this.id,\n statusCode: err instanceof ApiError ? err.statusCode : undefined,\n message: err.message,\n cliVersion: this.config.version,\n });\n }\n\n if (err instanceof ApiError) {\n if (err.statusCode === 401) {\n this.error('Session expired. Run `rulemetric auth login` to re-authenticate.');\n }\n\n this.error(err.message);\n }\n\n if (err.message?.includes('fetch failed') || err.message?.includes('ECONNREFUSED')) {\n this.error('Could not connect to the API server. Is it running?');\n }\n\n throw err;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,aAAa;AAe/B,SAAS,oBAAoB,KAAqB;AAChD,MAAI,eAAe,UAAU;AAC3B,WAAO,IAAI,cAAc,OAAO,IAAI,eAAe,OAAO,IAAI,eAAe;AAAA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AAClF,WAAK,MAAM,qDAAqD;AAAA,IAClE;AAEA,UAAM;AAAA,EACR;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ApiError,
|
|
3
3
|
api
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-ZUJBM6HE.js";
|
|
5
5
|
|
|
6
6
|
// src/lib/antigravity-transcript.ts
|
|
7
7
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmdirSync, writeFileSync } from "node:fs";
|
|
@@ -304,4 +304,4 @@ export {
|
|
|
304
304
|
tailAntigravityTranscript,
|
|
305
305
|
stateApi
|
|
306
306
|
};
|
|
307
|
-
//# sourceMappingURL=chunk-
|
|
307
|
+
//# sourceMappingURL=chunk-2ORJWTNZ.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-EKJ2CABV.js";
|
|
7
7
|
import {
|
|
8
8
|
apiGet
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-ZUJBM6HE.js";
|
|
10
10
|
|
|
11
11
|
// src/lib/active-org-refresh.ts
|
|
12
12
|
var attempted = false;
|
|
@@ -56,4 +56,4 @@ export {
|
|
|
56
56
|
bootstrapActiveOrg,
|
|
57
57
|
_resetRefreshAttempt
|
|
58
58
|
};
|
|
59
|
-
//# sourceMappingURL=chunk-
|
|
59
|
+
//# sourceMappingURL=chunk-37LN5O7M.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
PermanentJobError
|
|
3
3
|
} from "./chunk-DGHWRQXL.js";
|
|
4
|
-
import {
|
|
5
|
-
judgeEvalQuality
|
|
6
|
-
} from "./chunk-J7N3DLH6.js";
|
|
7
4
|
import {
|
|
8
5
|
createEvalWorktree
|
|
9
6
|
} from "./chunk-52WIYRZH.js";
|
|
7
|
+
import {
|
|
8
|
+
judgeEvalQuality
|
|
9
|
+
} from "./chunk-J7N3DLH6.js";
|
|
10
10
|
import {
|
|
11
11
|
gradeEvalOutput
|
|
12
12
|
} from "./chunk-YNIH3KMU.js";
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
apiGet,
|
|
18
18
|
apiPatch,
|
|
19
19
|
apiPost
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-ZUJBM6HE.js";
|
|
21
21
|
|
|
22
22
|
// src/lib/handlers/process-eval.ts
|
|
23
23
|
async function processEval(payload, helpers) {
|
|
@@ -188,4 +188,4 @@ function buildSummary(results) {
|
|
|
188
188
|
export {
|
|
189
189
|
processEval
|
|
190
190
|
};
|
|
191
|
-
//# sourceMappingURL=chunk-
|
|
191
|
+
//# sourceMappingURL=chunk-3LKVS6W5.js.map
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
removeStatuslineShimAnyHome
|
|
3
|
+
} from "./chunk-OQBBVTDG.js";
|
|
4
|
+
|
|
1
5
|
// src/lib/hooks-config.ts
|
|
2
6
|
import { execSync } from "node:child_process";
|
|
3
7
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, copyFileSync } from "node:fs";
|
|
@@ -150,6 +154,83 @@ function removeClaudeCodeHooks(settings) {
|
|
|
150
154
|
if (Object.keys(hooks).length === 0) delete settings.hooks;
|
|
151
155
|
return removed > 0;
|
|
152
156
|
}
|
|
157
|
+
var RULEMETRIC_NO_PROXY = "localhost,127.0.0.1,*.supabase.co,*.supabase.in";
|
|
158
|
+
function claudeSettingsInstallPath(configDir, isGlobal) {
|
|
159
|
+
return join(configDir, isGlobal ? "settings.json" : "settings.local.json");
|
|
160
|
+
}
|
|
161
|
+
function removeRulemetricProxyEnv(settings, gatewayPort) {
|
|
162
|
+
const env = settings.env;
|
|
163
|
+
if (!env || typeof env !== "object") return false;
|
|
164
|
+
let removed = false;
|
|
165
|
+
const proxy = env.HTTPS_PROXY;
|
|
166
|
+
if (proxy === `http://localhost:${gatewayPort}` || proxy === `http://127.0.0.1:${gatewayPort}`) {
|
|
167
|
+
delete env.HTTPS_PROXY;
|
|
168
|
+
removed = true;
|
|
169
|
+
}
|
|
170
|
+
if (env.NO_PROXY === RULEMETRIC_NO_PROXY) {
|
|
171
|
+
delete env.NO_PROXY;
|
|
172
|
+
removed = true;
|
|
173
|
+
}
|
|
174
|
+
const ca = env.NODE_EXTRA_CA_CERTS;
|
|
175
|
+
if (typeof ca === "string" && ca.includes(".mitmproxy") && ca.endsWith("mitmproxy-ca-cert.pem")) {
|
|
176
|
+
delete env.NODE_EXTRA_CA_CERTS;
|
|
177
|
+
removed = true;
|
|
178
|
+
}
|
|
179
|
+
if (removed && Object.keys(env).length === 0) delete settings.env;
|
|
180
|
+
return removed;
|
|
181
|
+
}
|
|
182
|
+
function removeRulemetricMachineState(settings, gatewayPort) {
|
|
183
|
+
const removedHooks = removeClaudeCodeHooks(settings);
|
|
184
|
+
const removedProxyEnv = removeRulemetricProxyEnv(settings, gatewayPort);
|
|
185
|
+
const removedStatusline = removeStatuslineShimAnyHome(settings);
|
|
186
|
+
return {
|
|
187
|
+
removedHooks,
|
|
188
|
+
removedProxyEnv,
|
|
189
|
+
removedStatusline,
|
|
190
|
+
removed: removedHooks || removedProxyEnv || removedStatusline
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function migrateSharedClaudeSettings(sharedPath, gatewayPort) {
|
|
194
|
+
const none = {
|
|
195
|
+
migrated: false,
|
|
196
|
+
backupPath: null,
|
|
197
|
+
removedHooks: false,
|
|
198
|
+
removedProxyEnv: false,
|
|
199
|
+
removedStatusline: false,
|
|
200
|
+
removed: false
|
|
201
|
+
};
|
|
202
|
+
if (!existsSync(sharedPath)) return none;
|
|
203
|
+
let settings;
|
|
204
|
+
try {
|
|
205
|
+
settings = JSON.parse(readFileSync(sharedPath, "utf-8"));
|
|
206
|
+
} catch {
|
|
207
|
+
return none;
|
|
208
|
+
}
|
|
209
|
+
const removal = removeRulemetricMachineState(settings, gatewayPort);
|
|
210
|
+
if (!removal.removed) return none;
|
|
211
|
+
const { backupPath } = writeClaudeSettingsWithBackup(sharedPath, settings);
|
|
212
|
+
return { ...removal, migrated: true, backupPath };
|
|
213
|
+
}
|
|
214
|
+
function cleanClaudeSettingsFiles(claudeDir, gatewayPort) {
|
|
215
|
+
const results = [];
|
|
216
|
+
for (const fileName of ["settings.json", "settings.local.json"]) {
|
|
217
|
+
const configPath = join(claudeDir, fileName);
|
|
218
|
+
if (!existsSync(configPath)) continue;
|
|
219
|
+
const { settings, recoveredBackup } = readClaudeSettings(configPath);
|
|
220
|
+
const removal = removeRulemetricMachineState(settings, gatewayPort);
|
|
221
|
+
if (removal.removed) {
|
|
222
|
+
writeClaudeSettingsWithBackup(configPath, settings);
|
|
223
|
+
}
|
|
224
|
+
results.push({
|
|
225
|
+
...removal,
|
|
226
|
+
configPath,
|
|
227
|
+
fileName,
|
|
228
|
+
recoveredBackup,
|
|
229
|
+
changed: removal.removed
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
return results;
|
|
233
|
+
}
|
|
153
234
|
function writeCursorHooksToDir(cursorDir, binDir) {
|
|
154
235
|
if (!existsSync(cursorDir)) {
|
|
155
236
|
return null;
|
|
@@ -160,14 +241,11 @@ function writeCursorHooksToDir(cursorDir, binDir) {
|
|
|
160
241
|
if (parsed === null) return null;
|
|
161
242
|
const existing = parsed;
|
|
162
243
|
const merged = { ...existing.hooks ?? {} };
|
|
244
|
+
const isRulemetricHook = (h) => typeof h === "object" && h !== null && "command" in h && typeof h.command === "string" && h.command.includes("rulemetric");
|
|
163
245
|
for (const [event, hooks] of Object.entries(generated.hooks)) {
|
|
164
246
|
const current = merged[event] ?? [];
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
);
|
|
168
|
-
if (!hasRulemetric) {
|
|
169
|
-
merged[event] = [...current, ...hooks];
|
|
170
|
-
}
|
|
247
|
+
const siblings = current.filter((h) => !isRulemetricHook(h));
|
|
248
|
+
merged[event] = [...siblings, ...hooks];
|
|
171
249
|
}
|
|
172
250
|
const result = {
|
|
173
251
|
version: existing.version ?? generated.version,
|
|
@@ -514,6 +592,12 @@ export {
|
|
|
514
592
|
mergeClaudeCodeHooks,
|
|
515
593
|
hasRulemetricClaudeHooks,
|
|
516
594
|
removeClaudeCodeHooks,
|
|
595
|
+
RULEMETRIC_NO_PROXY,
|
|
596
|
+
claudeSettingsInstallPath,
|
|
597
|
+
removeRulemetricProxyEnv,
|
|
598
|
+
removeRulemetricMachineState,
|
|
599
|
+
migrateSharedClaudeSettings,
|
|
600
|
+
cleanClaudeSettingsFiles,
|
|
517
601
|
writeCursorHooks,
|
|
518
602
|
writeCursorUserHooks,
|
|
519
603
|
writeCopilotHooks,
|
|
@@ -535,4 +619,4 @@ export {
|
|
|
535
619
|
removeAntigravityHooks,
|
|
536
620
|
removeAntigravityUserHooks
|
|
537
621
|
};
|
|
538
|
-
//# sourceMappingURL=chunk-
|
|
622
|
+
//# sourceMappingURL=chunk-4KRMZLQV.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/hooks-config.ts"],
|
|
4
|
+
"sourcesContent": ["import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, copyFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, dirname } from 'node:path';\nimport { removeStatuslineShimAnyHome } from './statusline-shim.js';\n\nexport type DetectedTool = 'claude_code' | 'cursor' | 'copilot_agent' | 'antigravity';\n\n/**\n * Detect which AI coding tools are installed in the project by checking\n * for their config directories.\n */\nexport function detectInstalledTools(projectPath: string): DetectedTool[] {\n const tools: DetectedTool[] = ['claude_code'];\n\n if (existsSync(join(projectPath, '.cursor'))) {\n tools.push('cursor');\n }\n\n if (existsSync(join(projectPath, '.github'))) {\n tools.push('copilot_agent');\n }\n\n // Antigravity's workspace config lives at `.agents/`. The user-level hooks\n // file at ~/.gemini/config/hooks.json is written by writeAntigravityUserHooks()\n // ONLY when ~/.gemini already exists (the tool is present) \u2014 see F2.\n if (existsSync(join(projectPath, '.agents'))) {\n tools.push('antigravity');\n }\n\n return tools;\n}\n\n/**\n * Generate Cursor hooks config object.\n *\n * Cursor uses event names like beforeSubmitPrompt, afterFileEdit, etc.\n * Each event maps to an array of hook objects with a `command` field.\n */\nexport function generateCursorHooksConfig(binDir?: string): object {\n // Event coverage matches Cursor 1.7+ hook API (cursor.com/docs/hooks).\n // `sessionStart` is required so the registry file is written with\n // conversation_id before any tool runs; without it the proxy-based linker\n // path would have nothing to map and we'd drop captures. `sessionEnd`\n // emits the session-end signal once per chat conversation (vs `stop`\n // which fires per-turn \u2014 those go through post-tool-use).\n //\n // binDir: prepended to PATH like the Claude Code hooks \u2014 Cursor is a GUI app\n // launched with launchd's minimal PATH (no nvm/pnpm-global bin), so a bare\n // `rulemetric` silently fails with command-not-found.\n const prefix = binDir ? `PATH=\"${binDir}:$PATH\" ` : '';\n const cmd = (name: string) => ({ command: `${prefix}rulemetric hooks run ${name}` });\n return {\n version: 1,\n hooks: {\n sessionStart: [cmd('session-start')],\n beforeSubmitPrompt: [cmd('user-prompt')],\n afterFileEdit: [cmd('post-tool-use')],\n beforeShellExecution: [cmd('post-tool-use')],\n afterShellExecution: [cmd('post-tool-use')],\n beforeMCPExecution: [cmd('post-tool-use')],\n afterMCPExecution: [cmd('post-tool-use')],\n // `afterAgentResponse` carries the full assistant response text +\n // token usage. Verified empirically via a probe hook on\n // 2026-05-12 \u2014 Cursor passes `text`, `input_tokens`,\n // `output_tokens`, `cache_read_tokens`, `cache_write_tokens`. This\n // is the cleanest path to per-turn assistant content for Cursor\n // (chat traffic itself bypasses the proxy via HTTP/2 \u2014 see\n // docs/audits/2026-05-11-cursor-capture-architecture.md).\n afterAgentResponse: [cmd('assistant-response')],\n // `stop` fires when the agent loop ends for a single turn (status:\n // completed|aborted|error). Per-turn, NOT per-session \u2014 route it to\n // post-tool-use, not session-end. The real session boundary is\n // `sessionEnd` below.\n stop: [cmd('post-tool-use')],\n sessionEnd: [cmd('session-end')],\n },\n };\n}\n\n/**\n * Generate Copilot Agent hooks config object.\n *\n * Copilot uses event names like sessionStart, userPromptSubmitted, etc.\n * Each event maps to an array of hook objects with `type` and `bash` fields.\n */\nexport function generateCopilotHooksConfig(binDir?: string): object {\n // binDir prepended to PATH \u2014 Copilot Agent runs in the same GUI/minimal-PATH\n // environment class as Cursor, so a bare `rulemetric` silently fails.\n const prefix = binDir ? `PATH=\"${binDir}:$PATH\" ` : '';\n const cmd = (name: string) => ({ type: 'command', bash: `${prefix}rulemetric hooks run ${name}` });\n return {\n version: 1,\n hooks: {\n sessionStart: [cmd('session-start')],\n userPromptSubmitted: [cmd('user-prompt')],\n postToolUse: [cmd('post-tool-use')],\n sessionEnd: [cmd('session-end')],\n },\n };\n}\n\ninterface ClaudeHookEntry {\n type: 'command';\n command: string;\n}\n\ninterface ClaudeHookBlock {\n matcher?: string;\n hooks: ClaudeHookEntry[];\n}\n\n/** The `settings.hooks` map RuleMetric installs into a project's `.claude/settings.json`. */\nexport type ClaudeCodeHooksConfig = Record<\n 'SessionStart' | 'UserPromptSubmit' | 'PostToolUse' | 'Stop' | 'SessionEnd',\n ClaudeHookBlock[]\n>;\n\n/**\n * Generate the Claude Code hooks map for `.claude/settings.json`.\n *\n * Claude Code keys hook blocks by native event name, each block being\n * `{ matcher?, hooks: [{ type: 'command', command }] }`. Unlike Antigravity\n * these carry NO `RULEMETRIC_HOOK_TOOL` prefix \u2014 `_normalize.sh` defaults to\n * the `claude_code` branch (session_id + transcript_path payload shape).\n *\n * This is the hooks-first, zero-proxy capture path: SessionEnd runs\n * `session-end.sh`, which reimports the whole transcript via\n * `POST /api/sessions/:id/reimport` \u2014 no mitmproxy / CA trust / gateway needed.\n * The rendered system prompt is still proxy-only, so instruction-effectiveness\n * linking is handled separately (Phase 2 synthetic snapshot).\n */\nexport function generateClaudeCodeHooksConfig(binDir?: string): ClaudeCodeHooksConfig {\n // The literal `rulemetric` is always present: it's the marker that install.ts\n // \u00A71 and mergeClaudeCodeHooks use to dedup/strip our hooks (a resolved\n // node+run.js path omits 'rulemetric' in a dev checkout, which would silently\n // break that dedup).\n //\n // `binDir`, when provided, is prepended to PATH so the command resolves even\n // in Claude Code's hook shell \u2014 which runs `/bin/sh -c` with a minimal PATH\n // that does NOT include nvm/pnpm global bin dirs. Without it, a fresh-install\n // user hits `rulemetric: command not found` on every hook, so capture (and\n // the session-start gateway auto-start that keeps the proxy alive) silently\n // fails. Callers resolve the real bin dir at install time and pass it here.\n const prefix = binDir ? `PATH=\"${binDir}:$PATH\" ` : '';\n const mk = (name: string): ClaudeHookEntry => ({\n type: 'command',\n command: `${prefix}rulemetric hooks run ${name}`,\n });\n return {\n SessionStart: [{ hooks: [mk('session-start')] }],\n UserPromptSubmit: [{ hooks: [mk('user-prompt')] }],\n PostToolUse: [{ matcher: '.*', hooks: [mk('post-tool-use')] }],\n Stop: [{ hooks: [mk('assistant-response')] }],\n SessionEnd: [{ hooks: [mk('session-end')] }],\n };\n}\n\n/**\n * Read a Claude Code `settings.json` for merging, WITHOUT ever crashing the\n * install on a fresh machine. A missing file yields `{}`. A malformed file\n * (hand-edited JSONC, a stray trailing comma, a half-written file) is NOT\n * allowed to throw \u2014 that used to hard-fail `hooks install` with a raw\n * SyntaxError and leave the user with NO capture. Instead we back the\n * unparseable file up (so nothing is silently lost) and proceed on a fresh\n * object so capture still installs.\n *\n * Returns the parsed settings plus `recoveredBackup`: the path the corrupt\n * original was copied to, or `null` when the file was absent/valid.\n */\nexport function readClaudeSettings(configPath: string): {\n settings: Record<string, unknown>;\n recoveredBackup: string | null;\n} {\n if (!existsSync(configPath)) return { settings: {}, recoveredBackup: null };\n const raw = readFileSync(configPath, 'utf-8');\n try {\n return { settings: JSON.parse(raw) as Record<string, unknown>, recoveredBackup: null };\n } catch {\n const recoveredBackup = `${configPath}.corrupt.bak`;\n writeFileSync(recoveredBackup, raw);\n return { settings: {}, recoveredBackup };\n }\n}\n\n/**\n * Write a Claude Code `settings.json`, backing up any prior file first so the\n * change is reversible: the `.bak` holds the previous contents for the user to\n * restore manually if a merge ever goes wrong. Creates the parent dir as needed.\n * Returns `backupPath` (the `.bak` written) or `null` when there was no\n * pre-existing file to back up.\n */\nexport function writeClaudeSettingsWithBackup(\n configPath: string,\n settings: Record<string, unknown>,\n): { backupPath: string | null } {\n mkdirSync(dirname(configPath), { recursive: true });\n let backupPath: string | null = null;\n if (existsSync(configPath)) {\n backupPath = `${configPath}.bak`;\n copyFileSync(configPath, backupPath);\n }\n writeFileSync(configPath, JSON.stringify(settings, null, 2) + '\\n');\n return { backupPath };\n}\n\n/**\n * Read a JSON config file for a safe in-place merge. Returns `{}` when the file\n * is absent, the parsed object when it's valid, and `null` when it EXISTS but is\n * unparseable \u2014 in which case the original is first backed up to `.corrupt.bak`.\n * Callers MUST treat `null` as \"skip, do not write\": editor settings.json files\n * are JSONC (comments + trailing commas are legal and common), so a strict\n * JSON.parse throws on valid user files; blindly resetting to `{}` and writing\n * would clobber the user's ENTIRE editor config down to our few keys. Backing up\n * + skipping is the non-destructive floor (mirrors readClaudeSettings).\n */\nfunction readMergeableJson(configPath: string): Record<string, unknown> | null {\n if (!existsSync(configPath)) return {};\n const raw = readFileSync(configPath, 'utf-8');\n try {\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n try {\n writeFileSync(`${configPath}.corrupt.bak`, raw);\n } catch {\n /* best-effort backup */\n }\n return null;\n }\n}\n\n/**\n * Merge RuleMetric's Claude Code hooks into an in-memory `.claude/settings.json`\n * object. Claude Code hooks share the same settings.json that install.ts reads,\n * strips (\u00A71), and writes (\u00A75), so this mutates `settings.hooks` in place rather\n * than doing its own file I/O. Idempotent + non-destructive: per event it skips\n * adding when a rulemetric command is already present and otherwise appends,\n * preserving the user's own hooks.\n */\nexport function mergeClaudeCodeHooks(settings: Record<string, unknown>, binDir?: string): void {\n const generated = generateClaudeCodeHooksConfig(binDir);\n const hooks = (settings.hooks ?? {}) as Record<string, ClaudeHookBlock[]>;\n for (const [event, blocks] of Object.entries(generated)) {\n const current = (hooks[event] ?? []) as ClaudeHookBlock[];\n const alreadyPresent = current.some((b) =>\n b?.hooks?.some((h) => typeof h?.command === 'string' && h.command.includes('rulemetric')),\n );\n if (!alreadyPresent) {\n hooks[event] = [...current, ...blocks];\n }\n }\n settings.hooks = hooks;\n}\n\n/**\n * True iff RuleMetric's Claude Code session hooks are present in a settings\n * object \u2014 i.e. capture is actually wired up. This is the honest readiness\n * signal for the onboarding hooks step: capture works when the hooks exist,\n * NOT merely because a proxy env var was written (which greened even when the\n * proxy pointed at a dead port \u2014 the fresh-laptop ConnectionRefused footgun).\n */\nexport function hasRulemetricClaudeHooks(settings: Record<string, unknown>): boolean {\n if (!settings.hooks || typeof settings.hooks !== 'object') return false;\n const hooks = settings.hooks as Record<string, ClaudeHookBlock[]>;\n return Object.values(hooks).some(\n (blocks) =>\n Array.isArray(blocks) &&\n blocks.some((b) =>\n b?.hooks?.some((h) => typeof h?.command === 'string' && h.command.includes('rulemetric')),\n ),\n );\n}\n\n/**\n * Strip RuleMetric's Claude Code hooks from an in-memory settings object while\n * preserving the user's own hook entries. Mirrors install.ts \u00A71 but is reusable\n * for uninstall. Removes emptied event arrays and deletes `settings.hooks` if it\n * ends up empty. Returns true iff anything was removed.\n */\nexport function removeClaudeCodeHooks(settings: Record<string, unknown>): boolean {\n if (!settings.hooks || typeof settings.hooks !== 'object') return false;\n const hooks = settings.hooks as Record<string, ClaudeHookBlock[]>;\n let removed = 0;\n for (const event of Object.keys(hooks)) {\n const entries = hooks[event];\n if (!Array.isArray(entries)) continue;\n const kept = entries.filter((block) => {\n const isRulemetric = block?.hooks?.some(\n (h) => typeof h?.command === 'string' && h.command.includes('rulemetric'),\n );\n if (isRulemetric) removed += 1;\n return !isRulemetric;\n });\n if (kept.length === 0) delete hooks[event];\n else hooks[event] = kept;\n }\n if (Object.keys(hooks).length === 0) delete settings.hooks;\n return removed > 0;\n}\n\n// ---------------------------------------------------------------------------\n// Machine-local Claude Code settings (settings.local.json) + shared-file healing\n// ---------------------------------------------------------------------------\n\n/** The NO_PROXY value `hooks install` writes alongside HTTPS_PROXY. */\nexport const RULEMETRIC_NO_PROXY = 'localhost,127.0.0.1,*.supabase.co,*.supabase.in';\n\n/**\n * The settings file `hooks install` owns for RuleMetric's machine-local state.\n * Project installs write `settings.local.json`: the shared `settings.json` is\n * typically checked into git, and everything we write is machine-local by\n * nature \u2014 hook commands carry a per-user PATH prefix, and the proxy env pins\n * HTTPS_PROXY + a per-user CA path that BREAK Claude Code's HTTPS on any clone\n * without a live gateway on that port. Claude Code merges settings.local.json\n * on top of settings.json, runs hooks from both, and auto-gitignores the local\n * file. Global installs keep writing `~/.claude/settings.json` \u2014 the home file\n * is not in a repo, so machine-local state is safe there.\n */\nexport function claudeSettingsInstallPath(configDir: string, isGlobal: boolean): string {\n return join(configDir, isGlobal ? 'settings.json' : 'settings.local.json');\n}\n\n/**\n * Remove the gateway proxy env keys `hooks install` writes, and ONLY those:\n * each key is deleted solely when its value is one RuleMetric itself produces,\n * so a user-owned corporate proxy / custom CA is never touched.\n * - HTTPS_PROXY: points at the local gateway port (localhost or 127.0.0.1)\n * - NO_PROXY: exactly RULEMETRIC_NO_PROXY\n * - NODE_EXTRA_CA_CERTS: the mitmproxy default CA path \u2014 suffix-matched, not\n * exact, because a shared file poisoned by a teammate's install carries\n * THEIR $HOME prefix\n * Drops the `env` block entirely when the removal empties it. Returns true iff\n * anything was removed.\n */\nexport function removeRulemetricProxyEnv(\n settings: Record<string, unknown>,\n gatewayPort: number,\n): boolean {\n const env = settings.env as Record<string, unknown> | undefined;\n if (!env || typeof env !== 'object') return false;\n let removed = false;\n const proxy = env.HTTPS_PROXY;\n if (proxy === `http://localhost:${gatewayPort}` || proxy === `http://127.0.0.1:${gatewayPort}`) {\n delete env.HTTPS_PROXY;\n removed = true;\n }\n if (env.NO_PROXY === RULEMETRIC_NO_PROXY) {\n delete env.NO_PROXY;\n removed = true;\n }\n const ca = env.NODE_EXTRA_CA_CERTS;\n if (typeof ca === 'string' && ca.includes('.mitmproxy') && ca.endsWith('mitmproxy-ca-cert.pem')) {\n delete env.NODE_EXTRA_CA_CERTS;\n removed = true;\n }\n if (removed && Object.keys(env).length === 0) delete settings.env;\n return removed;\n}\n\nexport interface RulemetricStateRemoval {\n removedHooks: boolean;\n removedProxyEnv: boolean;\n removedStatusline: boolean;\n /** True iff any of the three categories removed something. */\n removed: boolean;\n}\n\n/**\n * Strip ALL RuleMetric-owned machine-local state from an in-memory settings\n * object: session hooks, gateway proxy env keys, and the statusline shim. Each\n * remover has its own user-preserving predicate, so anything the user owns\n * survives untouched. Shared by uninstall and the shared-file migration.\n */\nexport function removeRulemetricMachineState(\n settings: Record<string, unknown>,\n gatewayPort: number,\n): RulemetricStateRemoval {\n const removedHooks = removeClaudeCodeHooks(settings);\n const removedProxyEnv = removeRulemetricProxyEnv(settings, gatewayPort);\n const removedStatusline = removeStatuslineShimAnyHome(settings);\n return {\n removedHooks,\n removedProxyEnv,\n removedStatusline,\n removed: removedHooks || removedProxyEnv || removedStatusline,\n };\n}\n\nexport interface SharedSettingsMigration extends RulemetricStateRemoval {\n /** True iff something was removed and the file was rewritten. */\n migrated: boolean;\n backupPath: string | null;\n}\n\n/**\n * Heal a shared `.claude/settings.json` that an older `hooks install` (this\n * machine's or a teammate's) filled with machine-local state: PATH-prefixed,\n * username-leaking hook commands, the gateway proxy env keys (an HTTPS_PROXY\n * pin breaks Claude Code's HTTPS entirely on any clone without a live gateway\n * on that port), and the $HOME-anchored statusline shim. User-owned hooks/env/\n * statusLine are never touched. The file is rewritten (with the standard\n * backup) ONLY when something was actually removed; an unparseable file is\n * left exactly as-is \u2014 we cannot safely edit what we cannot parse.\n */\nexport function migrateSharedClaudeSettings(\n sharedPath: string,\n gatewayPort: number,\n): SharedSettingsMigration {\n const none: SharedSettingsMigration = {\n migrated: false,\n backupPath: null,\n removedHooks: false,\n removedProxyEnv: false,\n removedStatusline: false,\n removed: false,\n };\n if (!existsSync(sharedPath)) return none;\n let settings: Record<string, unknown>;\n try {\n settings = JSON.parse(readFileSync(sharedPath, 'utf-8')) as Record<string, unknown>;\n } catch {\n return none;\n }\n const removal = removeRulemetricMachineState(settings, gatewayPort);\n if (!removal.removed) return none;\n const { backupPath } = writeClaudeSettingsWithBackup(sharedPath, settings);\n return { ...removal, migrated: true, backupPath };\n}\n\nexport interface ClaudeSettingsCleanup extends RulemetricStateRemoval {\n configPath: string;\n /** `settings.json` or `settings.local.json` \u2014 for log lines. */\n fileName: string;\n recoveredBackup: string | null;\n /** True iff the file was rewritten. */\n changed: boolean;\n}\n\n/**\n * Remove all RuleMetric-owned state from BOTH Claude Code settings files in a\n * project: the shared `settings.json` (legacy installs wrote there) and\n * `settings.local.json` (where current installs put machine-local state). Each\n * file is rewritten (with backup) only when something was actually removed.\n * Returns one entry per file that exists, with per-category flags so the\n * caller can log precisely what was cleaned where.\n */\nexport function cleanClaudeSettingsFiles(\n claudeDir: string,\n gatewayPort: number,\n): ClaudeSettingsCleanup[] {\n const results: ClaudeSettingsCleanup[] = [];\n for (const fileName of ['settings.json', 'settings.local.json'] as const) {\n const configPath = join(claudeDir, fileName);\n if (!existsSync(configPath)) continue;\n const { settings, recoveredBackup } = readClaudeSettings(configPath);\n const removal = removeRulemetricMachineState(settings, gatewayPort);\n if (removal.removed) {\n writeClaudeSettingsWithBackup(configPath, settings);\n }\n results.push({\n ...removal,\n configPath,\n fileName,\n recoveredBackup,\n changed: removal.removed,\n });\n }\n return results;\n}\n\n/**\n * Merge rulemetric hooks into a Cursor `hooks.json` at the given directory.\n *\n * Used by both the project (`<repo>/.cursor/`) and user (`~/.cursor/`) writers.\n * Returns the config file path, or null if the cursor dir doesn't exist.\n */\nfunction writeCursorHooksToDir(cursorDir: string, binDir?: string): string | null {\n if (!existsSync(cursorDir)) {\n return null;\n }\n\n const configPath = join(cursorDir, 'hooks.json');\n const generated = generateCursorHooksConfig(binDir) as {\n version: number;\n hooks: Record<string, Array<{ command: string }>>;\n };\n\n const parsed = readMergeableJson(configPath);\n if (parsed === null) return null; // unparseable \u2014 backed up, don't drop sibling hooks\n const existing = parsed as { version?: number; hooks?: Record<string, unknown[]> };\n\n const merged: Record<string, unknown[]> = { ...(existing.hooks ?? {}) };\n\n const isRulemetricHook = (h: unknown): boolean =>\n typeof h === 'object' &&\n h !== null &&\n 'command' in h &&\n typeof (h as { command: string }).command === 'string' &&\n (h as { command: string }).command.includes('rulemetric');\n\n for (const [event, hooks] of Object.entries(generated.hooks)) {\n const current = merged[event] ?? [];\n // REPLACE prior rulemetric entries, never skip-if-present: a stale command\n // (old format, moved binary, outdated PATH prefix) must be repairable by\n // re-running `hooks install` \u2014 skip-if-present froze broken Cursor capture\n // forever. Sibling (non-rulemetric) hooks are preserved untouched.\n const siblings = current.filter((h: unknown) => !isRulemetricHook(h));\n merged[event] = [...siblings, ...hooks];\n }\n\n const result = {\n version: existing.version ?? generated.version,\n hooks: merged,\n };\n\n writeFileSync(configPath, JSON.stringify(result, null, 2) + '\\n');\n return configPath;\n}\n\n/**\n * Write Cursor hooks config to `<projectPath>/.cursor/hooks.json`.\n * Merges with existing config \u2014 appends rulemetric hooks without duplicating.\n * Returns the config file path, or null if `.cursor/` doesn't exist.\n */\nexport function writeCursorHooks(projectPath: string, binDir?: string): string | null {\n return writeCursorHooksToDir(join(projectPath, '.cursor'), binDir);\n}\n\n/**\n * Write Cursor hooks config to user-level `~/.cursor/hooks.json` so capture\n * works for every Cursor conversation without per-project setup.\n *\n * Returns the config file path, or null if `~/.cursor/` doesn't exist\n * (i.e., Cursor has never been launched on this machine).\n */\nexport function writeCursorUserHooks(binDir?: string, home: string = homedir()): string | null {\n // Only wire user-level Cursor hooks if Cursor is actually present \u2014 never\n // manufacture ~/.cursor for a user who doesn't use it (undisclosed scope,\n // onboarding field report 2026-07-07 F2). `home` is injectable for tests.\n const cursorHome = join(home, '.cursor');\n if (!existsSync(cursorHome)) return null;\n return writeCursorHooksToDir(cursorHome, binDir);\n}\n\n/**\n * Write Copilot Agent hooks config to `.github/hooks/rulemetric.json`.\n * Creates the hooks directory if needed.\n * Returns the config file path, or null if `.github/` doesn't exist.\n */\nexport function writeCopilotHooks(projectPath: string, binDir?: string): string | null {\n const githubDir = join(projectPath, '.github');\n if (!existsSync(githubDir)) {\n return null;\n }\n\n const hooksDir = join(githubDir, 'hooks');\n mkdirSync(hooksDir, { recursive: true });\n\n const configPath = join(hooksDir, 'rulemetric.json');\n const config = generateCopilotHooksConfig(binDir);\n\n writeFileSync(configPath, JSON.stringify(config, null, 2) + '\\n');\n return configPath;\n}\n\n/**\n * Strip rulemetric hooks from a Cursor `hooks.json` at the given path.\n * Preserves other hooks and removes empty event arrays.\n * Returns true if changes were made.\n */\nfunction removeCursorHooksFromFile(configPath: string): boolean {\n if (!existsSync(configPath)) {\n return false;\n }\n\n let config: { version?: number; hooks?: Record<string, unknown[]> };\n try {\n config = JSON.parse(readFileSync(configPath, 'utf-8'));\n } catch {\n return false;\n }\n\n if (!config.hooks) {\n return false;\n }\n\n let changed = false;\n for (const [event, hooks] of Object.entries(config.hooks)) {\n const filtered = hooks.filter((h: unknown) => {\n if (typeof h !== 'object' || h === null || !('command' in h)) return true;\n const cmd = (h as { command: string }).command;\n if (typeof cmd === 'string' && cmd.includes('rulemetric')) {\n changed = true;\n return false;\n }\n return true;\n });\n\n if (filtered.length === 0) {\n delete config.hooks[event];\n } else {\n config.hooks[event] = filtered;\n }\n }\n\n if (changed) {\n writeFileSync(configPath, JSON.stringify(config, null, 2) + '\\n');\n }\n\n return changed;\n}\n\n/**\n * Remove rulemetric hooks from `<projectPath>/.cursor/hooks.json`.\n */\nexport function removeCursorHooks(projectPath: string): boolean {\n return removeCursorHooksFromFile(join(projectPath, '.cursor', 'hooks.json'));\n}\n\n/**\n * Remove rulemetric hooks from user-level `~/.cursor/hooks.json`.\n */\nexport function removeCursorUserHooks(): boolean {\n return removeCursorHooksFromFile(join(homedir(), '.cursor', 'hooks.json'));\n}\n\n/**\n * Write Cursor proxy config to `.cursor/settings.json`.\n * Sets `http.proxy` and `http.proxyStrictSSL` while preserving existing settings.\n * Returns true if `.cursor/` exists and config was written, false otherwise.\n */\nexport function writeCursorProxyConfig(projectPath: string, gatewayPort: number, certPath: string): boolean {\n const cursorDir = join(projectPath, '.cursor');\n if (!existsSync(cursorDir)) return false;\n\n const settingsPath = join(cursorDir, 'settings.json');\n const settings = readMergeableJson(settingsPath);\n if (settings === null) return false; // unparseable JSONC \u2014 backed up, don't clobber\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = existsSync(certPath);\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Write VS Code proxy config to `.vscode/settings.json` for Copilot capture.\n * Sets `http.proxy`, `http.proxyStrictSSL`, and Copilot-specific override\n * while preserving existing settings.\n * Returns true if config was written, false if `.vscode/` doesn't exist.\n */\nexport function writeVSCodeProxyConfig(projectPath: string, gatewayPort: number, certPath: string): boolean {\n const vscodeDir = join(projectPath, '.vscode');\n // Only touch projects that already use VS Code \u2014 do NOT manufacture a\n // `.vscode/` in every repo (matches writeCursorProxyConfig's contract and this\n // function's own docstring). Creating it pollutes Claude-Code-only repos with\n // an untracked, proxy-pinning settings.json.\n if (!existsSync(vscodeDir)) return false;\n\n const settingsPath = join(vscodeDir, 'settings.json');\n const settings = readMergeableJson(settingsPath);\n if (settings === null) return false; // unparseable JSONC \u2014 backed up, don't clobber\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = existsSync(certPath);\n\n // Copilot-specific override for surgical proxy targeting\n const copilotAdvanced = (settings['github.copilot.advanced'] ?? {}) as Record<string, unknown>;\n copilotAdvanced['debug.overrideProxyUrl'] = `http://localhost:${gatewayPort}`;\n settings['github.copilot.advanced'] = copilotAdvanced;\n\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Remove VS Code proxy config from `.vscode/settings.json`.\n * Removes `http.proxy`, `http.proxyStrictSSL`, and Copilot proxy override.\n * Returns true if changes were made.\n */\nexport function removeVSCodeProxyConfig(projectPath: string): boolean {\n const settingsPath = join(projectPath, '.vscode', 'settings.json');\n if (!existsSync(settingsPath)) return false;\n\n let settings: Record<string, unknown>;\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }\n\n let changed = false;\n\n if (settings['http.proxy']) {\n delete settings['http.proxy'];\n delete settings['http.proxyStrictSSL'];\n changed = true;\n }\n\n const copilotAdvanced = settings['github.copilot.advanced'] as Record<string, unknown> | undefined;\n if (copilotAdvanced?.['debug.overrideProxyUrl']) {\n delete copilotAdvanced['debug.overrideProxyUrl'];\n if (Object.keys(copilotAdvanced).length === 0) {\n delete settings['github.copilot.advanced'];\n }\n changed = true;\n }\n\n if (changed) {\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n }\n\n return changed;\n}\n\n/**\n * Remove Copilot Agent hooks by deleting `.github/hooks/rulemetric.json`.\n * Returns true if the file was removed.\n */\nexport function removeCopilotHooks(projectPath: string): boolean {\n const configPath = join(projectPath, '.github', 'hooks', 'rulemetric.json');\n if (!existsSync(configPath)) {\n return false;\n }\n\n unlinkSync(configPath);\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// macOS LaunchAgent for GUI app env vars (HTTPS_PROXY, NODE_EXTRA_CA_CERTS)\n// ---------------------------------------------------------------------------\n\nconst LAUNCH_AGENT_LABEL = 'com.rulemetric.env';\n\nfunction getLaunchAgentPath(): string {\n return join(homedir(), 'Library', 'LaunchAgents', `${LAUNCH_AGENT_LABEL}.plist`);\n}\n\n/**\n * Set HTTPS_PROXY and NODE_EXTRA_CA_CERTS for all GUI apps on macOS.\n *\n * Two layers:\n * 1. `launchctl setenv` \u2014 immediate effect for newly launched apps\n * 2. LaunchAgent plist \u2014 persists across reboots\n *\n * This ensures VS Code / Copilot / Cursor route LLM traffic through the\n * gateway even when launched from Dock or Spotlight (not a terminal).\n *\n * References:\n * - anthropics/claude-code#30318 (same pattern for Claude Desktop)\n * - Snyk IDE docs recommend launchctl setenv for macOS\n * - Apple QA1067 (archived) \u2014 original env var mechanism removed in 10.10\n */\nexport function installMacOSProxyEnv(gatewayPort: number, certPath: string): boolean {\n if (process.platform !== 'darwin') return false;\n\n const proxyUrl = `http://localhost:${gatewayPort}`;\n\n // Layer 1: immediate effect via launchctl setenv\n try {\n execSync(`launchctl setenv HTTPS_PROXY ${proxyUrl}`, { stdio: 'pipe' });\n if (existsSync(certPath)) {\n execSync(`launchctl setenv NODE_EXTRA_CA_CERTS ${certPath}`, { stdio: 'pipe' });\n }\n } catch {\n return false;\n }\n\n // Layer 2: LaunchAgent plist for persistence across reboots\n const plistPath = getLaunchAgentPath();\n const agentsDir = join(homedir(), 'Library', 'LaunchAgents');\n mkdirSync(agentsDir, { recursive: true });\n\n const certLine = existsSync(certPath)\n ? `launchctl setenv NODE_EXTRA_CA_CERTS ${certPath};`\n : '';\n\n // LIVENESS-GUARDED boot command: at every login this re-pins HTTPS_PROXY\n // machine-wide, but the gateway on :8787 is not a supervised service on the\n // end-user path \u2014 it dies on logout and nothing restarts it. Pinning a dead\n // port breaks HTTPS for every GUI app. So probe :8787 first and only setenv\n // when the gateway actually answers; otherwise clear it (the session-start\n // hook will re-pin once Claude Code brings the gateway back up).\n const bootCmd =\n `if nc -z -w 1 127.0.0.1 ${gatewayPort} 2>/dev/null; then ` +\n `launchctl setenv HTTPS_PROXY ${proxyUrl};${certLine} ` +\n `else launchctl unsetenv HTTPS_PROXY; launchctl unsetenv NODE_EXTRA_CA_CERTS; fi`;\n\n const plist = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"\n \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${LAUNCH_AGENT_LABEL}</string>\n <key>ProgramArguments</key>\n <array>\n <string>/bin/sh</string>\n <string>-c</string>\n <string>${bootCmd}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n</dict>\n</plist>\n`;\n\n writeFileSync(plistPath, plist);\n return true;\n}\n\n/**\n * Remove the RuleMetric LaunchAgent and unset env vars.\n */\nexport function uninstallMacOSProxyEnv(): boolean {\n if (process.platform !== 'darwin') return false;\n\n let changed = false;\n\n // Unset env vars for current session\n try {\n execSync('launchctl unsetenv HTTPS_PROXY', { stdio: 'pipe' });\n execSync('launchctl unsetenv NODE_EXTRA_CA_CERTS', { stdio: 'pipe' });\n } catch { /* may not be set */ }\n\n // Remove LaunchAgent plist\n const plistPath = getLaunchAgentPath();\n if (existsSync(plistPath)) {\n unlinkSync(plistPath);\n changed = true;\n }\n\n return changed;\n}\n\n// ---------------------------------------------------------------------------\n// VS Code user-level proxy settings\n// ---------------------------------------------------------------------------\n\nfunction getVSCodeUserSettingsPath(): string {\n if (process.platform === 'darwin') {\n return join(homedir(), 'Library', 'Application Support', 'Code', 'User', 'settings.json');\n }\n if (process.platform === 'win32') {\n return join(process.env.APPDATA ?? '', 'Code', 'User', 'settings.json');\n }\n return join(homedir(), '.config', 'Code', 'User', 'settings.json');\n}\n\n/**\n * Set http.proxy in VS Code user settings (not workspace).\n *\n * Workspace-level http.proxy is silently ignored because VS Code restricts\n * it to APPLICATION scope (microsoft/vscode#236932). User-level settings\n * are the only reliable way to configure http.proxy.\n */\nexport function writeVSCodeUserProxyConfig(gatewayPort: number): boolean {\n const settingsPath = getVSCodeUserSettingsPath();\n if (!existsSync(join(settingsPath, '..'))) return false;\n\n const settings = readMergeableJson(settingsPath);\n if (settings === null) return false; // unparseable JSONC \u2014 backed up, don't clobber user config\n\n // Only set if not already configured by the user\n if (settings['http.proxy'] && !(settings['http.proxy'] as string).includes('localhost')) {\n return false; // user has a custom proxy, don't overwrite\n }\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = false;\n\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Remove RuleMetric proxy config from VS Code user settings.\n */\nexport function removeVSCodeUserProxyConfig(): boolean {\n const settingsPath = getVSCodeUserSettingsPath();\n if (!existsSync(settingsPath)) return false;\n\n let settings: Record<string, unknown>;\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }\n\n const proxy = settings['http.proxy'] as string | undefined;\n if (!proxy?.includes('localhost')) return false;\n\n delete settings['http.proxy'];\n delete settings['http.proxyStrictSSL'];\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Cursor user-level proxy settings\n// ---------------------------------------------------------------------------\n//\n// Cursor is a VS Code fork and uses the same settings.json shape, but reads\n// from `Cursor/User/settings.json` instead of `Code/User/settings.json`. The\n// `.cursor/settings.json` (workspace) path can't reach Cursor's Electron main\n// process for the same reason VS Code's workspace path can't reach VS Code's\n// \u2014 the http.proxy setting is restricted to APPLICATION scope and only the\n// user-level file is honored.\n\nfunction getCursorUserSettingsPath(): string {\n if (process.platform === 'darwin') {\n return join(homedir(), 'Library', 'Application Support', 'Cursor', 'User', 'settings.json');\n }\n if (process.platform === 'win32') {\n return join(process.env.APPDATA ?? '', 'Cursor', 'User', 'settings.json');\n }\n return join(homedir(), '.config', 'Cursor', 'User', 'settings.json');\n}\n\n/**\n * Set http.proxy in Cursor user settings (not workspace). Mirrors\n * `writeVSCodeUserProxyConfig` \u2014 workspace-level http.proxy is silently\n * ignored due to APPLICATION-scope restriction (Cursor inherits this from\n * VS Code, see microsoft/vscode#236932).\n *\n * Returns true if config was written, false if Cursor isn't installed\n * (User dir absent) or the user already has a non-localhost proxy set.\n */\nexport function writeCursorUserProxyConfig(gatewayPort: number): boolean {\n const settingsPath = getCursorUserSettingsPath();\n if (!existsSync(join(settingsPath, '..'))) return false;\n\n const settings = readMergeableJson(settingsPath);\n if (settings === null) return false; // unparseable JSONC \u2014 backed up, don't clobber user config\n\n if (settings['http.proxy'] && !(settings['http.proxy'] as string).includes('localhost')) {\n return false;\n }\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = false;\n\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Remove RuleMetric proxy config from Cursor user settings.\n */\nexport function removeCursorUserProxyConfig(): boolean {\n const settingsPath = getCursorUserSettingsPath();\n if (!existsSync(settingsPath)) return false;\n\n let settings: Record<string, unknown>;\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }\n\n const proxy = settings['http.proxy'] as string | undefined;\n if (!proxy?.includes('localhost')) return false;\n\n delete settings['http.proxy'];\n delete settings['http.proxyStrictSSL'];\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n// \u2500\u2500\u2500 Antigravity (Google's Gemini-based agentic IDE) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Antigravity hooks live in `.agents/hooks.json` (workspace) and\n// `~/.gemini/config/hooks.json` (user-level). Events follow the\n// SessionStart / UserPromptSubmit / PreToolUse / PostToolUse / Stop /\n// SessionEnd vocabulary. Each hook command sets `RULEMETRIC_HOOK_TOOL=\n// antigravity` so `_normalize.sh` routes through the Antigravity branch.\n\ninterface AntigravityHookEntry {\n type: 'command';\n command: string;\n timeout?: number;\n}\n\ninterface AntigravityHookBlock {\n matcher?: string;\n hooks: AntigravityHookEntry[];\n}\n\ninterface AntigravityRuleMetricBlock {\n enabled: boolean;\n SessionStart: AntigravityHookBlock[];\n UserPromptSubmit: AntigravityHookBlock[];\n PreToolUse: AntigravityHookBlock[];\n PostToolUse: AntigravityHookBlock[];\n Stop: AntigravityHookBlock[];\n SessionEnd: AntigravityHookBlock[];\n}\n\nexport type AntigravityHooksConfig = { rulemetric: AntigravityRuleMetricBlock };\n\n/** Resolve the binary string to invoke for a hook command. */\nfunction getRulemetricCommand(): string {\n // Prefer the local Node binary + bin/run.js so the hook works even when\n // `rulemetric` isn't on PATH for the GUI Antigravity process.\n const nodeBin = process.execPath;\n // bin/run.js lives next to dist/ in the installed CLI; resolve from\n // import.meta isn't available in a portable way here, so we use the\n // process argv1 if it's pointing at the CLI entry, else fall back to\n // the bare command name. In practice this function is called inside\n // `rulemetric hooks install`, where process.argv[1] is bin/run.js.\n const cliEntry = process.argv[1];\n if (cliEntry && cliEntry.endsWith('run.js')) {\n return `${nodeBin} ${cliEntry}`;\n }\n return 'rulemetric';\n}\n\nexport function generateAntigravityHooksConfig(): AntigravityHooksConfig {\n const cmd = getRulemetricCommand();\n const mk = (name: string): AntigravityHookEntry => ({\n type: 'command',\n command: `RULEMETRIC_HOOK_TOOL=antigravity ${cmd} hooks run ${name}`,\n timeout: 30,\n });\n return {\n rulemetric: {\n enabled: true,\n SessionStart: [{ hooks: [mk('session-start')] }],\n UserPromptSubmit: [{ hooks: [mk('user-prompt')] }],\n PreToolUse: [{ matcher: '.*', hooks: [mk('post-tool-use')] }],\n PostToolUse: [{ matcher: '.*', hooks: [mk('post-tool-use')] }],\n Stop: [{ hooks: [mk('assistant-response')] }],\n SessionEnd: [{ hooks: [mk('session-end')] }],\n },\n };\n}\n\nfunction writeAntigravityHooksToDir(dir: string): string | null {\n const configPath = join(dir, 'hooks.json');\n const existing = readMergeableJson(configPath);\n if (existing === null) return null; // unparseable \u2014 backed up, don't drop sibling blocks\n const generated = generateAntigravityHooksConfig();\n // Antigravity keys hook blocks by name; RuleMetric owns its own block\n // and never touches sibling blocks the user may have added.\n const merged = { ...existing, rulemetric: generated.rulemetric };\n mkdirSync(dir, { recursive: true });\n writeFileSync(configPath, JSON.stringify(merged, null, 2) + '\\n');\n return configPath;\n}\n\nexport function writeAntigravityHooks(projectPath: string): string | null {\n return writeAntigravityHooksToDir(join(projectPath, '.agents'));\n}\n\nexport function writeAntigravityUserHooks(home: string = homedir()): string | null {\n // Only wire user-level Antigravity/Gemini hooks if the tool is actually\n // present \u2014 never manufacture ~/.gemini for a user who doesn't use it\n // (undisclosed scope, onboarding field report 2026-07-07 F2). `home` is\n // injectable for tests.\n const geminiHome = join(home, '.gemini');\n if (!existsSync(geminiHome)) return null;\n return writeAntigravityHooksToDir(join(geminiHome, 'config'));\n}\n\nfunction removeAntigravityHooksFromFile(configPath: string): boolean {\n if (!existsSync(configPath)) return false;\n let existing: Record<string, unknown>;\n try { existing = JSON.parse(readFileSync(configPath, 'utf-8')); } catch { return false; }\n if (!('rulemetric' in existing)) return false;\n delete existing.rulemetric;\n if (Object.keys(existing).length === 0) {\n // No other blocks \u2014 remove the file entirely.\n try { unlinkSync(configPath); } catch { /* ignore */ }\n } else {\n writeFileSync(configPath, JSON.stringify(existing, null, 2) + '\\n');\n }\n return true;\n}\n\nexport function removeAntigravityHooks(projectPath: string): boolean {\n return removeAntigravityHooksFromFile(join(projectPath, '.agents', 'hooks.json'));\n}\n\nexport function removeAntigravityUserHooks(): boolean {\n const modern = removeAntigravityHooksFromFile(join(homedir(), '.gemini', 'config', 'hooks.json'));\n const legacy = removeAntigravityHooksFromFile(join(homedir(), '.gemini', 'hooks.json'));\n return modern || legacy;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY,WAAW,cAAc,eAAe,YAAY,oBAAoB;AAC7F,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AASvB,SAAS,qBAAqB,aAAqC;AACxE,QAAM,QAAwB,CAAC,aAAa;AAE5C,MAAI,WAAW,KAAK,aAAa,SAAS,CAAC,GAAG;AAC5C,UAAM,KAAK,QAAQ;AAAA,EACrB;AAEA,MAAI,WAAW,KAAK,aAAa,SAAS,CAAC,GAAG;AAC5C,UAAM,KAAK,eAAe;AAAA,EAC5B;AAKA,MAAI,W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 @@
|
|
|
1
|
+
import {
|
|
2
|
+
probeGatewayIdentity,
|
|
3
|
+
waitForGatewayIdentity
|
|
4
|
+
} from "./chunk-7LVVKQMZ.js";
|
|
5
|
+
import {
|
|
6
|
+
GATEWAY_ENTRY_COMMAND_PATTERN,
|
|
7
|
+
isPidLiveAndMatching
|
|
8
|
+
} from "./chunk-5EDMGK3W.js";
|
|
9
|
+
|
|
1
10
|
// src/lib/gateway-lifecycle.ts
|
|
2
11
|
import { spawn } from "node:child_process";
|
|
3
12
|
import { createConnection } from "node:net";
|
|
@@ -32,17 +41,16 @@ async function waitForGatewayListening(port = GATEWAY_PORT, { timeoutMs = 3e3, i
|
|
|
32
41
|
await new Promise((resolve2) => setTimeout(resolve2, intervalMs));
|
|
33
42
|
}
|
|
34
43
|
}
|
|
35
|
-
function
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
44
|
+
function isRulemetricGatewayListening(port = GATEWAY_PORT, timeoutMs = 1500) {
|
|
45
|
+
return probeGatewayIdentity(port, timeoutMs);
|
|
46
|
+
}
|
|
47
|
+
function waitForRulemetricGateway(port = GATEWAY_PORT, opts = {}) {
|
|
48
|
+
return waitForGatewayIdentity(port, opts);
|
|
49
|
+
}
|
|
50
|
+
function isGatewayRunning(pidOpts = {}) {
|
|
51
|
+
const pid = getGatewayPid();
|
|
52
|
+
if (pid === null) return false;
|
|
53
|
+
return isPidLiveAndMatching(pid, GATEWAY_ENTRY_COMMAND_PATTERN, pidOpts);
|
|
46
54
|
}
|
|
47
55
|
function getGatewayPid() {
|
|
48
56
|
if (!existsSync(GATEWAY_PID_FILE)) return null;
|
|
@@ -98,12 +106,14 @@ function spawnGateway(cliVersion) {
|
|
|
98
106
|
writeFileSync(GATEWAY_PID_FILE, String(child.pid));
|
|
99
107
|
return child.pid;
|
|
100
108
|
}
|
|
101
|
-
function stopGateway() {
|
|
109
|
+
function stopGateway(pidOpts = {}) {
|
|
102
110
|
const pid = getGatewayPid();
|
|
103
111
|
if (pid === null) return false;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
112
|
+
if (isPidLiveAndMatching(pid, GATEWAY_ENTRY_COMMAND_PATTERN, pidOpts)) {
|
|
113
|
+
try {
|
|
114
|
+
process.kill(pid, "SIGTERM");
|
|
115
|
+
} catch {
|
|
116
|
+
}
|
|
107
117
|
}
|
|
108
118
|
try {
|
|
109
119
|
unlinkSync(GATEWAY_PID_FILE);
|
|
@@ -119,9 +129,11 @@ export {
|
|
|
119
129
|
MITMPROXY_PORT,
|
|
120
130
|
isGatewayListening,
|
|
121
131
|
waitForGatewayListening,
|
|
132
|
+
isRulemetricGatewayListening,
|
|
133
|
+
waitForRulemetricGateway,
|
|
122
134
|
isGatewayRunning,
|
|
123
135
|
getGatewayPid,
|
|
124
136
|
spawnGateway,
|
|
125
137
|
stopGateway
|
|
126
138
|
};
|
|
127
|
-
//# sourceMappingURL=chunk-
|
|
139
|
+
//# sourceMappingURL=chunk-4LYCDS2N.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/gateway-lifecycle.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Gateway process lifecycle helpers \u2014 spawn, stop, check status.\n * Used by hooks install/uninstall, session-start hook, and proxy status.\n */\nimport { spawn } from 'node:child_process';\nimport { createConnection } from 'node:net';\nimport { existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n probeGatewayIdentity,\n waitForGatewayIdentity,\n type GatewayIdentity,\n} from './gateway-identity.js';\nimport {\n isPidLiveAndMatching,\n GATEWAY_ENTRY_COMMAND_PATTERN,\n type PidIdentityOptions,\n} from './pid-identity.js';\n\n// `import.meta.dirname` only exists on Node >= 20.11 \u2014 on Node 18.x/\u226420.10 it is\n// `undefined`, and `resolve(undefined, \u2026)` throws, surfacing as a spurious\n// \"Could not find gateway-entry.js\" on fresh npm installs (the launchd gateway\n// masks it in dev). Derive the dir portably instead. See onboarding field report\n// 2026-07-07 F1.\nconst MODULE_DIR = dirname(fileURLToPath(import.meta.url));\n\nconst CONFIG_DIR = join(homedir(), '.config', 'rulemetric');\nexport const GATEWAY_PID_FILE = join(CONFIG_DIR, 'gateway.pid');\nexport const GATEWAY_LOG_FILE = join(CONFIG_DIR, 'gateway.log');\nexport const GATEWAY_PORT = 8787;\nexport const MITMPROXY_PORT = 8788;\n\n/**\n * TCP liveness probe: does something actually ACCEPT a connection on the port?\n * Distinct from isGatewayRunning() (which only checks the PID is alive) \u2014 a\n * process can be \"running\" per its pidfile while :8787 accepts nothing. This is\n * the check that must gate writing HTTPS_PROXY: never pin Claude Code's proxy\n * at a port with nothing behind it (the fresh-laptop ConnectionRefused footgun).\n */\nexport function isGatewayListening(port: number = GATEWAY_PORT, timeoutMs = 1500): Promise<boolean> {\n return new Promise((resolveProbe) => {\n const socket = createConnection({ host: '127.0.0.1', port });\n const finish = (result: boolean) => {\n socket.destroy();\n resolveProbe(result);\n };\n socket.setTimeout(timeoutMs);\n socket.once('connect', () => finish(true));\n socket.once('timeout', () => finish(false));\n socket.once('error', () => finish(false));\n });\n}\n\n/**\n * Poll isGatewayListening() until it's true or the window elapses. spawnGateway()\n * returns as soon as it writes the PID file \u2014 the detached child hasn't bound\n * :8787 yet (Node bootstrap + module load). A one-shot probe microseconds later\n * fails-closed on every fresh install, so the proxy/deep-capture layer silently\n * never turns on. This tolerates a normal cold-start bind delay.\n */\nexport async function waitForGatewayListening(\n port: number = GATEWAY_PORT,\n { timeoutMs = 3000, intervalMs = 150 }: { timeoutMs?: number; intervalMs?: number } = {},\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n if (await isGatewayListening(port, Math.min(1500, timeoutMs))) return true;\n if (Date.now() >= deadline) return false;\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n}\n\n/**\n * Identity-aware liveness probe on :GATEWAY_PORT \u2014 connects, requests the\n * identity marker, and distinguishes ours-live / foreign / dead. This (not\n * the raw TCP probe above) is what HTTPS_PROXY-pinning decisions must use: a\n * foreign process accepting on :8787 passes isGatewayListening() but would\n * brick every HTTPS request Claude Code makes.\n */\nexport function isRulemetricGatewayListening(\n port: number = GATEWAY_PORT,\n timeoutMs = 1500,\n): Promise<GatewayIdentity> {\n return probeGatewayIdentity(port, timeoutMs);\n}\n\n/**\n * Poll the identity probe through a cold-start bind delay. 'dead' retries\n * until the window elapses; 'ours-live' and 'foreign' return immediately\n * (waiting can't change what owns the port).\n */\nexport function waitForRulemetricGateway(\n port: number = GATEWAY_PORT,\n opts: { timeoutMs?: number; intervalMs?: number } = {},\n): Promise<GatewayIdentity> {\n return waitForGatewayIdentity(port, opts);\n}\n\n/**\n * PID-file liveness WITH identity validation. PID files survive reboots, and\n * `kill -0` on a reused PID reports \"alive\" for an unrelated process \u2014 which\n * permanently defeats the session-start self-heal. The recorded PID only\n * counts as \"running\" when its command line is actually gateway-entry.\n */\nexport function isGatewayRunning(pidOpts: PidIdentityOptions = {}): boolean {\n const pid = getGatewayPid();\n if (pid === null) return false;\n return isPidLiveAndMatching(pid, GATEWAY_ENTRY_COMMAND_PATTERN, pidOpts);\n}\n\nexport function getGatewayPid(): number | null {\n if (!existsSync(GATEWAY_PID_FILE)) return null;\n const content = readFileSync(GATEWAY_PID_FILE, 'utf-8').trim();\n const pid = parseInt(content, 10);\n return isNaN(pid) ? null : pid;\n}\n\nfunction findGatewayEntry(): string {\n // Resolve the compiled gateway-entry.js across BOTH layouts:\n // - unbundled (dev/tsx, or tsc output): this module sits in dist/lib, so\n // gateway-entry.js is a sibling (`./gateway-entry.js`).\n // - BUNDLED (published build): esbuild flattens this module into\n // dist/chunk-*.js at the dist ROOT, so MODULE_DIR is dist/ and the entry\n // (kept as a separate build entry) is at dist/lib/gateway-entry.js\n // (`./lib/gateway-entry.js`). Without this candidate the gateway never\n // spawns on a clean npm install \u2014 masked in dev by the launchd gateway\n // short-circuiting before this runs. See onboarding field report F1.\n const candidates = [\n resolve(MODULE_DIR, './gateway-entry.js'), // sibling (unbundled)\n resolve(MODULE_DIR, './lib/gateway-entry.js'), // bundled chunk at dist root\n resolve(MODULE_DIR, '../lib/gateway-entry.js'), // nested command dir \u2192 dist/lib\n resolve(MODULE_DIR, '../../lib/gateway-entry.js'),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n throw new Error(\n 'Could not find gateway-entry.js. Is the CLI built?\\n' +\n 'Searched:\\n' + candidates.map(c => ` ${c}`).join('\\n'),\n );\n}\n\nexport function spawnGateway(cliVersion?: string): number {\n if (isGatewayRunning()) {\n const pid = getGatewayPid();\n if (pid) return pid;\n }\n\n mkdirSync(CONFIG_DIR, { recursive: true });\n\n const entryPath = findGatewayEntry();\n const logFd = openSync(GATEWAY_LOG_FILE, 'a');\n\n const child = spawn(process.execPath, [entryPath], {\n detached: true,\n stdio: ['ignore', logFd, logFd],\n // The gateway inherits the spawning CLI's env. RULEMETRIC_CLI_VERSION\n // identifies the CLI version that started this gateway \u2014 used to\n // detect drift when a newer CLI starts mitmproxy with a different\n // version. RULEMETRIC_CLI_ENTRY is the path to the oclif entry point\n // (process.argv[1]) so the gateway can re-invoke the CLI for\n // `proxy restart` without needing the binary in PATH. Falls back to\n // \"unknown\" if the caller didn't pass them.\n env: {\n ...process.env,\n RULEMETRIC_CLI_VERSION: cliVersion ?? 'unknown',\n RULEMETRIC_CLI_ENTRY: process.argv[1] ?? '',\n },\n });\n\n child.unref();\n\n if (!child.pid) {\n throw new Error('Failed to spawn gateway process');\n }\n\n writeFileSync(GATEWAY_PID_FILE, String(child.pid));\n return child.pid;\n}\n\nexport function stopGateway(pidOpts: PidIdentityOptions = {}): boolean {\n const pid = getGatewayPid();\n if (pid === null) return false;\n\n // Only signal a PID whose command line is actually gateway-entry \u2014 a\n // reused PID belongs to an unrelated process we must never SIGTERM. Either\n // way the PID file is stale after this and gets removed.\n if (isPidLiveAndMatching(pid, GATEWAY_ENTRY_COMMAND_PATTERN, pidOpts)) {\n try {\n process.kill(pid, 'SIGTERM');\n } catch {\n // Process already gone\n }\n }\n\n try { unlinkSync(GATEWAY_PID_FILE); } catch { /* already gone */ }\n return true;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;AAIA,SAAS,aAAa;AACtB,SAAS,wBAAwB;AACjC,SAAS,YAAY,WAAW,UAAU,cAAc,YAAY,qBAAqB;AACzF,SAAS,eAAe;AACxB,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,qBAAqB;AAiB9B,IAAM,aAAa,QAAQ,cAAc,YAAY,GAAG,CAAC;AAEzD,IAAM,aAAa,KAAK,QAAQ,GAAG,WAAW,YAAY;AACnD,IAAM,mBAAmB,KAAK,YAAY,aAAa;AACvD,IAAM,mBAAmB,KAAK,YAAY,aAAa;AACvD,IAAM,eAAe;AACrB,IAAM,iBAAiB;AASvB,SAAS,mBAAmB,OAAe,cAAc,YAAY,MAAwB;AAClG,SAAO,IAAI,QAAQ,CAAC,iBAAiB;AACnC,UAAM,SAAS,iBAAiB,EAAE,MAAM,aAAa,KAAK,CAAC;AAC3D,UAAM,SAAS,CAAC,WAAoB;AAClC,aAAO,QAAQ;AACf,mBAAa,MAAM;AAAA,IACrB;AACA,WAAO,WAAW,SAAS;AAC3B,WAAO,KAAK,WAAW,MAAM,OAAO,IAAI,CAAC;AACzC,WAAO,KAAK,WAAW,MAAM,OAAO,KAAK,CAAC;AAC1C,WAAO,KAAK,SAAS,MAAM,OAAO,KAAK,CAAC;AAAA,EAC1C,CAAC;AACH;AASA,eAAsB,wBACpB,OAAe,cACf,EAAE,YAAY,KAAM,aAAa,IAAI,IAAiD,CAAC,GACrE;AAClB,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,aAAS;AACP,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KAAK,CAAC;AAEzC,QAAM,YAAY,iBAAiB;AACnC,QAAM,QAAQ,SAAS,kBAAkB,GAAG;AAE5C,QAAM,QAAQ,MAAM,QAAQ,UAAU,CAAC,SAAS,GAAG;AAAA,IACjD,UAAU;AAAA,IACV,OAAO,CAAC,UAAU,OAAO,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQ9B,KAAK;AAAA,MACH,GAAG,QAAQ;AAAA,MACX,wBAAwB,cAAc;AAAA,MACtC,sBAAsB,QAAQ,KAAK,CAAC,KAAK;AAAA,IAC3C;AAAA,EACF,CAAC;AAED,QAAM,MAAM;AAEZ,MAAI,CAAC,MAAM,KAAK;AACd,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AAEA,gBAAc,kBAAkB,OAAO,MAAM,GAAG,CAAC;AACjD,SAAO,MAAM;AACf;AAEO,SAAS,YAAY,UAA8B,CAAC,GAAY;AACrE,QAAM,MAAM,cAAc;AAC1B,MAAI,QAAQ,KAAM,QAAO;AAKzB,MAAI,qBAAqB,KAAK,+BAA+B,OAAO,GAAG;AACrE,QAAI;AACF,cAAQ,KAAK,KAAK,SAAS;AAAA,IAC7B,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,MAAI;AAAE,eAAW,gBAAgB;AAAA,EAAG,QAAQ;AAAA,EAAqB;AACjE,SAAO;AACT;",
|
|
6
|
+
"names": ["resolve"]
|
|
7
|
+
}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ActiveJobsList
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-5BAOGNUH.js";
|
|
4
4
|
import {
|
|
5
5
|
NewLaunchForm
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-DNKSVWMD.js";
|
|
7
|
+
import {
|
|
8
|
+
ORANGE
|
|
9
|
+
} from "./chunk-QJQS6TUN.js";
|
|
7
10
|
import {
|
|
8
11
|
useLaunchJobs
|
|
9
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-EYPAAGN5.js";
|
|
10
13
|
import {
|
|
11
14
|
cancelLaunchJob,
|
|
12
15
|
createLaunchJob,
|
|
13
16
|
listLaunchers
|
|
14
|
-
} from "./chunk-
|
|
15
|
-
import {
|
|
16
|
-
ORANGE
|
|
17
|
-
} from "./chunk-QJQS6TUN.js";
|
|
17
|
+
} from "./chunk-UKMLICWS.js";
|
|
18
18
|
|
|
19
19
|
// src/dashboard/launcher/LauncherOverlay.tsx
|
|
20
20
|
import { useEffect, useState } from "react";
|
|
@@ -158,4 +158,4 @@ function LauncherOverlay({
|
|
|
158
158
|
export {
|
|
159
159
|
LauncherOverlay
|
|
160
160
|
};
|
|
161
|
-
//# sourceMappingURL=chunk-
|
|
161
|
+
//# sourceMappingURL=chunk-4XAWK6S2.js.map
|
|
@@ -3,19 +3,19 @@ import {
|
|
|
3
3
|
FACET_GENERATION_PROMPT,
|
|
4
4
|
RECOMMENDATION_PROMPTS
|
|
5
5
|
} from "./chunk-XZXS2W24.js";
|
|
6
|
+
import {
|
|
7
|
+
PermanentJobError
|
|
8
|
+
} from "./chunk-DGHWRQXL.js";
|
|
6
9
|
import {
|
|
7
10
|
detectLlmBackend,
|
|
8
11
|
runLlmPrompt,
|
|
9
12
|
runToolPrompt
|
|
10
13
|
} from "./chunk-FZKLLNDS.js";
|
|
11
|
-
import {
|
|
12
|
-
PermanentJobError
|
|
13
|
-
} from "./chunk-DGHWRQXL.js";
|
|
14
14
|
import {
|
|
15
15
|
apiGet,
|
|
16
16
|
apiPatch,
|
|
17
17
|
apiPost
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-ZUJBM6HE.js";
|
|
19
19
|
|
|
20
20
|
// src/lib/handlers/process-insights.ts
|
|
21
21
|
async function processInsights(payload, helpers) {
|
|
@@ -240,4 +240,4 @@ async function buildDataSummaryFromApi(projectPath, projectId) {
|
|
|
240
240
|
export {
|
|
241
241
|
processInsights
|
|
242
242
|
};
|
|
243
|
-
//# sourceMappingURL=chunk-
|
|
243
|
+
//# sourceMappingURL=chunk-4YAP7RT7.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
toolLabel
|
|
3
|
-
} from "./chunk-RH7NHVSK.js";
|
|
4
1
|
import {
|
|
5
2
|
DIM,
|
|
6
3
|
GREEN,
|
|
7
4
|
ORANGE,
|
|
8
5
|
RED
|
|
9
6
|
} from "./chunk-QJQS6TUN.js";
|
|
7
|
+
import {
|
|
8
|
+
toolLabel
|
|
9
|
+
} from "./chunk-RH7NHVSK.js";
|
|
10
10
|
|
|
11
11
|
// src/dashboard/launcher/ActiveJobsList.tsx
|
|
12
12
|
import { Box, Text } from "ink";
|
|
@@ -76,4 +76,4 @@ function ActiveJobsList({
|
|
|
76
76
|
export {
|
|
77
77
|
ActiveJobsList
|
|
78
78
|
};
|
|
79
|
-
//# sourceMappingURL=chunk-
|
|
79
|
+
//# sourceMappingURL=chunk-5BAOGNUH.js.map
|