@ascenda-one/agent-mcp 0.1.33 → 0.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +1050 -243
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -965,7 +965,7 @@ var require_collectorVersion = __commonJS({
965
965
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
966
966
  exports.describeCollectorVersion = describeCollectorVersion;
967
967
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
968
- exports.COLLECTOR_VERSION = "0.1.33" ? "0.1.33" : exports.UNRELEASED_COLLECTOR_VERSION;
968
+ exports.COLLECTOR_VERSION = "0.1.34" ? "0.1.34" : exports.UNRELEASED_COLLECTOR_VERSION;
969
969
  function describeCollectorVersion(version2 = exports.COLLECTOR_VERSION) {
970
970
  return version2 === exports.UNRELEASED_COLLECTOR_VERSION ? `${version2} (built from a checkout, not a release)` : version2;
971
971
  }
@@ -3674,6 +3674,771 @@ var require_setupDisclosure = __commonJS({
3674
3674
  }
3675
3675
  });
3676
3676
 
3677
+ // ../packages/tool-kit/out/hookRunner.js
3678
+ var require_hookRunner = __commonJS({
3679
+ "../packages/tool-kit/out/hookRunner.js"(exports) {
3680
+ "use strict";
3681
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3682
+ if (k2 === void 0) k2 = k;
3683
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3684
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3685
+ desc = { enumerable: true, get: function() {
3686
+ return m[k];
3687
+ } };
3688
+ }
3689
+ Object.defineProperty(o, k2, desc);
3690
+ } : function(o, m, k, k2) {
3691
+ if (k2 === void 0) k2 = k;
3692
+ o[k2] = m[k];
3693
+ });
3694
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3695
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3696
+ } : function(o, v) {
3697
+ o["default"] = v;
3698
+ });
3699
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3700
+ var ownKeys = function(o) {
3701
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3702
+ var ar = [];
3703
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3704
+ return ar;
3705
+ };
3706
+ return ownKeys(o);
3707
+ };
3708
+ return function(mod) {
3709
+ if (mod && mod.__esModule) return mod;
3710
+ var result = {};
3711
+ if (mod != null) {
3712
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3713
+ }
3714
+ __setModuleDefault(result, mod);
3715
+ return result;
3716
+ };
3717
+ }();
3718
+ Object.defineProperty(exports, "__esModule", { value: true });
3719
+ exports.hookRunnerPaths = hookRunnerPaths;
3720
+ exports.hookLauncherScript = hookLauncherScript;
3721
+ exports.installHookRunner = installHookRunner;
3722
+ exports.removeHookRunner = removeHookRunner;
3723
+ exports.hookRunnerCommand = hookRunnerCommand;
3724
+ exports.lastHookPath = lastHookPath;
3725
+ exports.stampLastHook = stampLastHook;
3726
+ exports.readLastHook = readLastHook;
3727
+ exports.describeAge = describeAge;
3728
+ exports.resolveHookNode = resolveHookNode;
3729
+ exports.tidyHomePath = tidyHomePath;
3730
+ var child_process_1 = __require("child_process");
3731
+ var fs = __importStar(__require("fs"));
3732
+ var path = __importStar(__require("path"));
3733
+ var tokenStore_1 = require_tokenStore();
3734
+ function hookRunnerPaths(binaryName) {
3735
+ const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3736
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
3737
+ }
3738
+ var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3739
+ function hookLauncherScript(options) {
3740
+ const { binaryName, setupCommand, loudEvent } = options;
3741
+ return [
3742
+ "#!/bin/sh",
3743
+ `# Ascenda hook launcher (${binaryName}). Written by \`setup\`, replaced by the`,
3744
+ "# next one; edits here are lost. Finds a Node to run the hook bundle beside it.",
3745
+ "",
3746
+ 'dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0',
3747
+ `bundle="$dir/${binaryName}.mjs"`,
3748
+ `record="$dir/${binaryName}.node"`,
3749
+ `missing="$dir/${binaryName}.no-node"`,
3750
+ "",
3751
+ 'runs() { [ -n "$1" ] && [ -f "$1" ] && [ -x "$1" ]; }',
3752
+ "",
3753
+ "# The hook bundle needs Node 20 or newer. Checked only while searching, so",
3754
+ "# the recorded path costs nothing to reuse.",
3755
+ "recent() {",
3756
+ ` runs "$1" && "$1" -e 'process.exit(parseInt(process.versions.node, 10) >= 20 ? 0 : 1)' >/dev/null 2>&1`,
3757
+ "}",
3758
+ "",
3759
+ "newest_nvm() {",
3760
+ ' [ -d "$HOME/.nvm/versions/node" ] || return 0',
3761
+ ` ls "$HOME/.nvm/versions/node" 2>/dev/null | sed 's/^v//' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1 | sed 's/^/v/'`,
3762
+ "}",
3763
+ "",
3764
+ 'node=""',
3765
+ "how=recorded",
3766
+ '[ -r "$record" ] && IFS= read -r node < "$record"',
3767
+ "",
3768
+ 'if ! runs "$node"; then',
3769
+ ' node=""',
3770
+ " how=found",
3771
+ ' nvm_default=""',
3772
+ ' if [ -r "$HOME/.nvm/alias/default" ]; then',
3773
+ ' IFS= read -r wanted < "$HOME/.nvm/alias/default"',
3774
+ " wanted=${wanted#v}",
3775
+ ' for candidate in "$HOME/.nvm/versions/node/v$wanted"*; do',
3776
+ ' [ -x "$candidate/bin/node" ] && nvm_default="$candidate/bin/node"',
3777
+ " done",
3778
+ " fi",
3779
+ " nvm_newest=$(newest_nvm)",
3780
+ " for candidate in \\",
3781
+ ' "$(command -v node 2>/dev/null)" \\',
3782
+ " /opt/homebrew/bin/node \\",
3783
+ " /usr/local/bin/node \\",
3784
+ ' "$HOME/.volta/bin/node" \\',
3785
+ ' "$nvm_default" \\',
3786
+ ' "$HOME/.local/share/fnm/aliases/default/bin/node" \\',
3787
+ ' "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \\',
3788
+ ' "$HOME/.asdf/shims/node" \\',
3789
+ ' "$HOME/.local/share/mise/shims/node" \\',
3790
+ ' "$HOME/.nvm/versions/node/$nvm_newest/bin/node"',
3791
+ " do",
3792
+ ' if recent "$candidate"; then node=$candidate; break; fi',
3793
+ " done",
3794
+ ' if [ -n "$node" ]; then',
3795
+ ` printf '%s\\n' "$node" > "$record.$$" 2>/dev/null && mv -f "$record.$$" "$record" 2>/dev/null`,
3796
+ ' rm -f "$missing" 2>/dev/null',
3797
+ " fi",
3798
+ "fi",
3799
+ "",
3800
+ 'if [ -n "$ASCENDA_HOOK_LAUNCHER_PROBE" ]; then',
3801
+ ' [ -n "$node" ] || { echo "no Node 20 or newer found on PATH or in the usual install locations" >&2; exit 1; }',
3802
+ ` printf '%s\\t%s\\n' "$node" "$how"`,
3803
+ " exit 0",
3804
+ "fi",
3805
+ "",
3806
+ 'if [ -z "$node" ]; then',
3807
+ ' date -u +%Y-%m-%dT%H:%M:%SZ > "$missing" 2>/dev/null',
3808
+ ' case "$1" in',
3809
+ ...loudEvent ? [
3810
+ ` ${loudEvent})`,
3811
+ " cat >/dev/null 2>&1",
3812
+ ` echo "Ascenda hooks cannot find Node 20 or newer, so none of them are running. Install Node, then run: ${setupCommand}" >&2`,
3813
+ " exit 1 ;;"
3814
+ ] : [],
3815
+ ` ${LAUNCHER_MANAGEMENT_COMMANDS.join("|")})`,
3816
+ ` echo "${binaryName}: no Node 20 or newer found on PATH or in the usual install locations." >&2`,
3817
+ " exit 1 ;;",
3818
+ " *)",
3819
+ " # A hook: say nothing per tool call. status and doctor read the",
3820
+ " # file written above.",
3821
+ " cat >/dev/null 2>&1",
3822
+ " exit 0 ;;",
3823
+ " esac",
3824
+ "fi",
3825
+ "",
3826
+ 'exec "$node" "$bundle" "$@"',
3827
+ ""
3828
+ ].join("\n");
3829
+ }
3830
+ function installHookRunner(options) {
3831
+ const paths = hookRunnerPaths(options.binaryName);
3832
+ if (options.dryRun)
3833
+ return paths.launcher;
3834
+ const source = path.resolve(options.source ?? process.argv[1]);
3835
+ fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
3836
+ if (process.platform === "win32") {
3837
+ if (source !== path.resolve(paths.launcher))
3838
+ fs.copyFileSync(source, paths.launcher);
3839
+ return paths.launcher;
3840
+ }
3841
+ if (source !== path.resolve(paths.bundle))
3842
+ writeAtomically(paths.bundle, fs.readFileSync(source), 493);
3843
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
3844
+ writeAtomically(paths.record, `${process.execPath}
3845
+ `, 420);
3846
+ fs.rmSync(paths.noNode, { force: true });
3847
+ return paths.launcher;
3848
+ }
3849
+ function removeHookRunner(binaryName) {
3850
+ const removed = [];
3851
+ for (const file of Object.values(hookRunnerPaths(binaryName))) {
3852
+ if (!fs.existsSync(file))
3853
+ continue;
3854
+ fs.rmSync(file, { force: true });
3855
+ removed.push(file);
3856
+ }
3857
+ return removed;
3858
+ }
3859
+ function hookRunnerCommand(launcher) {
3860
+ return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
3861
+ }
3862
+ function writeAtomically(target, contents, mode) {
3863
+ const tmp = `${target}.${process.pid}.tmp`;
3864
+ fs.writeFileSync(tmp, contents, { mode });
3865
+ fs.chmodSync(tmp, mode);
3866
+ fs.renameSync(tmp, target);
3867
+ }
3868
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join((0, tokenStore_1.ascendaHome)(), "state");
3869
+ function lastHookPath(tool) {
3870
+ return path.join(stateDir(), `${tool}-last-hook.json`);
3871
+ }
3872
+ function stampLastHook(tool, event, now = /* @__PURE__ */ new Date()) {
3873
+ try {
3874
+ fs.mkdirSync(stateDir(), { recursive: true });
3875
+ const file = lastHookPath(tool);
3876
+ const tmp = `${file}.${process.pid}.tmp`;
3877
+ fs.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
3878
+ `, { mode: 384 });
3879
+ fs.renameSync(tmp, file);
3880
+ } catch {
3881
+ }
3882
+ }
3883
+ function readLastHook(tool) {
3884
+ try {
3885
+ const parsed = JSON.parse(fs.readFileSync(lastHookPath(tool), "utf8"));
3886
+ if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
3887
+ return void 0;
3888
+ return { event: parsed.event, at: parsed.at };
3889
+ } catch {
3890
+ return void 0;
3891
+ }
3892
+ }
3893
+ function describeAge(ms) {
3894
+ if (!Number.isFinite(ms) || ms < 0)
3895
+ return "just now";
3896
+ const seconds = Math.round(ms / 1e3);
3897
+ if (seconds < 60)
3898
+ return `${seconds} s ago`;
3899
+ const minutes = Math.round(seconds / 60);
3900
+ if (minutes < 60)
3901
+ return `${minutes} min ago`;
3902
+ const hours = Math.round(minutes / 60);
3903
+ if (hours < 48)
3904
+ return `${hours} h ago`;
3905
+ return `${Math.round(hours / 24)} days ago`;
3906
+ }
3907
+ function resolveHookNode(launcher) {
3908
+ if (!fs.existsSync(launcher))
3909
+ return { problem: "the hook launcher is not installed" };
3910
+ const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
3911
+ encoding: "utf8",
3912
+ timeout: 5e3,
3913
+ env: { HOME: process.env.HOME ?? "", PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ASCENDA_HOOK_LAUNCHER_PROBE: "1" }
3914
+ });
3915
+ const [node, how] = (probe.stdout ?? "").trim().split(" ");
3916
+ if (probe.status !== 0 || !node) {
3917
+ return { problem: (probe.stderr ?? "").trim() || "the launcher found no Node it can run" };
3918
+ }
3919
+ const version2 = (0, child_process_1.spawnSync)(node, ["--version"], { encoding: "utf8", timeout: 5e3 });
3920
+ if (version2.status !== 0)
3921
+ return { node, how, problem: `${node} did not run` };
3922
+ return { node, how, version: version2.stdout.trim() };
3923
+ }
3924
+ function tidyHomePath(file, home = process.env.HOME ?? "") {
3925
+ return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
3926
+ }
3927
+ }
3928
+ });
3929
+
3930
+ // ../packages/tool-kit/out/saverHandoff.js
3931
+ var require_saverHandoff = __commonJS({
3932
+ "../packages/tool-kit/out/saverHandoff.js"(exports) {
3933
+ "use strict";
3934
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3935
+ if (k2 === void 0) k2 = k;
3936
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3937
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3938
+ desc = { enumerable: true, get: function() {
3939
+ return m[k];
3940
+ } };
3941
+ }
3942
+ Object.defineProperty(o, k2, desc);
3943
+ } : function(o, m, k, k2) {
3944
+ if (k2 === void 0) k2 = k;
3945
+ o[k2] = m[k];
3946
+ });
3947
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3948
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3949
+ } : function(o, v) {
3950
+ o["default"] = v;
3951
+ });
3952
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3953
+ var ownKeys = function(o) {
3954
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3955
+ var ar = [];
3956
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3957
+ return ar;
3958
+ };
3959
+ return ownKeys(o);
3960
+ };
3961
+ return function(mod) {
3962
+ if (mod && mod.__esModule) return mod;
3963
+ var result = {};
3964
+ if (mod != null) {
3965
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3966
+ }
3967
+ __setModuleDefault(result, mod);
3968
+ return result;
3969
+ };
3970
+ }();
3971
+ Object.defineProperty(exports, "__esModule", { value: true });
3972
+ exports.SAVER_REPLAY_SCHEMA = exports.SAVER_REPLAY_WINDOW_MS = void 0;
3973
+ exports.saverContainerDir = saverContainerDir;
3974
+ exports.saverSupportDir = saverSupportDir;
3975
+ exports.saverReplayPath = saverReplayPath;
3976
+ exports.saverStatusDir = saverStatusDir;
3977
+ exports.holdForSaver = holdForSaver;
3978
+ exports.heldForSaver = heldForSaver;
3979
+ exports.readSaverStatuses = readSaverStatuses;
3980
+ exports.probeSocket = probeSocket;
3981
+ var fs = __importStar(__require("fs"));
3982
+ var net = __importStar(__require("net"));
3983
+ var os = __importStar(__require("os"));
3984
+ var path = __importStar(__require("path"));
3985
+ var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3986
+ function saverContainerDir() {
3987
+ return process.env.ASCENDA_SAVER_CONTAINER ?? path.join(os.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
3988
+ }
3989
+ function saverSupportDir() {
3990
+ return path.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
3991
+ }
3992
+ function saverReplayPath() {
3993
+ return path.join(saverContainerDir(), "l.replay.json");
3994
+ }
3995
+ function saverStatusDir() {
3996
+ return path.join(saverSupportDir(), "status");
3997
+ }
3998
+ exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
3999
+ var SAVER_REPLAY_MAX = 32;
4000
+ exports.SAVER_REPLAY_SCHEMA = 1;
4001
+ function holdForSaver(signal, now = Date.now()) {
4002
+ try {
4003
+ if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
4004
+ return;
4005
+ if (!fs.existsSync(saverSupportDir()))
4006
+ return;
4007
+ const wire = signal;
4008
+ const tool = wire.tool;
4009
+ const session = wire.session;
4010
+ const event = wire.event;
4011
+ if (typeof tool !== "string" || typeof session !== "string" || typeof event !== "string")
4012
+ return;
4013
+ const file = saverReplayPath();
4014
+ const kept = readHeld(file).filter((held) => now - held.at <= exports.SAVER_REPLAY_WINDOW_MS && !(held.tool === tool && held.session === session));
4015
+ kept.push({ ...wire, tool, session, event, at: now });
4016
+ kept.sort((a, b) => a.at - b.at);
4017
+ const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
4018
+ const tmp = `${file}.${process.pid}.tmp`;
4019
+ fs.writeFileSync(tmp, `${body}
4020
+ `, { mode: 384 });
4021
+ fs.renameSync(tmp, file);
4022
+ } catch {
4023
+ }
4024
+ }
4025
+ function readHeld(file) {
4026
+ try {
4027
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
4028
+ if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
4029
+ return [];
4030
+ return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
4031
+ } catch {
4032
+ return [];
4033
+ }
4034
+ }
4035
+ function heldForSaver(now = Date.now()) {
4036
+ const held = readHeld(saverReplayPath()).filter((entry) => now - entry.at <= exports.SAVER_REPLAY_WINDOW_MS);
4037
+ if (held.length === 0)
4038
+ return { count: 0 };
4039
+ return { count: held.length, newestAgeMs: now - Math.max(...held.map((entry) => entry.at)) };
4040
+ }
4041
+ function readSaverStatuses(now = Date.now()) {
4042
+ let names;
4043
+ try {
4044
+ names = fs.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
4045
+ } catch {
4046
+ return [];
4047
+ }
4048
+ const readings = [];
4049
+ for (const name of names) {
4050
+ try {
4051
+ const status = JSON.parse(fs.readFileSync(path.join(saverStatusDir(), name), "utf8"));
4052
+ if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
4053
+ continue;
4054
+ readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
4055
+ } catch {
4056
+ }
4057
+ }
4058
+ return readings.sort((a, b) => a.ageMs - b.ageMs);
4059
+ }
4060
+ function processAlive(pid) {
4061
+ try {
4062
+ process.kill(pid, 0);
4063
+ return true;
4064
+ } catch (error2) {
4065
+ return error2.code === "EPERM";
4066
+ }
4067
+ }
4068
+ function probeSocket(socketPath, timeoutMs = 300) {
4069
+ return new Promise((resolve) => {
4070
+ try {
4071
+ if (!fs.statSync(socketPath).isSocket()) {
4072
+ resolve("absent");
4073
+ return;
4074
+ }
4075
+ } catch {
4076
+ resolve("absent");
4077
+ return;
4078
+ }
4079
+ let settled = false;
4080
+ const finish = (state) => {
4081
+ if (settled)
4082
+ return;
4083
+ settled = true;
4084
+ clearTimeout(timer);
4085
+ socket.destroy();
4086
+ resolve(state);
4087
+ };
4088
+ const socket = net.createConnection(socketPath);
4089
+ const timer = setTimeout(() => finish("unreachable"), timeoutMs);
4090
+ socket.on("connect", () => finish("listening"));
4091
+ socket.on("error", (error2) => finish(error2.code === "ECONNREFUSED" || error2.code === "ENOENT" ? "stale" : "unreachable"));
4092
+ });
4093
+ }
4094
+ }
4095
+ });
4096
+
4097
+ // ../packages/tool-kit/out/liveBus.js
4098
+ var require_liveBus = __commonJS({
4099
+ "../packages/tool-kit/out/liveBus.js"(exports) {
4100
+ "use strict";
4101
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4102
+ if (k2 === void 0) k2 = k;
4103
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4104
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4105
+ desc = { enumerable: true, get: function() {
4106
+ return m[k];
4107
+ } };
4108
+ }
4109
+ Object.defineProperty(o, k2, desc);
4110
+ } : function(o, m, k, k2) {
4111
+ if (k2 === void 0) k2 = k;
4112
+ o[k2] = m[k];
4113
+ });
4114
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4115
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4116
+ } : function(o, v) {
4117
+ o["default"] = v;
4118
+ });
4119
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4120
+ var ownKeys = function(o) {
4121
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4122
+ var ar = [];
4123
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4124
+ return ar;
4125
+ };
4126
+ return ownKeys(o);
4127
+ };
4128
+ return function(mod) {
4129
+ if (mod && mod.__esModule) return mod;
4130
+ var result = {};
4131
+ if (mod != null) {
4132
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4133
+ }
4134
+ __setModuleDefault(result, mod);
4135
+ return result;
4136
+ };
4137
+ }();
4138
+ Object.defineProperty(exports, "__esModule", { value: true });
4139
+ exports.SAVER_HOST_BUNDLE_ID = exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
4140
+ exports.liveBusSocketCandidates = liveBusSocketCandidates;
4141
+ exports.existingSocketCandidates = existingSocketCandidates;
4142
+ exports.liveBusSocketPath = liveBusSocketPath;
4143
+ exports.bucketPromptSize = bucketPromptSize;
4144
+ exports.emitLiveSignal = emitLiveSignal;
4145
+ exports.deliverLine = deliverLine;
4146
+ var fs = __importStar(__require("fs"));
4147
+ var net = __importStar(__require("net"));
4148
+ var os = __importStar(__require("os"));
4149
+ var path = __importStar(__require("path"));
4150
+ var hookSet_1 = require_hookSet();
4151
+ var saverHandoff_1 = require_saverHandoff();
4152
+ var WRITE_TIMEOUT_MS = 50;
4153
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
4154
+ var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
4155
+ exports.SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4156
+ function liveBusSocketCandidates() {
4157
+ const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4158
+ if (override)
4159
+ return [override];
4160
+ const home = os.homedir();
4161
+ return [
4162
+ path.join(home, ".ascenda", "live.sock"),
4163
+ path.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4164
+ path.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4165
+ ];
4166
+ }
4167
+ function existingSocketCandidates() {
4168
+ const candidates = liveBusSocketCandidates();
4169
+ if (process.env.ASCENDA_LIVE_BUS_SOCKET)
4170
+ return candidates;
4171
+ return candidates.filter((candidate) => {
4172
+ try {
4173
+ return fs.statSync(candidate).isSocket();
4174
+ } catch {
4175
+ return false;
4176
+ }
4177
+ });
4178
+ }
4179
+ function liveBusSocketPath() {
4180
+ return existingSocketCandidates()[0] ?? liveBusSocketCandidates()[0];
4181
+ }
4182
+ function bucketPromptSize(text) {
4183
+ const length = typeof text === "string" ? text.length : 0;
4184
+ if (length <= 280)
4185
+ return "s";
4186
+ if (length <= 2e3)
4187
+ return "m";
4188
+ if (length <= 8e3)
4189
+ return "l";
4190
+ return "xl";
4191
+ }
4192
+ var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4193
+ function onTheWire(signal) {
4194
+ const out = { ...signal };
4195
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4196
+ delete out.hookSet;
4197
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4198
+ delete out.viaPlugin;
4199
+ return out;
4200
+ }
4201
+ function emitLiveSignal(signal) {
4202
+ const wire = onTheWire(signal);
4203
+ return deliverLine(`${JSON.stringify(wire)}
4204
+ `).then((delivered) => {
4205
+ if (!delivered)
4206
+ (0, saverHandoff_1.holdForSaver)(wire);
4207
+ });
4208
+ }
4209
+ function deliverLine(line) {
4210
+ return new Promise((resolve) => {
4211
+ const candidates = existingSocketCandidates();
4212
+ if (candidates.length === 0) {
4213
+ resolve(void 0);
4214
+ return;
4215
+ }
4216
+ let settled = false;
4217
+ let accepted;
4218
+ let socket;
4219
+ const drop = () => {
4220
+ try {
4221
+ socket?.destroy();
4222
+ } catch {
4223
+ }
4224
+ socket = void 0;
4225
+ };
4226
+ const done = () => {
4227
+ if (settled)
4228
+ return;
4229
+ settled = true;
4230
+ clearTimeout(timer);
4231
+ drop();
4232
+ resolve(accepted);
4233
+ };
4234
+ const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4235
+ const tryFrom = (index) => {
4236
+ if (settled)
4237
+ return;
4238
+ if (index >= candidates.length) {
4239
+ done();
4240
+ return;
4241
+ }
4242
+ let attempt;
4243
+ try {
4244
+ attempt = net.createConnection(candidates[index]);
4245
+ } catch {
4246
+ tryFrom(index + 1);
4247
+ return;
4248
+ }
4249
+ socket = attempt;
4250
+ if (typeof attempt.unref === "function")
4251
+ attempt.unref();
4252
+ let connected = false;
4253
+ attempt.on("error", (error2) => {
4254
+ if (settled || socket !== attempt)
4255
+ return;
4256
+ if (!connected && error2.code && NOBODY_LISTENING.has(error2.code)) {
4257
+ drop();
4258
+ tryFrom(index + 1);
4259
+ return;
4260
+ }
4261
+ done();
4262
+ });
4263
+ attempt.on("connect", () => {
4264
+ if (settled || socket !== attempt)
4265
+ return;
4266
+ connected = true;
4267
+ accepted = candidates[index];
4268
+ try {
4269
+ attempt.write(line, done);
4270
+ } catch {
4271
+ done();
4272
+ }
4273
+ });
4274
+ };
4275
+ tryFrom(0);
4276
+ });
4277
+ }
4278
+ }
4279
+ });
4280
+
4281
+ // ../packages/tool-kit/out/terminalStyle.js
4282
+ var require_terminalStyle = __commonJS({
4283
+ "../packages/tool-kit/out/terminalStyle.js"(exports) {
4284
+ "use strict";
4285
+ Object.defineProperty(exports, "__esModule", { value: true });
4286
+ exports.colourEnabled = colourEnabled;
4287
+ exports.terminalStyle = terminalStyle;
4288
+ function colourEnabled(stream = process.stdout, env = process.env) {
4289
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "")
4290
+ return false;
4291
+ if (env.FORCE_COLOR !== void 0)
4292
+ return env.FORCE_COLOR !== "0";
4293
+ if (env.TERM === "dumb")
4294
+ return false;
4295
+ return Boolean(stream.isTTY);
4296
+ }
4297
+ function terminalStyle(enabled = colourEnabled()) {
4298
+ const wrap = (open, close) => (text) => enabled ? `\x1B[${open}m${text}\x1B[${close}m` : text;
4299
+ const bold = wrap(1, 22);
4300
+ const dim = wrap(2, 22);
4301
+ const green = wrap(32, 39);
4302
+ const yellow = wrap(33, 39);
4303
+ const red = wrap(31, 39);
4304
+ const cyan = wrap(36, 39);
4305
+ const colour = { ok: green, warn: yellow, bad: red, info: dim };
4306
+ const marks = { ok: "\u2713", warn: "!", bad: "\u2717", info: "\xB7" };
4307
+ return {
4308
+ enabled,
4309
+ bold,
4310
+ dim,
4311
+ green,
4312
+ yellow,
4313
+ red,
4314
+ cyan,
4315
+ mark: (tone) => colour[tone](marks[tone]),
4316
+ tone: (tone, text) => colour[tone](text)
4317
+ };
4318
+ }
4319
+ }
4320
+ });
4321
+
4322
+ // ../packages/tool-kit/out/liveSignalDoctor.js
4323
+ var require_liveSignalDoctor = __commonJS({
4324
+ "../packages/tool-kit/out/liveSignalDoctor.js"(exports) {
4325
+ "use strict";
4326
+ Object.defineProperty(exports, "__esModule", { value: true });
4327
+ exports.DOCTOR_VALUE_COLUMN = void 0;
4328
+ exports.doctorRow = doctorRow;
4329
+ exports.liveSignalDoctorLines = liveSignalDoctorLines;
4330
+ var hookRunner_1 = require_hookRunner();
4331
+ var liveBus_1 = require_liveBus();
4332
+ var saverHandoff_1 = require_saverHandoff();
4333
+ var terminalStyle_1 = require_terminalStyle();
4334
+ exports.DOCTOR_VALUE_COLUMN = 25;
4335
+ function doctorRow(ui, tone, label, value) {
4336
+ return ` ${ui.mark(tone)} ${label.padEnd(exports.DOCTOR_VALUE_COLUMN - 5)} ${value}`;
4337
+ }
4338
+ async function liveSignalDoctorLines(options) {
4339
+ const ui = options.ui ?? (0, terminalStyle_1.terminalStyle)();
4340
+ const lines = [` ${ui.bold("Live signal")} ${ui.dim("(this machine; needs no pairing)")}`];
4341
+ const now = Date.now();
4342
+ let problems = 0;
4343
+ const row = (tone, label, value) => {
4344
+ if (tone === "bad" || tone === "warn")
4345
+ problems += 1;
4346
+ lines.push(doctorRow(ui, tone, label, tone === "bad" ? ui.red(value) : value));
4347
+ };
4348
+ const more = (value) => lines.push(`${" ".repeat(exports.DOCTOR_VALUE_COLUMN)}${value}`);
4349
+ if (options.launcher && process.platform !== "win32") {
4350
+ const node = (0, hookRunner_1.resolveHookNode)(options.launcher);
4351
+ if (node.problem)
4352
+ row("bad", "Node", `${node.problem}. Install Node 20 or newer, then run setup again`);
4353
+ else
4354
+ row("ok", "Node", `${node.node} ${ui.dim(`(${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`)}`);
4355
+ }
4356
+ if (options.registrations.length === 0)
4357
+ row("bad", "Hooks", `not registered. Run: ${options.setupCommand}`);
4358
+ for (const entry of options.registrations) {
4359
+ const where = entry.homeProject ? `loads only when ${options.displayName} starts in the home folder. Run setup again to move it to every project` : entry.scope === "user" ? "every project" : "this project only";
4360
+ const complete = entry.registered === options.eventCount;
4361
+ row(entry.homeProject || !complete ? "warn" : entry.scope === "user" ? "ok" : "info", "Hooks", `${entry.registered}/${options.eventCount} in ${entry.file} ${ui.dim(`(${where})`)}`);
4362
+ }
4363
+ if (options.registrations.length > 1) {
4364
+ problems += 1;
4365
+ more(ui.yellow("Registered in more than one file, so each event runs more than once. Run setup again to fix."));
4366
+ }
4367
+ const last = (0, hookRunner_1.readLastHook)(options.tool);
4368
+ if (last)
4369
+ row("ok", "Last hook", `${last.event}, ${(0, hookRunner_1.describeAge)(now - Date.parse(last.at))}`);
4370
+ else
4371
+ row("info", "Last hook", `none yet. Start ${options.displayName} (restart it if it was open during setup)${options.lookHint ? `, then ${options.lookHint}` : ""}`);
4372
+ const [appSocket, appContainerSocket, saverSocket] = (0, liveBus_1.liveBusSocketCandidates)();
4373
+ const appState = await (0, saverHandoff_1.probeSocket)(appSocket);
4374
+ const legacyState = appContainerSocket ? await (0, saverHandoff_1.probeSocket)(appContainerSocket) : "absent";
4375
+ if (appState === "listening" || legacyState === "listening")
4376
+ row("ok", "Desktop app", "listening. It takes every signal, and the saver mirrors it");
4377
+ else
4378
+ row("info", "Desktop app", "not listening");
4379
+ const saverState = saverSocket ? await (0, saverHandoff_1.probeSocket)(saverSocket) : "absent";
4380
+ const live = (0, saverHandoff_1.readSaverStatuses)(now).filter((status) => status.alive);
4381
+ const holder = live.find((status) => status.ownsBus);
4382
+ const saver = describeSaver(saverState, holder, live);
4383
+ row(saver.tone, "Screen saver", saver.text);
4384
+ for (const status of live)
4385
+ more(ui.dim(describeProcess(status, now)));
4386
+ const held = (0, saverHandoff_1.heldForSaver)(now);
4387
+ if (held.count > 0) {
4388
+ row("info", "Held for the saver", `${held.count} session${held.count === 1 ? "" : "s"}, newest ${(0, hookRunner_1.describeAge)(held.newestAgeMs ?? 0)}. Replayed when the saver starts`);
4389
+ }
4390
+ const trip = await pingRoundTrip(saverSocket, options.selfCommand);
4391
+ row(trip.tone, "Round trip", trip.text);
4392
+ lines.push("");
4393
+ lines.push(problems === 0 ? ` ${ui.mark("ok")} ${ui.bold("Ready.")} The hooks can run, and the screen saver hears them while it's on screen.` : ` ${ui.mark("bad")} ${ui.bold(`${problems} problem${problems === 1 ? "" : "s"} above.`)} Each line says how to fix it.`);
4394
+ return lines;
4395
+ }
4396
+ function describeSaver(state, holder, live) {
4397
+ if (state === "listening") {
4398
+ if (!holder)
4399
+ return { tone: "warn", text: "listening, from a process that isn't reporting. Restart it: killall legacyScreenSaver" };
4400
+ if (holder.saverViews === 0) {
4401
+ return { tone: "bad", text: `pid ${holder.pid} holds the socket but isn't drawing the saver, so signals go nowhere you can see. Fix: killall legacyScreenSaver` };
4402
+ }
4403
+ return { tone: "ok", text: `listening, pid ${holder.pid}, on screen` };
4404
+ }
4405
+ if (state === "stale")
4406
+ return { tone: "info", text: "not running (a socket file was left behind, which is harmless)" };
4407
+ if (live.some((status) => status.previewViews > 0)) {
4408
+ return { tone: "info", text: "not running. The System Settings preview never listens, so it stays still; the water goes live once the saver itself runs" };
4409
+ }
4410
+ return { tone: "info", text: "not running. That's normal: it listens only while it's on screen" };
4411
+ }
4412
+ function describeProcess(status, now) {
4413
+ const what = [
4414
+ status.saverViews > 0 ? `saver on ${status.saverViews} display${status.saverViews === 1 ? "" : "s"}` : void 0,
4415
+ status.previewViews > 0 ? "preview" : void 0
4416
+ ].filter(Boolean).join(" + ") || "not drawing";
4417
+ const heard = status.lastSignalAt ? `last signal ${status.lastSignalEvent ?? ""} ${(0, hookRunner_1.describeAge)(now - Date.parse(status.lastSignalAt))}`.replace(/\s+/g, " ") : "no signal yet";
4418
+ const replay = status.replayed > 0 ? `, replayed ${status.replayed} since this process started` : "";
4419
+ const beat = status.ageMs > 1e4 ? `, heartbeat ${(0, hookRunner_1.describeAge)(status.ageMs)} (not animating)` : "";
4420
+ return `pid ${status.pid} ${status.version ?? ""}: ${what}, ${status.mode ?? "?"}${status.ownsBus ? ", owns the socket" : ""}, ${heard}${replay}${beat}`.replace(/\s+:/, ":");
4421
+ }
4422
+ async function pingRoundTrip(saverSocket, selfCommand) {
4423
+ const session = `doctor-${process.pid}-${Date.now()}`;
4424
+ const accepted = await (0, liveBus_1.deliverLine)(`${JSON.stringify({ tool: "doctor", session, event: "ping" })}
4425
+ `);
4426
+ if (!accepted) {
4427
+ return { tone: "info", text: `nobody is listening right now, so there is nothing to test. To test the saver: open -a ScreenSaverEngine; sleep 5; ${selfCommand} doctor` };
4428
+ }
4429
+ if (accepted !== saverSocket)
4430
+ return { tone: "ok", text: `the desktop app took it (${accepted})` };
4431
+ for (let waited = 0; waited < 2e3; waited += 100) {
4432
+ await new Promise((resolve) => setTimeout(resolve, 100));
4433
+ const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
4434
+ if (answered)
4435
+ return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
4436
+ }
4437
+ return { tone: "bad", text: "the saver's socket took the ping but no saver reported it. It may be a version from before 0.8.1, or stuck. Fix: killall legacyScreenSaver" };
4438
+ }
4439
+ }
4440
+ });
4441
+
3677
4442
  // ../packages/tool-kit/out/studyNotices.js
