The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(hooks): add the Beacon-managed Cline plugin and its installer
Claude3ad026768067
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b7bb7e2a..040fddce 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -55,6 +55,9 @@ jobs:- name: Check OpenCode pluginworking-directory: plugins/opencode-beaconrun: bun run check && bun test+ - name: Check Cline plugin+ working-directory: plugins/cline-beacon+ run: bun run check && bun test- name: Build embedded hooks binaryworking-directory: cli/beacon# hooks.bin is gitignored (build-time artifact). The CLI embeds it viadiff --git a/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.tsnew file mode 100644index 00000000..baf151b3--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts@@ -0,0 +1,211 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry plugin for Cline.+// Managed by beacon endpoint hooks install --harness cline.++// The argv Beacon's installer writes, as an array rather than a command line.+//+// Cline plugins run inside whichever host loaded them -- the VS Code extension host, a JetBrains+// plugin host, or the CLI -- so the hook may be spawned on Windows as readily as on macOS. An argv+// array is passed straight to the OS with no shell in between, which sidesteps quoting entirely: a+// POSIX-quoted command line is not valid in cmd.exe, and a Windows path inside double quotes is+// still expanded by bash.+const beaconArgv: string[] = ["__BEACON_ARGV__"]++const debugEnabled = process.env.BEACON_CLINE_DEBUG === "1"++// A send that has not finished in this long is abandoned. Cline awaits these handlers, so this is+// the worst case Beacon can add to a tool call.+const sendTimeoutMs = 2000++// How deep into a hook context the serializer will walk before giving up.+const maxDepth = 8++function debugLog(message: string, extra?: unknown) {+ if (!debugEnabled) return+ try {+ // eslint-disable-next-line no-console+ console.error("[beacon-cline]", message, extra ?? "")+ } catch {+ // Debug logging must stay best-effort.+ }+}++// safeClone turns a hook context into something JSON.stringify accepts.+//+// The contexts Cline passes are live SDK objects, not plain data: they carry functions, class+// instances, and parent references. JSON.stringify throws on a circular reference and on a bigint,+// and silently drops an Error to {}, so each of those is handled here rather than losing the whole+// payload to one bad field.+//+// Cycles are tracked along the current path and released on the way out, so an object that legibly+// appears twice -- the same workspace root referenced from two places -- is kept both times. A+// WeakSet that never released would drop the second occurrence as if it were a cycle.+function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {+ if (value === null) return null+ const kind = typeof value+ if (kind === "function" || kind === "symbol" || kind === "undefined") return undefined+ if (kind === "bigint") return String(value)+ if (kind !== "object") return value+ if (depth >= maxDepth) return undefined++ const object = value as object+ if (seen.has(object)) return undefined+ if (value instanceof Error) return { name: value.name, message: value.message }+ if (value instanceof Date) return value.toISOString()++ seen.add(object)+ try {+ if (Array.isArray(value)) {+ return value.map((item) => safeClone(item, depth + 1, seen))+ }+ const out: Record<string, unknown> = {}+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {+ const cloned = safeClone(nested, depth + 1, seen)+ if (cloned !== undefined) out[key] = cloned+ }+ return out+ } finally {+ seen.delete(object)+ }+}++async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {+ // Flattened before anything else sees it, so every consumer of this function is handed plain+ // data. Doing it further down, on the way into the child process, would leave a live SDK object+ // -- cycles, functions and all -- reaching whatever else is wired up here.+ const safe = safeClone(payload)++ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.cline.testSender")]+ if (typeof testSender === "function") {+ await (testSender as (value: unknown) => unknown)(safe)+ return+ }++ let body: string+ try {+ body = JSON.stringify(safe)+ } catch (err) {+ debugLog("payload could not be serialized", err)+ return+ }+ if (!body) return++ try {+ // Imported lazily so a host without node:child_process fails to send rather than failing to+ // load: a throwing import at module scope would surface to the user as a broken plugin.+ const { spawn } = await import("node:child_process")+ await new Promise<void>((resolve) => {+ let settled = false+ const finish = () => {+ if (settled) return+ settled = true+ resolve()+ }+ let child+ try {+ child = spawn(beaconArgv[0], beaconArgv.slice(1), {+ stdio: ["pipe", "ignore", "ignore"],+ windowsHide: true,+ })+ } catch (err) {+ debugLog("hook binary could not be spawned", err)+ finish()+ return+ }+ const timer = setTimeout(() => {+ try {+ child.kill()+ } catch {+ // Already gone.+ }+ debugLog("hook binary timed out", { type: payload?.type })+ finish()+ }, sendTimeoutMs)+ // An unreferenced timer cannot keep a CLI host alive waiting on Beacon telemetry.+ if (typeof timer.unref === "function") timer.unref()+ const done = () => {+ clearTimeout(timer)+ finish()+ }+ child.on("error", (err) => {+ debugLog("hook binary failed", err)+ done()+ })+ child.on("close", done)+ // Without this, a hook binary that exits before reading stdin turns an EPIPE into an+ // unhandled error event in the host process. Beacon telemetry must never do that.+ child.stdin?.on("error", () => {})+ try {+ child.stdin?.end(body)+ } catch (err) {+ debugLog("payload could not be written", err)+ }+ })+ } catch (err) {+ debugLog("send failed", err)+ // Beacon telemetry must never interrupt Cline execution.+ }+}++// Fields Beacon needs at the top level of the envelope, lifted out of wherever the context keeps+// them.+//+// Best-effort by design: Cline documents the base fields every hook receives, but not where each+// handler's context puts them, so several shapes are tried and a miss costs the field rather than+// the event. The hook adapter reads the same names, so anything missed here is still recoverable+// from the forwarded context.+function identity(context: Record<string, unknown> | undefined): Record<string, unknown> {+ if (!context) return {}+ const task = (context.task ?? context.run ?? {}) as Record<string, unknown>+ const fields: Record<string, unknown> = {}+ const taskId = context.taskId ?? context.taskID ?? context.task_id ?? task.id ?? task.taskId+ if (taskId) fields.taskId = taskId+ const roots = context.workspaceRoots ?? context.workspace_roots ?? context.workspaceFolders+ if (roots) fields.workspaceRoots = roots+ const cwd = context.cwd ?? context.workingDirectory ?? context.working_directory+ if (cwd) fields.cwd = cwd+ const version = context.clineVersion ?? context.cline_version ?? context.version+ if (version) fields.clineVersion = version+ return fields+}++type HookContext = Record<string, unknown> | undefined++export function createBeaconPlugin() {+ let base: Record<string, unknown> = {}++ const forward = async (type: string, context: HookContext) => {+ try {+ await sendToBeacon({ ...base, ...identity(context), ...(context ?? {}), type })+ } catch (err) {+ // Unreachable in practice: sendToBeacon swallows its own failures. Kept because a hook that+ // rejects is a hook that can break the run it was observing.+ debugLog("hook failed", err)+ }+ }++ return {+ name: "beacon-endpoint",+ manifest: { capabilities: ["hooks"] },++ // The setup context carries the workspace identity for every later hook, so it is captured+ // once rather than re-derived per event.+ setup(_api: unknown, context: HookContext) {+ base = identity(context)+ },++ hooks: {+ // Every handler returns undefined. Beacon observes; it never cancels a tool call, modifies a+ // prompt, or rewrites a tool result. Enforcement lives behind the policy provider seam in the+ // hook adapter, not here.+ beforeRun: (context: HookContext) => forward("beforeRun", context),+ beforeTool: (context: HookContext) => forward("beforeTool", context),+ afterTool: (context: HookContext) => forward("afterTool", context),+ afterRun: (context: HookContext) => forward("afterRun", context),+ },+ }+}++export const BeaconEndpointPlugin = createBeaconPlugin()++export default BeaconEndpointPlugindiff --git a/cli/beacon/internal/endpoint/hooks/assets/cline/embed.go b/cli/beacon/internal/endpoint/hooks/assets/cline/embed.gonew file mode 100644index 00000000..745f7e4f--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/cline/embed.go@@ -0,0 +1,10 @@+package clineplugin++import _ "embed"++// Template embeds the checked copy used by Beacon's Go installer.+// The root source of truth lives at plugins/cline-beacon/src/beacon.ts.+// Tests fail if this copy drifts.+//+//go:embed beacon.ts+var Template stringdiff --git a/cli/beacon/internal/endpoint/hooks/cline.go b/cli/beacon/internal/endpoint/hooks/cline.gonew file mode 100644index 00000000..5973300c--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/cline.go@@ -0,0 +1,199 @@+package hooks++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"++ clineplugin "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/cline"+)++const (+ clinePluginFileName = "beacon.ts"+ clineManagedPluginMarker = "beacon-managed-cline-plugin:v1"+ clineArgvPlaceholder = `["__BEACON_ARGV__"]`+)++var clinePluginTemplate = clineplugin.Template++type ClineOptions struct {+ Level Level+ LogPath string+ UserMode bool+}++type ClineStatus struct {+ Installed bool `json:"installed"`+ BinaryPath string `json:"binary_path,omitempty"`+ PluginPath string `json:"plugin_path,omitempty"`+ Message string `json:"message,omitempty"`+}++var clineRuntime = hookRuntime{+ displayName: "Cline",+ configPath: clinePluginPath,+ install: installClinePlugin,+ uninstall: removeClinePlugin,+ isInstalled: isClineInstalledAt,+}++func InstallCline(opts ClineOptions) (ClineStatus, error) {+ status, err := installRuntimeHooks(clineRuntime, RuntimeOptions(opts))+ if err != nil {+ return ClineStatus{}, err+ }+ return clineStatusFromRuntime(status), nil+}++func UninstallCline(opts ClineOptions) (ClineStatus, error) {+ status, err := uninstallRuntimeHooks(clineRuntime, RuntimeOptions(opts))+ if err != nil {+ return ClineStatus{}, err+ }+ return clineStatusFromRuntime(status), nil+}++func ClineHookStatus(opts ClineOptions) ClineStatus {+ return clineStatusFromRuntime(runtimeHookStatus(clineRuntime, RuntimeOptions(opts)))+}++func IsClineInstalled(opts ClineOptions) bool {+ return isRuntimeInstalled(clineRuntime, RuntimeOptions(opts))+}++// clineStatusFromRuntime reports installed only when the plugin can actually reach the hook binary.+//+// The marker alone is not enough. A plugin file survives a Beacon uninstall, a partially applied+// update, or a home directory restored from backup onto a machine where the binary lives elsewhere,+// and in each of those cases Cline loads a plugin that spawns nothing. Reporting that as installed+// tells an operator telemetry is being collected when none is.+func clineStatusFromRuntime(status runtimeStatus) ClineStatus {+ out := ClineStatus{+ Installed: status.Installed,+ BinaryPath: status.BinaryPath,+ PluginPath: status.ConfigPath,+ Message: status.Message,+ }+ if !out.Installed || out.BinaryPath == "" {+ return out+ }+ if _, err := os.Stat(out.BinaryPath); err != nil {+ out.Installed = false+ out.Message = fmt.Sprintf("Cline plugin is installed, but Beacon hook binary is missing at %s", out.BinaryPath)+ return out+ }+ data, err := os.ReadFile(out.PluginPath)+ if err != nil || !strings.Contains(string(data), out.BinaryPath) || strings.Contains(string(data), "__BEACON_") {+ out.Installed = false+ out.Message = fmt.Sprintf("Cline plugin at %s does not reference the active Beacon hook binary", out.PluginPath)+ }+ return out+}++func clineEmbeddedPluginSourcePath() string {+ return filepath.Clean(filepath.Join("assets", "cline", "beacon.ts"))+}++func clineRootPluginSourcePath() string {+ return filepath.Clean(filepath.Join("..", "..", "..", "..", "..", "plugins", "cline-beacon", "src", "beacon.ts"))+}++func installClinePlugin(path, binaryPath, logPath, configPath string) error {+ if existing, err := os.ReadFile(path); err == nil {+ if !strings.Contains(string(existing), clineManagedPluginMarker) {+ return fmt.Errorf("refusing to overwrite unmanaged Cline plugin at %s", path)+ }+ } else if !os.IsNotExist(err) {+ return err+ }+ plugin, err := renderClinePlugin(binaryPath, logPath, configPath)+ if err != nil {+ return err+ }+ return os.WriteFile(path, []byte(plugin), 0644)+}++func removeClinePlugin(path string) (bool, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return false, nil+ }+ return false, err+ }+ if !strings.Contains(string(data), clineManagedPluginMarker) {+ return false, nil+ }+ return true, os.Remove(path)+}++func isClineInstalledAt(path string) bool {+ data, err := os.ReadFile(path)+ if err != nil {+ return false+ }+ return strings.Contains(string(data), clineManagedPluginMarker)+}++// clinePluginPath is where Cline auto-discovers plugins.+//+// Cline reads ~/.cline/plugins for global plugins and .cline/plugins in a repository for+// project-scoped ones, and discovers a bare .ts file dropped into either. That is why Beacon writes+// a file rather than running `cline plugin install`: no CLI has to be present, and an install works+// the same for the VS Code and JetBrains hosts, which ship no `cline` binary at all.+func clinePluginPath(level Level) (string, error) {+ dir, err := clinePluginDir(level)+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, clinePluginFileName), nil+}++func clinePluginDir(level Level) (string, error) {+ switch level {+ case "", LevelUser:+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, ".cline", "plugins"), nil+ case LevelProject:+ cwd, err := os.Getwd()+ if err != nil {+ return "", err+ }+ return filepath.Join(cwd, ".cline", "plugins"), nil+ default:+ return "", fmt.Errorf("unknown hook level %q", level)+ }+}++func renderClinePlugin(binaryPath, logPath, configPath string) (string, error) {+ return renderClinePluginTemplate(clinePluginTemplate, binaryPath, logPath, configPath)+}++// renderClinePluginTemplate substitutes the hook invocation into the plugin source.+//+// The invocation goes in as a JSON array of argv, not as a command line, because the plugin spawns+// the binary directly. That removes the shell -- and with it the per-shell quoting problem that+// endpointCommandPrefix documents -- from a runtime whose hosts include VS Code on Windows. JSON+// encoding also means a path containing a quote or a backslash needs no special handling: Windows+// paths are exactly that case.+func renderClinePluginTemplate(template, binaryPath, logPath, configPath string) (string, error) {+ args := append(endpointCommandArgs("cline", binaryPath, logPath, configPath), "cline-event")+ argv, err := json.Marshal(args)+ if err != nil {+ return "", err+ }+ source := strings.ReplaceAll(template, "__BEACON_MANAGED_MARKER__", clineManagedPluginMarker)+ if !strings.Contains(source, clineArgvPlaceholder) {+ return "", fmt.Errorf("cline plugin template is missing the %s placeholder", clineArgvPlaceholder)+ }+ source = strings.ReplaceAll(source, clineArgvPlaceholder, string(argv))+ if strings.Contains(source, "__BEACON_") {+ return "", fmt.Errorf("cline plugin template contains unresolved Beacon placeholders")+ }+ return source, nil+}diff --git a/cli/beacon/internal/endpoint/hooks/cline_test.go b/cli/beacon/internal/endpoint/hooks/cline_test.gonew file mode 100644index 00000000..9e522b6f--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/cline_test.go@@ -0,0 +1,259 @@+package hooks++import (+ "encoding/json"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "testing"+)++// clineRenderedArgv extracts the argv the installer substituted into the plugin.+//+// Parsed back out of the source rather than compared as a string: argv is the whole point of this+// install shape, so the test asserts on the decoded array a host would spawn.+func clineRenderedArgv(t *testing.T, source string) []string {+ t.Helper()+ match := regexp.MustCompile(`(?m)^const beaconArgv: string\[\] = (\[.*\])$`).FindStringSubmatch(source)+ if len(match) != 2 {+ t.Fatalf("no beaconArgv assignment in rendered plugin:\n%s", source)+ }+ var argv []string+ if err := json.Unmarshal([]byte(match[1]), &argv); err != nil {+ t.Fatalf("decode beaconArgv %q: %v", match[1], err)+ }+ return argv+}++func TestInstallClinePluginWritesManagedPlugin(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ if err := installClinePlugin(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClinePlugin returned error: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read plugin: %v", err)+ }+ text := string(data)+ for _, want := range []string{+ clineManagedPluginMarker,+ "BeaconEndpointPlugin",+ "BEACON_CLINE_DEBUG",+ "beforeTool",+ "afterTool",+ "beforeRun",+ "afterRun",+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("plugin missing %q:\n%s", want, text)+ }+ }++ argv := clineRenderedArgv(t, text)+ if argv[0] != "/tmp/beacon-hooks" {+ t.Errorf("argv[0] = %q, want the hook binary", argv[0])+ }+ // The subcommand is the whole point of the invocation: without it the binary runs its root+ // command, exits, and every Cline event is silently dropped.+ if argv[len(argv)-1] != "cline-event" {+ t.Errorf("argv = %v, want it to end with cline-event", argv)+ }+ for _, want := range [][2]string{+ {"--platform", "cline"},+ {"--log", "/tmp/runtime.jsonl"},+ {"--config", "/tmp/config.json"},+ } {+ if !clineArgvHasFlag(argv, want[0], want[1]) {+ t.Errorf("argv = %v, want %s %s", argv, want[0], want[1])+ }+ }+}++func clineArgvHasFlag(argv []string, flag, value string) bool {+ for i, arg := range argv {+ if arg == flag {+ return i+1 < len(argv) && argv[i+1] == value+ }+ }+ return false+}++// Every path reaches the plugin through JSON encoding, which is why a Windows path needs no+// per-shell quoting: the backslashes and spaces that break a POSIX-quoted command line survive a+// round trip unchanged.+func TestRenderClinePluginEncodesWindowsPaths(t *testing.T) {+ binary := `C:\Program Files\Beacon\hooks\beacon-hooks.exe`+ logPath := `C:\ProgramData\Beacon\logs\runtime.jsonl`+ source, err := renderClinePlugin(binary, logPath, `C:\ProgramData\Beacon\config.json`)+ if err != nil {+ t.Fatalf("renderClinePlugin returned error: %v", err)+ }+ argv := clineRenderedArgv(t, source)+ if argv[0] != binary {+ t.Errorf("argv[0] = %q, want %q", argv[0], binary)+ }+ if !clineArgvHasFlag(argv, "--log", logPath) {+ t.Errorf("argv = %v, want the unmangled log path", argv)+ }+}++func TestInstallClinePluginRefusesToOverwriteUnmanagedPlugin(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ original := "export default { name: \"someone-elses-plugin\" }"+ if err := os.WriteFile(path, []byte(original), 0644); err != nil {+ t.Fatal(err)+ }+ err := installClinePlugin(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")+ if err == nil || !strings.Contains(err.Error(), "refusing to overwrite unmanaged") {+ t.Fatalf("install error = %v, want a refusal", err)+ }+ data, readErr := os.ReadFile(path)+ if readErr != nil || string(data) != original {+ t.Fatalf("unmanaged plugin changed: err=%v body=%q", readErr, data)+ }+}++func TestRemoveClinePluginOnlyRemovesManagedPlugin(t *testing.T) {+ dir := t.TempDir()+ userPlugin := filepath.Join(dir, "user.ts")+ if err := os.WriteFile(userPlugin, []byte("export default { name: \"mine\" }"), 0644); err != nil {+ t.Fatalf("write user plugin: %v", err)+ }+ changed, err := removeClinePlugin(userPlugin)+ if err != nil {+ t.Fatalf("removeClinePlugin returned error: %v", err)+ }+ if changed {+ t.Fatal("user plugin should not be removed")+ }+ if _, err := os.Stat(userPlugin); err != nil {+ t.Fatalf("user plugin was removed: %v", err)+ }++ managed := filepath.Join(dir, "beacon.ts")+ if err := installClinePlugin(managed, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClinePlugin returned error: %v", err)+ }+ changed, err = removeClinePlugin(managed)+ if err != nil || !changed {+ t.Fatalf("removeClinePlugin(managed) = %t, %v", changed, err)+ }+ if _, err := os.Stat(managed); !os.IsNotExist(err) {+ t.Fatalf("managed plugin still present: %v", err)+ }+}++func TestRemoveClinePluginIsQuietWhenNothingIsInstalled(t *testing.T) {+ changed, err := removeClinePlugin(filepath.Join(t.TempDir(), "beacon.ts"))+ if err != nil {+ t.Fatalf("removeClinePlugin returned error: %v", err)+ }+ if changed {+ t.Fatal("changed = true with no plugin present")+ }+}++func TestRenderClinePluginRejectsUnresolvedPlaceholders(t *testing.T) {+ if _, err := renderClinePluginTemplate("const x = \"__BEACON_UNKNOWN__\"", "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err == nil {+ t.Fatal("expected an error for a template with no argv placeholder")+ }+ template := clineArgvPlaceholder + "\nconst leftover = \"__BEACON_SOMETHING__\"\n"+ if _, err := renderClinePluginTemplate(template, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err == nil {+ t.Fatal("expected an error for a leftover Beacon placeholder")+ }+}++func TestClineEmbeddedPluginMatchesRootSource(t *testing.T) {+ embedded, err := os.ReadFile(clineEmbeddedPluginSourcePath())+ if err != nil {+ t.Fatalf("read embedded plugin source: %v", err)+ }+ root, err := os.ReadFile(clineRootPluginSourcePath())+ if err != nil {+ t.Fatalf("read root plugin source: %v", err)+ }+ if string(embedded) != string(root) {+ t.Fatalf("embedded Cline plugin source drifted from root package source")+ }+}++func TestClinePluginPathsPerLevel(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ userPath, err := clinePluginPath(LevelUser)+ if err != nil {+ t.Fatalf("clinePluginPath(user) returned error: %v", err)+ }+ if want := filepath.Join(home, ".cline", "plugins", "beacon.ts"); userPath != want {+ t.Errorf("user plugin path = %q, want %q", userPath, want)+ }++ projectPath, err := clinePluginPath(LevelProject)+ if err != nil {+ t.Fatalf("clinePluginPath(project) returned error: %v", err)+ }+ if !strings.HasSuffix(projectPath, filepath.Join(".cline", "plugins", "beacon.ts")) {+ t.Errorf("project plugin path = %q, want it under .cline/plugins", projectPath)+ }++ if _, err := clinePluginPath("nonsense"); err == nil {+ t.Error("clinePluginPath accepted an unknown level")+ }+}++// A plugin file outlives a Beacon uninstall, a half-applied update, or a home directory restored+// onto a machine where the binary lives elsewhere. In each case Cline loads a plugin that spawns+// nothing, and reporting that as installed tells an operator telemetry is being collected when none+// is.+func TestClineStatusRejectsAPluginWithNoBinary(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "beacon.ts")+ missingBinary := filepath.Join(dir, "absent", "beacon-hooks")+ if err := installClinePlugin(path, missingBinary, "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClinePlugin returned error: %v", err)+ }++ status := clineStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: missingBinary, ConfigPath: path})+ if status.Installed {+ t.Error("status reports installed with no hook binary present")+ }+ if !strings.Contains(status.Message, "missing") {+ t.Errorf("message = %q, want it to name the missing binary", status.Message)+ }+}++// A plugin left behind by an older install points at a binary that has since moved. It parses, it+// loads, and it sends nothing.+func TestClineStatusRejectsAPluginPointingElsewhere(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "beacon.ts")+ currentBinary := filepath.Join(dir, "beacon-hooks")+ if err := os.WriteFile(currentBinary, []byte("#!/bin/sh\n"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := installClinePlugin(path, filepath.Join(dir, "old", "beacon-hooks"), "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installClinePlugin returned error: %v", err)+ }++ status := clineStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: currentBinary, ConfigPath: path})+ if status.Installed {+ t.Error("status reports installed while the plugin points at a different binary")+ }+}++func TestIsClineInstalledAtRequiresTheManagedMarker(t *testing.T) {+ dir := t.TempDir()+ unmanaged := filepath.Join(dir, "other.ts")+ if err := os.WriteFile(unmanaged, []byte("export default {}"), 0644); err != nil {+ t.Fatal(err)+ }+ if isClineInstalledAt(unmanaged) {+ t.Error("an unmanaged plugin was reported as Beacon's")+ }+ if isClineInstalledAt(filepath.Join(dir, "absent.ts")) {+ t.Error("a missing plugin was reported as installed")+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/command_parse_test.go b/cli/beacon/internal/endpoint/hooks/command_parse_test.goindex 05bdd16f..8ddce788 100644--- a/cli/beacon/internal/endpoint/hooks/command_parse_test.go+++ b/cli/beacon/internal/endpoint/hooks/command_parse_test.go@@ -196,3 +196,39 @@ func TestCommandCarriesEndpointSettingsRecognizesBothSpellings(t *testing.T) {}}}++// The two builders of a hook invocation must stay in step.+//+// endpointCommandPrefix writes a command line for runtimes that hand a string to a shell;+// endpointCommandArgs builds argv for runtimes that spawn the binary themselves. A flag added to+// one and not the other means one runtime's hooks quietly stop reading the endpoint config, or stop+// reporting inventory, with nothing failing anywhere. Comparing the prefix's own tokens against+// argv is what keeps that from happening.+func TestEndpointCommandArgsMatchPrefix(t *testing.T) {+ cases := []struct {+ name string+ binaryPath string+ logPath string+ configPath string+ }{+ {name: "all settings", binaryPath: "/opt/beacon/hooks/beacon-hooks", logPath: "/var/log/beacon/runtime.jsonl", configPath: "/etc/beacon/config.json"},+ {name: "no log", binaryPath: "/opt/beacon/hooks/beacon-hooks", configPath: "/etc/beacon/config.json"},+ {name: "no config", binaryPath: "/opt/beacon/hooks/beacon-hooks", logPath: "/var/log/beacon/runtime.jsonl"},+ {name: "windows paths with spaces", binaryPath: `C:\Program Files\Beacon\beacon-hooks.exe`, logPath: `C:\ProgramData\Beacon\runtime.jsonl`, configPath: `C:\ProgramData\Beacon\config.json`},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ prefix := endpointCommandPrefix("cline", tc.binaryPath, tc.logPath, tc.configPath)+ args := endpointCommandArgs("cline", tc.binaryPath, tc.logPath, tc.configPath)+ tokens := commandFields(prefix)+ if len(tokens) != len(args) {+ t.Fatalf("prefix tokens %v do not match argv %v", tokens, args)+ }+ for i := range args {+ if tokens[i] != args[i] {+ t.Errorf("token %d = %q, argv = %q", i, tokens[i], args[i])+ }+ }+ })+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/runtime.go b/cli/beacon/internal/endpoint/hooks/runtime.goindex 75c74f13..135df0c1 100644--- a/cli/beacon/internal/endpoint/hooks/runtime.go+++ b/cli/beacon/internal/endpoint/hooks/runtime.go@@ -124,6 +124,33 @@ func isRuntimeInstalled(runtime hookRuntime, opts RuntimeOptions) bool {// shell on all three platforms for that runtime. Two results from the same measurement shape the code// below: a quoted executable path followed by flags runs correctly, and an *unquoted* Windows path// does not run at all, because bash consumes the backslashes as escapes.+// endpointCommandArgs builds the same invocation as endpointCommandPrefix, as argv rather than as a+// command line.+//+// Exists for runtimes that spawn the hook binary themselves instead of handing a string to a shell.+// A Cline plugin runs inside the VS Code extension host, a JetBrains host, or the CLI, on any+// platform, and passes argv straight to the OS -- which is the one form that needs no quoting at+// all. The comment on endpointCommandPrefix explains why quoting is otherwise unavoidably+// per-shell.+//+// The two functions must agree on which flags a hook receives; TestEndpointCommandArgsMatchPrefix+// is what keeps them from drifting.+func endpointCommandArgs(platform, binaryPath, logPath, configPath string) []string {+ args := []string{binaryPath, "--platform", platform}+ if logPath != "" {+ args = append(args, "--log", logPath)+ }+ if configPath != "" {+ args = append(args, "--config", configPath)+ }+ // Best-effort, exactly as in endpointCommandPrefix: the CLI path only enables the inventory+ // heartbeat, and a hook with no --cli still captures everything else.+ if cliPath, err := os.Executable(); err == nil && cliPath != "" {+ args = append(args, "--cli", cliPath)+ }+ return args+}+func endpointCommandPrefix(platform, binaryPath, logPath, configPath string) string {args := []string{hookCommandQuote(binaryPath), "--platform", platform}if logPath != "" {diff --git a/plugins/cline-beacon/package.json b/plugins/cline-beacon/package.jsonnew file mode 100644index 00000000..00a22dca--- /dev/null+++ b/plugins/cline-beacon/package.json@@ -0,0 +1,21 @@+{+ "name": "@asymptote-labs/cline-beacon",+ "version": "0.0.0",+ "private": true,+ "description": "Beacon endpoint telemetry adapter for Cline",+ "type": "module",+ "scripts": {+ "check": "bun --check src/beacon.ts && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts",+ "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts",+ "test": "bun test src/beacon.test.ts"+ },+ "exports": {+ ".": "./src/beacon.ts"+ },+ "files": [+ "src/"+ ],+ "peerDependencies": {+ "@cline/sdk": "*"+ }+}diff --git a/plugins/cline-beacon/src/beacon.test.ts b/plugins/cline-beacon/src/beacon.test.tsnew file mode 100644index 00000000..41832684--- /dev/null+++ b/plugins/cline-beacon/src/beacon.test.ts@@ -0,0 +1,108 @@+import { afterEach, describe, expect, test } from "bun:test"++import { createBeaconPlugin } from "./beacon"++const senderKey = Symbol.for("beacon.cline.testSender")++type Sent = Record<string, unknown>++function captureSends(): Sent[] {+ const sent: Sent[] = []+ ;(globalThis as Record<symbol, unknown>)[senderKey] = (payload: Sent) => {+ sent.push(payload)+ }+ return sent+}++afterEach(() => {+ delete (globalThis as Record<symbol, unknown>)[senderKey]+})++describe("beacon cline plugin", () => {+ test("declares itself as a hooks plugin", () => {+ const plugin = createBeaconPlugin()+ expect(plugin.manifest.capabilities).toEqual(["hooks"])+ expect(Object.keys(plugin.hooks).sort()).toEqual(["afterRun", "afterTool", "beforeRun", "beforeTool"])+ })++ test("forwards each hook with its stage name", async () => {+ const sent = captureSends()+ const plugin = createBeaconPlugin()++ await plugin.hooks.beforeRun({ taskId: "task-1" })+ await plugin.hooks.beforeTool({ taskId: "task-1", toolCall: { name: "read_file" } })+ await plugin.hooks.afterTool({ taskId: "task-1", toolCall: { name: "read_file" } })+ await plugin.hooks.afterRun({ taskId: "task-1" })++ expect(sent.map((event) => event.type)).toEqual(["beforeRun", "beforeTool", "afterTool", "afterRun"])+ })++ // The hook adapter reads these at the top level of the envelope. Leaving them wherever the+ // context happened to nest them would cost the session id, which is what groups a task's events.+ test("lifts task identity out of nested context shapes", async () => {+ const sent = captureSends()+ const plugin = createBeaconPlugin()++ await plugin.hooks.afterTool({ task: { id: "task-nested" }, workspace_roots: ["/repo"] })++ expect(sent[0].taskId).toBe("task-nested")+ expect(sent[0].workspaceRoots).toEqual(["/repo"])+ })++ // The setup context is the only place the workspace identity is guaranteed to appear, so it has+ // to reach hooks that did not carry it themselves.+ test("carries setup context onto later hooks", async () => {+ const sent = captureSends()+ const plugin = createBeaconPlugin()++ plugin.setup(undefined, { workspaceRoots: ["/repo"], clineVersion: "3.36.0" })+ await plugin.hooks.beforeTool({ toolCall: { name: "read_file" } })++ expect(sent[0].workspaceRoots).toEqual(["/repo"])+ expect(sent[0].clineVersion).toBe("3.36.0")+ })++ test("context fields win over the captured setup context", async () => {+ const sent = captureSends()+ const plugin = createBeaconPlugin()++ plugin.setup(undefined, { taskId: "task-setup" })+ await plugin.hooks.afterRun({ taskId: "task-current" })++ expect(sent[0].taskId).toBe("task-current")+ })++ // Cline awaits these handlers inside its own run loop. A hook that returns a rejected promise, or+ // that throws, is a hook that can break the run it was only supposed to observe.+ test("never rejects when the sender throws", async () => {+ ;(globalThis as Record<symbol, unknown>)[senderKey] = () => {+ throw new Error("sender exploded")+ }+ const plugin = createBeaconPlugin()++ await expect(plugin.hooks.beforeTool({ taskId: "task-1" })).resolves.toBeUndefined()+ })++ test("observes without cancelling: every hook resolves to undefined", async () => {+ captureSends()+ const plugin = createBeaconPlugin()++ for (const hook of Object.values(plugin.hooks)) {+ expect(await hook({ taskId: "task-1", toolCall: { name: "execute_command" } })).toBeUndefined()+ }+ })++ // A live SDK context is not plain data. JSON.stringify throws on a cycle, so a payload carrying+ // one has to survive as the fields around it rather than being dropped whole.+ test("survives a circular context", async () => {+ const sent = captureSends()+ const plugin = createBeaconPlugin()+ const context: Record<string, unknown> = { taskId: "task-cycle" }+ context.self = context++ await plugin.hooks.afterRun(context)++ expect(sent[0].taskId).toBe("task-cycle")+ expect(() => JSON.stringify(sent[0])).not.toThrow()+ })+})diff --git a/plugins/cline-beacon/src/beacon.ts b/plugins/cline-beacon/src/beacon.tsnew file mode 100644index 00000000..baf151b3--- /dev/null+++ b/plugins/cline-beacon/src/beacon.ts@@ -0,0 +1,211 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry plugin for Cline.+// Managed by beacon endpoint hooks install --harness cline.++// The argv Beacon's installer writes, as an array rather than a command line.+//+// Cline plugins run inside whichever host loaded them -- the VS Code extension host, a JetBrains+// plugin host, or the CLI -- so the hook may be spawned on Windows as readily as on macOS. An argv+// array is passed straight to the OS with no shell in between, which sidesteps quoting entirely: a+// POSIX-quoted command line is not valid in cmd.exe, and a Windows path inside double quotes is+// still expanded by bash.+const beaconArgv: string[] = ["__BEACON_ARGV__"]++const debugEnabled = process.env.BEACON_CLINE_DEBUG === "1"++// A send that has not finished in this long is abandoned. Cline awaits these handlers, so this is+// the worst case Beacon can add to a tool call.+const sendTimeoutMs = 2000++// How deep into a hook context the serializer will walk before giving up.+const maxDepth = 8++function debugLog(message: string, extra?: unknown) {+ if (!debugEnabled) return+ try {+ // eslint-disable-next-line no-console+ console.error("[beacon-cline]", message, extra ?? "")+ } catch {+ // Debug logging must stay best-effort.+ }+}++// safeClone turns a hook context into something JSON.stringify accepts.+//+// The contexts Cline passes are live SDK objects, not plain data: they carry functions, class+// instances, and parent references. JSON.stringify throws on a circular reference and on a bigint,+// and silently drops an Error to {}, so each of those is handled here rather than losing the whole+// payload to one bad field.+//+// Cycles are tracked along the current path and released on the way out, so an object that legibly+// appears twice -- the same workspace root referenced from two places -- is kept both times. A+// WeakSet that never released would drop the second occurrence as if it were a cycle.+function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {+ if (value === null) return null+ const kind = typeof value+ if (kind === "function" || kind === "symbol" || kind === "undefined") return undefined+ if (kind === "bigint") return String(value)+ if (kind !== "object") return value+ if (depth >= maxDepth) return undefined++ const object = value as object+ if (seen.has(object)) return undefined+ if (value instanceof Error) return { name: value.name, message: value.message }+ if (value instanceof Date) return value.toISOString()++ seen.add(object)+ try {+ if (Array.isArray(value)) {+ return value.map((item) => safeClone(item, depth + 1, seen))+ }+ const out: Record<string, unknown> = {}+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {+ const cloned = safeClone(nested, depth + 1, seen)+ if (cloned !== undefined) out[key] = cloned+ }+ return out+ } finally {+ seen.delete(object)+ }+}++async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {+ // Flattened before anything else sees it, so every consumer of this function is handed plain+ // data. Doing it further down, on the way into the child process, would leave a live SDK object+ // -- cycles, functions and all -- reaching whatever else is wired up here.+ const safe = safeClone(payload)++ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.cline.testSender")]+ if (typeof testSender === "function") {+ await (testSender as (value: unknown) => unknown)(safe)+ return+ }++ let body: string+ try {+ body = JSON.stringify(safe)+ } catch (err) {+ debugLog("payload could not be serialized", err)+ return+ }+ if (!body) return++ try {+ // Imported lazily so a host without node:child_process fails to send rather than failing to+ // load: a throwing import at module scope would surface to the user as a broken plugin.+ const { spawn } = await import("node:child_process")+ await new Promise<void>((resolve) => {+ let settled = false+ const finish = () => {+ if (settled) return+ settled = true+ resolve()+ }+ let child+ try {+ child = spawn(beaconArgv[0], beaconArgv.slice(1), {+ stdio: ["pipe", "ignore", "ignore"],+ windowsHide: true,+ })+ } catch (err) {+ debugLog("hook binary could not be spawned", err)+ finish()+ return+ }+ const timer = setTimeout(() => {+ try {+ child.kill()+ } catch {+ // Already gone.+ }+ debugLog("hook binary timed out", { type: payload?.type })+ finish()+ }, sendTimeoutMs)+ // An unreferenced timer cannot keep a CLI host alive waiting on Beacon telemetry.+ if (typeof timer.unref === "function") timer.unref()+ const done = () => {+ clearTimeout(timer)+ finish()+ }+ child.on("error", (err) => {+ debugLog("hook binary failed", err)+ done()+ })+ child.on("close", done)+ // Without this, a hook binary that exits before reading stdin turns an EPIPE into an+ // unhandled error event in the host process. Beacon telemetry must never do that.+ child.stdin?.on("error", () => {})+ try {+ child.stdin?.end(body)+ } catch (err) {+ debugLog("payload could not be written", err)+ }+ })+ } catch (err) {+ debugLog("send failed", err)+ // Beacon telemetry must never interrupt Cline execution.+ }+}++// Fields Beacon needs at the top level of the envelope, lifted out of wherever the context keeps+// them.+//+// Best-effort by design: Cline documents the base fields every hook receives, but not where each+// handler's context puts them, so several shapes are tried and a miss costs the field rather than+// the event. The hook adapter reads the same names, so anything missed here is still recoverable+// from the forwarded context.+function identity(context: Record<string, unknown> | undefined): Record<string, unknown> {+ if (!context) return {}+ const task = (context.task ?? context.run ?? {}) as Record<string, unknown>+ const fields: Record<string, unknown> = {}+ const taskId = context.taskId ?? context.taskID ?? context.task_id ?? task.id ?? task.taskId+ if (taskId) fields.taskId = taskId+ const roots = context.workspaceRoots ?? context.workspace_roots ?? context.workspaceFolders+ if (roots) fields.workspaceRoots = roots+ const cwd = context.cwd ?? context.workingDirectory ?? context.working_directory+ if (cwd) fields.cwd = cwd+ const version = context.clineVersion ?? context.cline_version ?? context.version+ if (version) fields.clineVersion = version+ return fields+}++type HookContext = Record<string, unknown> | undefined++export function createBeaconPlugin() {+ let base: Record<string, unknown> = {}++ const forward = async (type: string, context: HookContext) => {+ try {+ await sendToBeacon({ ...base, ...identity(context), ...(context ?? {}), type })+ } catch (err) {+ // Unreachable in practice: sendToBeacon swallows its own failures. Kept because a hook that+ // rejects is a hook that can break the run it was observing.+ debugLog("hook failed", err)+ }+ }++ return {+ name: "beacon-endpoint",+ manifest: { capabilities: ["hooks"] },++ // The setup context carries the workspace identity for every later hook, so it is captured+ // once rather than re-derived per event.+ setup(_api: unknown, context: HookContext) {+ base = identity(context)+ },++ hooks: {+ // Every handler returns undefined. Beacon observes; it never cancels a tool call, modifies a+ // prompt, or rewrites a tool result. Enforcement lives behind the policy provider seam in the+ // hook adapter, not here.+ beforeRun: (context: HookContext) => forward("beforeRun", context),+ beforeTool: (context: HookContext) => forward("beforeTool", context),+ afterTool: (context: HookContext) => forward("afterTool", context),+ afterRun: (context: HookContext) => forward("afterRun", context),+ },+ }+}++export const BeaconEndpointPlugin = createBeaconPlugin()++export default BeaconEndpointPlugin