3678
4443
  var require_studyNotices = __commonJS({
3679
4444
  "../packages/tool-kit/out/studyNotices.js"(exports) {
@@ -3923,10 +4688,12 @@ var require_cliAgentSetup = __commonJS({
3923
4688
  Object.defineProperty(exports, "__esModule", { value: true });
3924
4689
  exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
3925
4690
  exports.cliAgentHookBinPath = cliAgentHookBinPath;
4691
+ exports.cliAgentSelfCommand = cliAgentSelfCommand;
3926
4692
  exports.runCliAgentSetup = runCliAgentSetup;
3927
4693
  exports.writeHookSettings = writeHookSettings;
3928
4694
  exports.registeredHookSets = registeredHookSets;
3929
4695
  exports.findStaleHookCommands = findStaleHookCommands;
4696
+ exports.cliAgentRegistrations = cliAgentRegistrations;
3930
4697
  var crypto = __importStar(__require("crypto"));
3931
4698
  var fs = __importStar(__require("fs"));
3932
4699
  var os = __importStar(__require("os"));
@@ -3938,22 +4705,29 @@ var require_cliAgentSetup = __commonJS({
3938
4705
  var hookSet_1 = require_hookSet();
3939
4706
  var initiatives_1 = require_initiatives();
3940
4707
  var setupDisclosure_1 = require_setupDisclosure();
4708
+ var hookRunner_1 = require_hookRunner();
4709
+ var liveSignalDoctor_1 = require_liveSignalDoctor();
3941
4710
  var stateStore_1 = require_stateStore();
3942
4711
  var studyJoin_1 = require_studyJoin();
3943
4712
  var studyNotices_1 = require_studyNotices();
4713
+ var terminalStyle_1 = require_terminalStyle();
3944
4714
  var tokenStore_1 = require_tokenStore();
3945
- var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "join", "object", "-h", "--help"]);
4715
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "doctor", "join", "object", "-h", "--help"]);
3946
4716
  function isCliAgentManagementCommand(argument) {
3947
4717
  return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
3948
4718
  }
3949
4719
  function cliAgentHookBinPath(binaryName) {
3950
- return path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
4720
+ return (0, hookRunner_1.hookRunnerPaths)(binaryName).launcher;
4721
+ }
4722
+ function cliAgentSelfCommand(spec) {
4723
+ return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os.homedir());
3951
4724
  }
3952
4725
  function usage(spec) {
3953
4726
  return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
3954
4727
 
3955
4728
  npx ${spec.packageName} setup [options]
3956
4729
  npx ${spec.packageName} status
4730
+ npx ${spec.packageName} doctor
3957
4731
  npx ${spec.packageName} uninstall
3958
4732
  npx ${spec.packageName} join <code>
3959
4733
  npx ${spec.packageName} object <purpose> [--undo]
@@ -3964,7 +4738,7 @@ Options
3964
4738
  --tool-installation-id <id> reuse an existing pairing instead of creating one
3965
4739
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3966
4740
  --no-pair install without pairing: local features on, nothing sent
3967
- --scope project|user where hooks are registered (default project)
4741
+ --scope user|project where hooks are registered (default user: every project)
3968
4742
  --project-dir <path> project root for --scope project (default cwd)
3969
4743
  --dry-run print what would change, write nothing
3970
4744
  -h, --help
@@ -3990,29 +4764,26 @@ Options
3990
4764
  return await printStatus(options, spec);
3991
4765
  if (options.action === "uninstall")
3992
4766
  return uninstall(options, spec);
4767
+ if (options.action === "doctor")
4768
+ return await runDoctor(options, spec);
3993
4769
  const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3994
- console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
3995
- console.log(`
3996
- ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
3997
- `);
4770
+ const ui = (0, terminalStyle_1.terminalStyle)();
4771
+ const row = (tone, label, value) => console.log(` ${ui.mark(tone)} ${label.padEnd(12)} ${value}`);
4772
+ const detail = (label, value) => console.log(ui.dim(` ${label.padEnd(12)} ${value}`));
4773
+ console.log(`${ui.bold("Ascenda setup")} ${ui.dim(`\xB7 ${spec.displayName} \xB7 ${apiBaseUrl}`)}`);
4774
+ if (!options.skipPairing)
4775
+ console.log(`
4776
+ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}`);
4777
+ console.log("");
3998
4778
  let identity;
3999
- let unpairedReason;
4000
- if (options.skipPairing) {
4001
- unpairedReason = "asked not to pair (--no-pair)";
4002
- } else {
4779
+ if (!options.skipPairing)
4003
4780
  identity = await resolveIdentity(apiBaseUrl, options, spec);
4004
- if (identity) {
4005
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
4006
- } else {
4007
- unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
4008
- }
4009
- }
4010
- if (unpairedReason) {
4011
- console.log(` pairing none: ${unpairedReason}`);
4012
- console.log(" local features on, nothing is sent");
4013
- }
4014
4781
  const binary = installBinary(spec, options.dryRun);
4015
- console.log(` hook binary ${binary}`);
4782
+ const node = options.dryRun || process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
4783
+ if (node?.problem)
4784
+ row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
4785
+ else
4786
+ row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
4016
4787
  if (!options.dryRun) {
4017
4788
  const now = (/* @__PURE__ */ new Date()).toISOString();
4018
4789
  const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto.randomUUID()}`;
@@ -4022,31 +4793,76 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4022
4793
  ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4023
4794
  });
4024
4795
  }
4025
- console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
4796
+ if (isHomeProject(options)) {
4797
+ detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
4798
+ options.scope = "user";
4799
+ }
4026
4800
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4027
4801
  const before = registeredHookSets(readSettings(settingsFile), spec);
4028
4802
  const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
4029
4803
  if (written === null)
4030
4804
  return 1;
4031
- console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
4805
+ const reach = options.scope === "user" ? "every project" : "this project only";
4806
+ row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
4032
4807
  const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4033
4808
  if (changes)
4034
- console.log(` ${changes}`);
4809
+ detail("", changes);
4810
+ const otherFile = spec.settings.settingsPath(options.scope === "user" ? "project" : "user", options.projectDir);
4811
+ if (otherFile !== settingsFile && registeredHookSets(readSettings(otherFile), spec).size > 0) {
4812
+ if (options.dryRun) {
4813
+ row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os.homedir())}, so each event runs once`);
4814
+ } else if (removeOurHookEntries(otherFile, spec)) {
4815
+ row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
4816
+ } else {
4817
+ row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os.homedir())} registers these hooks too, so each event runs twice.`);
4818
+ detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
4819
+ }
4820
+ }
4821
+ const chosenLocal = options.skipPairing;
4822
+ if (identity)
4823
+ row("ok", "pairing", `${identity.toolInstallationId}${ui.dim(identity.paired ? " (new)" : " (existing)")}`);
4824
+ else if (chosenLocal)
4825
+ row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
4826
+ else
4827
+ row("warn", "pairing", "not paired: pairing did not finish");
4828
+ detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os.homedir())} (tools.${spec.host})`);
4035
4829
  if (options.dryRun) {
4036
- console.log("\nDry run \u2014 nothing was written.");
4830
+ console.log("\nDry run. Nothing was written.");
4037
4831
  return 0;
4038
4832
  }
4039
- console.log(`
4040
- Done. ${spec.restartHint}`);
4041
- if (!identity) {
4042
- console.log(`Pair later: npx ${spec.packageName} setup`);
4833
+ const self = cliAgentSelfCommand(spec);
4834
+ const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
4835
+ console.log("");
4836
+ if (chosenLocal) {
4837
+ console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
4838
+ console.log(" They run on this machine and need no account or pairing.");
4839
+ } else if (!identity) {
4840
+ console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
4841
+ console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
4842
+ } else {
4843
+ console.log(`${ui.mark("ok")} ${ui.bold("Done.")} Paired, and the hooks are installed.`);
4844
+ }
4845
+ console.log("");
4846
+ next("Next", spec.restartHint);
4847
+ next("Check", ui.cyan(`${self} doctor`));
4848
+ if (!identity)
4849
+ next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} setup`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
4850
+ if (chosenLocal) {
4851
+ console.log("");
4852
+ console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
4853
+ console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
4854
+ console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
4855
+ console.log("");
4856
+ console.log(ui.dim((0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName }).split("\n").map((line) => ` ${line}`).join("\n")));
4043
4857
  }
4044
- console.log(`Check anytime: npx ${spec.packageName} status`);
4045
4858
  return 0;
4046
4859
  }
4860
+ function isHomeProject(options) {
4861
+ return options.scope === "project" && path.resolve(options.projectDir) === path.resolve(os.homedir());
4862
+ }
4047
4863
  function parseArgs(argv, spec) {
4048
4864
  const options = {
4049
- scope: "project",
4865
+ scope: "user",
4050
4866
  projectDir: process.cwd(),
4051
4867
  dryRun: false,
4052
4868
  skipPairing: false,
@@ -4071,6 +4887,9 @@ Done. ${spec.restartHint}`);
4071
4887
  case "uninstall":
4072
4888
  options.action = "uninstall";
4073
4889
  break;
4890
+ case "doctor":
4891
+ options.action = "doctor";
4892
+ break;
4074
4893
  case "--api-base-url":
4075
4894
  options.apiBaseUrl = next();
4076
4895
  break;
@@ -4228,17 +5047,7 @@ Pairing ${status.status}. Run setup again.`);
4228
5047
  return void 0;
4229
5048
  }
4230
5049
  function installBinary(spec, dryRun) {
4231
- const target = cliAgentHookBinPath(spec.binaryName);
4232
- if (dryRun)
4233
- return target;
4234
- const source = process.argv[1];
4235
- fs.mkdirSync(path.dirname(target), { recursive: true });
4236
- if (path.resolve(source) !== path.resolve(target)) {
4237
- fs.copyFileSync(source, target);
4238
- }
4239
- if (process.platform !== "win32")
4240
- fs.chmodSync(target, 493);
4241
- return target;
5050
+ return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
4242
5051
  }
4243
5052
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
4244
5053
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -4279,7 +5088,7 @@ ${serialised}`);
4279
5088
  return true;
4280
5089
  }
4281
5090
  function hookCommand(binary, spec) {
4282
- return `"${process.execPath}" "${binary}"${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
5091
+ return `${(0, hookRunner_1.hookRunnerCommand)(binary)}${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
4283
5092
  }
4284
5093
  function registeredHookSets(settings, spec) {
4285
5094
  const sets = /* @__PURE__ */ new Map();
@@ -4332,7 +5141,18 @@ ${serialised}`);
4332
5141
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
4333
5142
  console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
4334
5143
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
5144
+ const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
5145
+ if (node) {
5146
+ console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
5147
+ }
5148
+ const last = (0, hookRunner_1.readLastHook)(spec.host);
5149
+ console.log(last ? `last hook ${last.event}, ${(0, hookRunner_1.describeAge)(Date.now() - Date.parse(last.at))}` : `last hook \u2014 none has run yet. Start ${spec.displayName} (restart it if it was open during setup)`);
4335
5150
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
5151
+ const otherScope = options.scope === "user" ? "project" : "user";
5152
+ const otherFile = spec.settings.settingsPath(otherScope, options.projectDir);
5153
+ const elsewhere = registered === 0 && otherFile !== settingsFile ? countRegistered(readSettings(otherFile), spec) : 0;
5154
+ if (elsewhere > 0)
5155
+ console.log(` ${elsewhere}/${spec.hookEvents.length} found in ${otherFile} (--scope ${otherScope})`);
4336
5156
  if (spec.hookSet !== void 0 && registered > 0) {
4337
5157
  const sets = [...registeredHookSets(settings, spec).values()];
4338
5158
  const oldest = Math.min(...sets);
@@ -4358,38 +5178,116 @@ ${serialised}`);
4358
5178
  if (process.stdout.isTTY)
4359
5179
  await notices.markShown();
4360
5180
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
4361
- const healthy = paired && registered === spec.hookEvents.length && fs.existsSync(binary) && !stale.length;
5181
+ const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5182
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
4362
5183
  return healthy ? 0 : 1;
4363
5184
  }
5185
+ function countRegistered(settings, spec) {
5186
+ return spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs(entry, spec))).length;
5187
+ }
5188
+ function cliAgentRegistrations(spec, projectDir = process.cwd()) {
5189
+ const home = os.homedir();
5190
+ const userFile = spec.settings.settingsPath("user", projectDir);
5191
+ const projectFile = spec.settings.settingsPath("project", projectDir);
5192
+ const found = [];
5193
+ for (const [scope, file] of [["user", userFile], ["project", projectFile]]) {
5194
+ if (scope === "project" && file === userFile)
5195
+ continue;
5196
+ const registered = countRegistered(readSettings(file), spec);
5197
+ if (registered === 0)
5198
+ continue;
5199
+ found.push({
5200
+ file: (0, hookRunner_1.tidyHomePath)(file, home),
5201
+ registered,
5202
+ scope,
5203
+ homeProject: scope === "project" && path.resolve(projectDir) === path.resolve(home)
5204
+ });
5205
+ }
5206
+ return found;
5207
+ }
5208
+ async function runDoctor(options, spec) {
5209
+ const ui = (0, terminalStyle_1.terminalStyle)();
5210
+ const lines = [`${ui.bold("Ascenda doctor")} ${ui.dim(`\xB7 ${spec.displayName}`)}`, ""];
5211
+ try {
5212
+ lines.push(...await (0, liveSignalDoctor_1.liveSignalDoctorLines)({
5213
+ displayName: spec.displayName,
5214
+ tool: spec.host,
5215
+ launcher: process.platform === "win32" ? void 0 : cliAgentHookBinPath(spec.binaryName),
5216
+ registrations: cliAgentRegistrations(spec, options.projectDir),
5217
+ eventCount: spec.hookEvents.length,
5218
+ selfCommand: cliAgentSelfCommand(spec),
5219
+ setupCommand: `npx ${spec.packageName} setup`,
5220
+ ui
5221
+ }));
5222
+ } catch (error2) {
5223
+ lines.push(` Live signal (could not be checked: ${error2 instanceof Error ? error2.message : String(error2)})`);
5224
+ }
5225
+ lines.push("", ...accountLines(ui, spec));
5226
+ console.log(lines.join("\n"));
5227
+ return 0;
5228
+ }
5229
+ function accountLines(ui, spec) {
5230
+ const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5231
+ const id = credentials?.toolInstallationId;
5232
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (installationId) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(installationId)) !== void 0);
5233
+ const row = (tone, label, value) => ` ${ui.mark(tone)} ${label.padEnd(20)} ${value}`;
5234
+ if (!id || localOnly) {
5235
+ return [
5236
+ ` ${ui.bold("Account sync")} ${ui.dim("(optional; this install isn't paired)")}`,
5237
+ ...id ? [ui.dim(row("info", "Installation id", id))] : [],
5238
+ "",
5239
+ " Not paired, which is fine: the screen saver and the live view above work",
5240
+ " without it. Nothing leaves this machine and nothing is queued. To send your",
5241
+ " sessions to Ascenda's servers, so they appear in the app:",
5242
+ ` ${ui.cyan(`${cliAgentSelfCommand(spec)} setup`)}`
5243
+ ];
5244
+ }
5245
+ const token = (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim();
5246
+ const state = (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(id));
5247
+ const outcome = state?.lastOutcome;
5248
+ return [
5249
+ ` ${ui.bold("Account sync")}`,
5250
+ row("info", "Installation id", id),
5251
+ token ? row("ok", "Token", "present") : row("bad", "Token", ui.red(`missing, so nothing can be sent. Run: npx ${spec.packageName} setup`)),
5252
+ outcome ? row(outcome === "accepted" ? "ok" : "warn", "Last send", `${outcome}${state?.lastAttemptAt ? ui.dim(` (${state.lastAttemptAt})`) : ""}`) : row("info", "Last send", "none yet")
5253
+ ];
5254
+ }
5255
+ function removeOurHookEntries(settingsFile, spec) {
5256
+ if (!fs.existsSync(settingsFile))
5257
+ return true;
5258
+ try {
5259
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5260
+ const hooks = { ...settings.hooks ?? {} };
5261
+ for (const event of Object.keys(hooks)) {
5262
+ const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
5263
+ if (kept.length)
5264
+ hooks[event] = kept;
5265
+ else
5266
+ delete hooks[event];
5267
+ }
5268
+ const updated = { ...settings, hooks };
5269
+ if (!Object.keys(hooks).length)
5270
+ delete updated.hooks;
5271
+ fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5272
+ fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5273
+ `, "utf8");
5274
+ return true;
5275
+ } catch {
5276
+ return false;
5277
+ }
5278
+ }
4364
5279
  function uninstall(options, spec) {
4365
5280
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4366
5281
  if (fs.existsSync(settingsFile)) {
4367
- try {
4368
- const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
4369
- const hooks = { ...settings.hooks ?? {} };
4370
- for (const event of Object.keys(hooks)) {
4371
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
4372
- if (kept.length)
4373
- hooks[event] = kept;
4374
- else
4375
- delete hooks[event];
4376
- }
4377
- const updated = { ...settings, hooks };
4378
- if (!Object.keys(hooks).length)
4379
- delete updated.hooks;
4380
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4381
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4382
- `, "utf8");
4383
- console.log(`hooks removed from ${settingsFile}`);
4384
- } catch {
5282
+ if (!removeOurHookEntries(settingsFile, spec)) {
4385
5283
  console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
4386
5284
  return 1;
4387
5285
  }
5286
+ console.log(`hooks removed from ${settingsFile}`);
4388
5287
  }
4389
- const binary = cliAgentHookBinPath(spec.binaryName);
4390
- if (fs.existsSync(binary)) {
4391
- fs.rmSync(binary);
4392
- console.log(`removed ${binary}`);
5288
+ for (const file of (0, hookRunner_1.removeHookRunner)(spec.binaryName)) {
5289
+ if (!file.endsWith(".node") && !file.endsWith(".no-node"))
5290
+ console.log(`removed ${file}`);
4393
5291
  }
4394
5292
  if ((0, credentials_1.readHostCredentials)(spec.host)) {
4395
5293
  (0, credentials_1.removeHostCredentials)(spec.host);
@@ -4481,180 +5379,6 @@ var require_turnState = __commonJS({
4481
5379
  }
4482
5380
  });
4483
5381
 
4484
- // ../packages/tool-kit/out/liveBus.js
4485
- var require_liveBus = __commonJS({
4486
- "../packages/tool-kit/out/liveBus.js"(exports) {
4487
- "use strict";
4488
- var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4489
- if (k2 === void 0) k2 = k;
4490
- var desc = Object.getOwnPropertyDescriptor(m, k);
4491
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4492
- desc = { enumerable: true, get: function() {
4493
- return m[k];
4494
- } };
4495
- }
4496
- Object.defineProperty(o, k2, desc);
4497
- } : function(o, m, k, k2) {
4498
- if (k2 === void 0) k2 = k;
4499
- o[k2] = m[k];
4500
- });
4501
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4502
- Object.defineProperty(o, "default", { enumerable: true, value: v });
4503
- } : function(o, v) {
4504
- o["default"] = v;
4505
- });
4506
- var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4507
- var ownKeys = function(o) {
4508
- ownKeys = Object.getOwnPropertyNames || function(o2) {
4509
- var ar = [];
4510
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4511
- return ar;
4512
- };
4513
- return ownKeys(o);
4514
- };
4515
- return function(mod) {
4516
- if (mod && mod.__esModule) return mod;
4517
- var result = {};
4518
- if (mod != null) {
4519
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4520
- }
4521
- __setModuleDefault(result, mod);
4522
- return result;
4523
- };
4524
- }();
4525
- Object.defineProperty(exports, "__esModule", { value: true });
4526
- exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
4527
- exports.liveBusSocketCandidates = liveBusSocketCandidates;
4528
- exports.liveBusSocketPath = liveBusSocketPath;
4529
- exports.bucketPromptSize = bucketPromptSize;
4530
- exports.emitLiveSignal = emitLiveSignal;
4531
- var fs = __importStar(__require("fs"));
4532
- var net = __importStar(__require("net"));
4533
- var os = __importStar(__require("os"));
4534
- var path = __importStar(__require("path"));
4535
- var hookSet_1 = require_hookSet();
4536
- var WRITE_TIMEOUT_MS = 50;
4537
- exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
4538
- var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
4539
- var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
4540
- function liveBusSocketCandidates() {
4541
- const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
4542
- if (override)
4543
- return [override];
4544
- const home = os.homedir();
4545
- return [
4546
- path.join(home, ".ascenda", "live.sock"),
4547
- path.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4548
- path.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4549
- ];
4550
- }
4551
- function existingSocketCandidates() {
4552
- const candidates = liveBusSocketCandidates();
4553
- if (process.env.ASCENDA_LIVE_BUS_SOCKET)
4554
- return candidates;
4555
- return candidates.filter((candidate) => {
4556
- try {
4557
- return fs.statSync(candidate).isSocket();
4558
- } catch {
4559
- return false;
4560
- }
4561
- });
4562
- }
4563
- function liveBusSocketPath() {
4564
- return existingSocketCandidates()[0] ?? liveBusSocketCandidates()[0];
4565
- }
4566
- function bucketPromptSize(text) {
4567
- const length = typeof text === "string" ? text.length : 0;
4568
- if (length <= 280)
4569
- return "s";
4570
- if (length <= 2e3)
4571
- return "m";
4572
- if (length <= 8e3)
4573
- return "l";
4574
- return "xl";
4575
- }
4576
- var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4577
- function onTheWire(signal) {
4578
- const out = { ...signal };
4579
- if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4580
- delete out.hookSet;
4581
- if ("viaPlugin" in out && out.viaPlugin !== true)
4582
- delete out.viaPlugin;
4583
- return out;
4584
- }
4585
- function emitLiveSignal(signal) {
4586
- return new Promise((resolve) => {
4587
- const candidates = existingSocketCandidates();
4588
- if (candidates.length === 0) {
4589
- resolve();
4590
- return;
4591
- }
4592
- let settled = false;
4593
- let socket;
4594
- const drop = () => {
4595
- try {
4596
- socket?.destroy();
4597
- } catch {
4598
- }
4599
- socket = void 0;
4600
- };
4601
- const done = () => {
4602
- if (settled)
4603
- return;
4604
- settled = true;
4605
- clearTimeout(timer);
4606
- drop();
4607
- resolve();
4608
- };
4609
- const timer = setTimeout(done, WRITE_TIMEOUT_MS);
4610
- if (typeof timer.unref === "function")
4611
- timer.unref();
4612
- const tryFrom = (index) => {
4613
- if (settled)
4614
- return;
4615
- if (index >= candidates.length) {
4616
- done();
4617
- return;
4618
- }
4619
- let attempt;
4620
- try {
4621
- attempt = net.createConnection(candidates[index]);
4622
- } catch {
4623
- tryFrom(index + 1);
4624
- return;
4625
- }
4626
- socket = attempt;
4627
- if (typeof attempt.unref === "function")
4628
- attempt.unref();
4629
- let connected = false;
4630
- attempt.on("error", (error2) => {
4631
- if (settled || socket !== attempt)
4632
- return;
4633
- if (!connected && error2.code && NOBODY_LISTENING.has(error2.code)) {
4634
- drop();
4635
- tryFrom(index + 1);
4636
- return;
4637
- }
4638
- done();
4639
- });
4640
- attempt.on("connect", () => {
4641
- if (settled || socket !== attempt)
4642
- return;
4643
- connected = true;
4644
- try {
4645
- attempt.write(`${JSON.stringify(onTheWire(signal))}
4646
- `, done);
4647
- } catch {
4648
- done();
4649
- }
4650
- });
4651
- };
4652
- tryFrom(0);
4653
- });
4654
- }
4655
- }
4656
- });
4657
-
4658
5382
  // ../packages/tool-kit/out/agentProcess.js
4659
5383
  var require_agentProcess = __commonJS({
4660
5384
  "../packages/tool-kit/out/agentProcess.js"(exports) {
@@ -4801,7 +5525,8 @@ var require_out2 = __commonJS({
4801
5525
  Object.defineProperty(exports, "__esModule", { value: true });
4802
5526
  exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
4803
5527
  exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = void 0;
4804
- exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
5528
+ exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
5529
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = void 0;
4805
5530
  var commandClassifier_1 = require_commandClassifier();
4806
5531
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
4807
5532
  return commandClassifier_1.classifyCommand;
@@ -5151,6 +5876,9 @@ var require_out2 = __commonJS({
5151
5876
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
5152
5877
  return liveBus_1.emitLiveSignal;
5153
5878
  } });
5879
+ Object.defineProperty(exports, "deliverLine", { enumerable: true, get: function() {
5880
+ return liveBus_1.deliverLine;
5881
+ } });
5154
5882
  Object.defineProperty(exports, "bucketPromptSize", { enumerable: true, get: function() {
5155
5883
  return liveBus_1.bucketPromptSize;
5156
5884
  } });
@@ -5163,6 +5891,85 @@ var require_out2 = __commonJS({
5163
5891
  Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5164
5892
  return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5165
5893
  } });
5894
+ var saverHandoff_1 = require_saverHandoff();
5895
+ Object.defineProperty(exports, "holdForSaver", { enumerable: true, get: function() {
5896
+ return saverHandoff_1.holdForSaver;
5897
+ } });
5898
+ Object.defineProperty(exports, "heldForSaver", { enumerable: true, get: function() {
5899
+ return saverHandoff_1.heldForSaver;
5900
+ } });
5901
+ Object.defineProperty(exports, "probeSocket", { enumerable: true, get: function() {
5902
+ return saverHandoff_1.probeSocket;
5903
+ } });
5904
+ Object.defineProperty(exports, "readSaverStatuses", { enumerable: true, get: function() {
5905
+ return saverHandoff_1.readSaverStatuses;
5906
+ } });
5907
+ Object.defineProperty(exports, "saverContainerDir", { enumerable: true, get: function() {
5908
+ return saverHandoff_1.saverContainerDir;
5909
+ } });
5910
+ Object.defineProperty(exports, "saverReplayPath", { enumerable: true, get: function() {
5911
+ return saverHandoff_1.saverReplayPath;
5912
+ } });
5913
+ Object.defineProperty(exports, "saverStatusDir", { enumerable: true, get: function() {
5914
+ return saverHandoff_1.saverStatusDir;
5915
+ } });
5916
+ Object.defineProperty(exports, "saverSupportDir", { enumerable: true, get: function() {
5917
+ return saverHandoff_1.saverSupportDir;
5918
+ } });
5919
+ Object.defineProperty(exports, "SAVER_REPLAY_WINDOW_MS", { enumerable: true, get: function() {
5920
+ return saverHandoff_1.SAVER_REPLAY_WINDOW_MS;
5921
+ } });
5922
+ var terminalStyle_1 = require_terminalStyle();
5923
+ Object.defineProperty(exports, "colourEnabled", { enumerable: true, get: function() {
5924
+ return terminalStyle_1.colourEnabled;
5925
+ } });
5926
+ Object.defineProperty(exports, "terminalStyle", { enumerable: true, get: function() {
5927
+ return terminalStyle_1.terminalStyle;
5928
+ } });
5929
+ var hookRunner_1 = require_hookRunner();
5930
+ Object.defineProperty(exports, "describeAge", { enumerable: true, get: function() {
5931
+ return hookRunner_1.describeAge;
5932
+ } });
5933
+ Object.defineProperty(exports, "hookLauncherScript", { enumerable: true, get: function() {
5934
+ return hookRunner_1.hookLauncherScript;
5935
+ } });
5936
+ Object.defineProperty(exports, "hookRunnerCommand", { enumerable: true, get: function() {
5937
+ return hookRunner_1.hookRunnerCommand;
5938
+ } });
5939
+ Object.defineProperty(exports, "hookRunnerPaths", { enumerable: true, get: function() {
5940
+ return hookRunner_1.hookRunnerPaths;
5941
+ } });
5942
+ Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
5943
+ return hookRunner_1.installHookRunner;
5944
+ } });
5945
+ Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
5946
+ return hookRunner_1.lastHookPath;
5947
+ } });
5948
+ Object.defineProperty(exports, "readLastHook", { enumerable: true, get: function() {
5949
+ return hookRunner_1.readLastHook;
5950
+ } });
5951
+ Object.defineProperty(exports, "removeHookRunner", { enumerable: true, get: function() {
5952
+ return hookRunner_1.removeHookRunner;
5953
+ } });
5954
+ Object.defineProperty(exports, "resolveHookNode", { enumerable: true, get: function() {
5955
+ return hookRunner_1.resolveHookNode;
5956
+ } });
5957
+ Object.defineProperty(exports, "stampLastHook", { enumerable: true, get: function() {
5958
+ return hookRunner_1.stampLastHook;
5959
+ } });
5960
+ Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
5961
+ return hookRunner_1.tidyHomePath;
5962
+ } });
5963
+ var liveSignalDoctor_1 = require_liveSignalDoctor();
5964
+ Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
5965
+ return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
5966
+ } });
5967
+ Object.defineProperty(exports, "doctorRow", { enumerable: true, get: function() {
5968
+ return liveSignalDoctor_1.doctorRow;
5969
+ } });
5970
+ Object.defineProperty(exports, "liveSignalDoctorLines", { enumerable: true, get: function() {
5971
+ return liveSignalDoctor_1.liveSignalDoctorLines;
5972
+ } });
5166
5973
  var hookSet_1 = require_hookSet();
5167
5974
  Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5168
5975
  return hookSet_1.HOOK_SET_FLAG;