diff --git a/CLAUDE.md b/CLAUDE.md index 920d764..cc2f478 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -109,7 +109,7 @@ Optional daemon services (feature-gated via config): - **AICodeOtelServer**: gRPC OTEL collector for AI coding CLI metrics, logs and traces (Claude Code, Codex). Spans (`claude_code.interaction`, `llm_request`, `tool`, ...) go to the same `/api/v1/cc/otel` endpoint in `spans`; a span without `session.id` takes it from another span of its trace in the same export. `shelltime cc install` turns traces on (`CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, `OTEL_TRACES_EXPORTER=otlp`). In a Claude Code cloud session (`CLAUDE_CODE_REMOTE=true`, where the SessionStart hook starts the daemon) it adds the VM's `CLAUDE_CODE_REMOTE_SESSION_ID` as the `ccr.session.id` attribute to Claude Code records that lack it; the server marks those sessions as cloud sessions. `daemon/main_test.go` clears both variables so tests behave the same inside a cloud session - **Git repositories** (`model/git_repository.go`): the server groups coding agent sessions into projects by git repository, not folder, so a renamed or moved clone, a worktree or a subfolder stays one project. `GitRepositoryResolver` asks the git CLI (found through `CommandService`, so the daemon's limited PATH reaches Homebrew) for a directory's top level and its `origin` remote (else `upstream`, else the first by name; `remote get-url`, so `insteadOf` applies) without optional locks, within one 2 s budget per lookup, since the daemon resolves on the OTLP export path. Concurrent lookups of one directory share one run, which goes on its own goroutine: a stat or git blocked in the kernel (a hung network mount) ignores the context, so the lookup is given up on after the budget (plus `gitRepositoryGrace`), or when its caller's context ends, and the directory gets no other until it returns (its answer is kept then). git runs with `LC_ALL=C`, since its messages are read; a remote's path segments are decoded and escaped again (`url.PathEscape`), like the server's. A migration run stops asking after `projectMigrationMaxUnanswered` folders' stats timed out (a hung mount; git refusing a folder doesn't count), and a folder that doesn't exist counts as missing, one it can't stat otherwise as unchecked. git refusing a repository it doesn't trust (`safe.directory`) or killed by a signal is no answer about the directory; a git binary not found is looked for again every 30 s. It keeps definitive answers, negative ones too (10 min in the daemon), and a timeout or git failing to start for 30 s only, reported as unknown by `Lookup` (`Resolve` drops the flag). `CanonicalRepositoryURL` turns any remote into `https:///` without credentials, port or `.git`, the form Claude Code reports; a local path is no repository. The repository travels as `vcs.repository.url.full` (`model.AICodeRepositoryAttribute`): the OTEL processor adds it to metrics and log events whose resource has a `pwd` and that don't name one (not to spans: the server keys a session from its events), and never when the resource names one (Claude Code's own value wins; git isn't asked then), the socket's `session_project` handler sends it with the statusline's directory, and backfill adds it to uploaded events (Codex's `session_meta.git.repository_url` first, since it was true when the session ran, else the transcript directory's). `aiCodeOtel.sendRepository: false` (`ShellTimeConfig.SendsRepository`) turns all of it off: no resolver in the processor or the socket, the processor removes the attribute from every record (the agent's own too), backfill attaches none, and neither the daemon nor `cc projects` migrates - **Project migration** (`daemon/project_migration.go`, `model/project_migration.go`): sessions recorded before the repository was sent are folder projects on the server. A while after start the daemon runs `MigrateProjectRepositories` once, never in AI cloud only mode (marker `~/.shelltime/project-repositories.v1`, written only when the run is `Complete`: a 404 from an older server, a failure, more pages than one run goes through (50), a folder git couldn't answer for, or a machine without a host name of its own leaves none, so the next start tries again): it lists the folder projects of this machine's names (`ProjectMigrationHosts`: the host name, without its domain, and the `machine.name` in `~/.claude/settings.json`, leaving out names many machines share, like `localhost`, `genericHostNames`) from `POST /api/v1/cc/projects/unresolved`, a page at a time by the last project of the page (`after`), and posts the folders that still exist and are clones to `POST /api/v1/cc/projects/repositories`. `shelltime cc projects` / `shelltime codex projects` run it by hand (`--dry-run` lists what would move; skipped in AI cloud only mode) -- **Agent hooks (Cursor, Antigravity)**: neither has OTEL, so `shelltime cursor install` / `shelltime agy install` (`commands/agent_hooks_install.go`; `model/cursor_hooks.go`, `model/antigravity_hooks.go`, on the ordered-JSON kit of `model/aicode_otel_claude_settings.go`) register the hidden `shelltime hook-ingest --agent cursor|agy --event --project` in the current repository's `.cursor/hooks.json` and in a `shelltime` group of its `.agents/hooks.json` (`model.ProjectHooksRoot`: the nearest folder up with `.git` below the home folder, else the folder itself, never the home folder, `ErrHomeIsNotAProject`), the only files Cursor Cloud Agents and the Antigravity agent's Gemini API sandbox run (never PreToolUse: a reply without a decision denies the tool; a file with a BOM, comments or invalid JSON is refused, never rewritten). Installing into a user-level file is refused (`ErrUserHooksRetired`), and so is Windows (`ErrProjectHooksUnsupported`: no daemon there); install leaves what older versions put in `~/.cursor/hooks.json` / `~/.gemini/config/hooks.json` (they still record every other folder) and says so, uninstall removes it (a user file it can't read is a warning, never a failure), and doctor's fix removes it when its binary is gone. The file is committed and the agents disagree on the folder a hook runs in, so each command is self-contained POSIX sh (`projectHookCommand`): it adds `model.ProjectHookSearchDirs` (`~/.shelltime/bin`, `/opt/homebrew/bin`, `/usr/local/bin`; doctor checks the same) to PATH, runs hook-ingest only when `shelltime` and `shelltime-daemon` are both found, and echoes the pass-through reply otherwise or when hook-ingest fails (a `shelltime` from before it exits non-zero; its stdout is dropped). A `--project` run whose event an older version's user-level hook records too (`userHooksRecord`: the user file registers that event with an absolute, executable binary, `AgentHooksStatus.EventBinaries`; Antigravity hooks and groups marked `"enabled": false` don't count) and that isn't cloud goes to the daemon with `YieldToUserHooks`, and the batcher drops it unless its session is cloud (Cloud Agents run no user-level hooks; Cursor marks only `sessionStart`); without a daemon hook-ingest drops it. The mark never reaches the server (`prepareAgentHookEvents` clears it). `hook-ingest` writes nothing to stdout but `agenthook.PassThrough` (`{"continue":true}` for Cursor's beforeSubmitPrompt, `{"decision":"allow"}` for Antigravity's Stop, else `{}`), exactly once, even on a panic, and exits 0. The `agenthook` package (no dependency on `model`) normalizes the payloads into `agenthook.Event`; for successful `gh pr create` or GitHub MCP `create_pull_request` tool calls (`agenthook/pr.go`), it also extracts normalized PR URLs from Cursor `tool_output` (or Antigravity `transcript.jsonl` / output fields) into daemon-only `PullRequestURLs` without keeping raw tool output. Each event's `cloud` names what showed it ran in a cloud agent's VM (`agenthook.cloudSignal`): Cursor's `is_background_agent` (only in `sessionStart`) or, for Antigravity, the OS user `antigravity` (`agenthook.InAntigravitySandbox`: the user database, else `USER`/`LOGNAME`), else `SHELLTIME_CLOUD=true` or `CLAUDE_CODE_REMOTE=true` in the hook's environment (`agenthook.CloudEnvSignal`), and an explicit `SHELLTIME_CLOUD=false` overrides them all (`agenthook.CloudEnvExplicit`); neither agent marks every hook of a cloud run, and Cursor's `CURSOR_CODE_REMOTE` (any remote workspace, the user's SSH hosts too) is only `metadata.remote_workspace`. hook-ingest hands it to the daemon (`agent_hook` socket message, acknowledged within 50 ms) or, without one, applies `model.ApplyAgentHookPrivacy` and appends it to `~/.shelltime/agent-hooks.pending.jsonl`; a payload over 4 MiB is recorded from its first 4 MiB, marked `truncated` (`agenthook.NormalizeTruncated`: the top-level fields before the cut). `AgentHookBatcher` (`daemon/agent_hooks.go`) marks the later events of a session an event showed was cloud (for an hour after its last event, `fillCloudLocked`) and sends batches to `POST /api/v1/agent-hooks` every 2 s or 100 events (stripping `PullRequestURLs` from the wire payload and dispatching `model.SendSessionPullRequests` to `POST /api/v1/cc/session-pull-requests` once a chunk succeeds, deduplicated per session+URL within `agentHookSessionTTL` and honoring `Exclude`), readied by `prepareAgentHookEvents` (the workspace's repository under `aiCodeOtel.sendRepository`, and the privacy settings, `agentHooks.sendContent` included, from the config on disk), and saves what can be sent later (no token, the failures `agentHookSendCanWait` names, a 404/405 from a server without the endpoint among them) for `AgentHookResyncService` (30-min interval), which readies saved events and dispatches their saved `PullRequestURLs` the same way; both run in AI cloud only mode too. hook-ingest and the daemon share the pending file under `agent-hooks.pending.lock`, an advisory flock like the command store's: appends hold it shared and the resync's read-and-rewrite exclusively, nobody waits more than 50 ms (an append then goes ahead, a rewrite returns `ErrAgentHookPendingBusy` and the pass changes nothing), and a rewrite carries over the lines appended since its read +- **Agent hooks (Cursor, Antigravity)**: neither has OTEL, so `shelltime cursor install` / `shelltime agy install` (`commands/agent_hooks_install.go`; `model/cursor_hooks.go`, `model/antigravity_hooks.go`, on the ordered-JSON kit of `model/aicode_otel_claude_settings.go`) register the hidden `shelltime hook-ingest --agent cursor|agy --event --project` in the current repository's `.cursor/hooks.json` and in a `shelltime` group of its `.agents/hooks.json` (`model.ProjectHooksRoot`: the nearest folder up with `.git` below the home folder, else the folder itself, never the home folder, `ErrHomeIsNotAProject`), the only files Cursor Cloud Agents and the Antigravity agent's Gemini API sandbox run (never PreToolUse: a reply without a decision denies the tool; a file with a BOM, comments or invalid JSON is refused, never rewritten). Installing into a user-level file is refused (`ErrUserHooksRetired`), and so is Windows (`ErrProjectHooksUnsupported`: no daemon there); install leaves what older versions put in `~/.cursor/hooks.json` / `~/.gemini/config/hooks.json` (they still record every other folder) and says so, uninstall removes it (a user file it can't read is a warning, never a failure), and doctor's fix removes it when its binary is gone. The file is committed and the agents disagree on the folder a hook runs in, so each command is self-contained POSIX sh (`projectHookCommand`): it adds `model.ProjectHookSearchDirs` (`~/.shelltime/bin`, `/opt/homebrew/bin`, `/usr/local/bin`; doctor checks the same) to PATH, runs hook-ingest only when `shelltime` and `shelltime-daemon` are both found, and echoes the pass-through reply otherwise or when hook-ingest fails (a `shelltime` from before it exits non-zero; its stdout is dropped). A `--project` run whose event an older version's user-level hook records too (`userHooksRecord`: the user file registers that event with an absolute, executable binary, `AgentHooksStatus.EventBinaries`; Antigravity hooks and groups marked `"enabled": false` don't count) and that isn't cloud goes to the daemon with `YieldToUserHooks`, and the batcher drops it unless its session is cloud (Cloud Agents run no user-level hooks; Cursor marks only `sessionStart`); without a daemon hook-ingest drops it. The mark never reaches the server (`prepareAgentHookEvents` clears it). `hook-ingest` writes nothing to stdout but `agenthook.PassThrough` (`{"continue":true}` for Cursor's beforeSubmitPrompt, `{"decision":"allow"}` for Antigravity's Stop, else `{}`), exactly once, even on a panic, and exits 0. The `agenthook` package (no dependency on `model`) normalizes the payloads into `agenthook.Event`; for successful `gh pr create` or GitHub MCP `create_pull_request` tool calls (`agenthook/pr.go`), it also extracts normalized PR URLs from Cursor `tool_output` (or Antigravity `transcript.jsonl` / output fields) into daemon-only `PullRequestURLs` without keeping raw tool output. Each event's `cloud` names what showed it ran in a cloud agent's VM (`agenthook.cloudSignal`): Cursor's `is_background_agent` (only in `sessionStart`) or, for Antigravity, the OS user `antigravity` (`agenthook.InAntigravitySandbox`: the user database, else `USER`/`LOGNAME`), else `SHELLTIME_CLOUD=true` or `CLAUDE_CODE_REMOTE=true` in the hook's environment (`agenthook.CloudEnvSignal`), and an explicit `SHELLTIME_CLOUD=false` overrides them all (`agenthook.CloudEnvExplicit`); neither agent marks every hook of a cloud run, and Cursor's `CURSOR_CODE_REMOTE` (any remote workspace, the user's SSH hosts too) is only `metadata.remote_workspace`. An Antigravity remote agent (antigravity.google.com/remote) runs outside its VM and runs no hook there: it sends each command in as `bash -l -c ` with `JULES_SESSION_ID` set, so `cloud.bash` (installation repo) adds a login profile script that pipes each command to `shelltime hook-ingest --agent agy --event ShellCommand --session --exit-code [--duration-ms ]` when its shell exits. That mode (`agenthook.NormalizeShellCommand`, Antigravity only) records the command as a `run_command` call (`tool_failure` with `exit status ` when non-zero; `metadata.exit_code`, `metadata.source = login_shell`), the working directory as the workspace, writes nothing to stdout and drops the command on a usage error. hook-ingest hands it to the daemon (`agent_hook` socket message, acknowledged within 50 ms) or, without one, applies `model.ApplyAgentHookPrivacy` and appends it to `~/.shelltime/agent-hooks.pending.jsonl`; a payload over 4 MiB is recorded from its first 4 MiB, marked `truncated` (`agenthook.NormalizeTruncated`: the top-level fields before the cut). `AgentHookBatcher` (`daemon/agent_hooks.go`) marks the later events of a session an event showed was cloud (for an hour after its last event, `fillCloudLocked`) and sends batches to `POST /api/v1/agent-hooks` every 2 s or 100 events (stripping `PullRequestURLs` from the wire payload and dispatching `model.SendSessionPullRequests` to `POST /api/v1/cc/session-pull-requests` once a chunk succeeds, deduplicated per session+URL within `agentHookSessionTTL` and honoring `Exclude`), readied by `prepareAgentHookEvents` (the workspace's repository under `aiCodeOtel.sendRepository`, and the privacy settings, `agentHooks.sendContent` included, from the config on disk), and saves what can be sent later (no token, the failures `agentHookSendCanWait` names, a 404/405 from a server without the endpoint among them) for `AgentHookResyncService` (30-min interval), which readies saved events and dispatches their saved `PullRequestURLs` the same way; both run in AI cloud only mode too. hook-ingest and the daemon share the pending file under `agent-hooks.pending.lock`, an advisory flock like the command store's: appends hold it shared and the resync's read-and-rewrite exclusively, nobody waits more than 50 ms (an append then goes ahead, a rewrite returns `ErrAgentHookPendingBusy` and the pass changes nothing), and a rewrite carries over the lines appended since its read - **HeartbeatResyncService**: Periodic resync of failed heartbeats (30-min interval) - **CleanupTimerService**: Periodic log file cleanup (24-hour interval) diff --git a/README.md b/README.md index ea99600..9e8afd7 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ shelltime agy install # in each repository you use Google Antigravity in | `shelltime codex projects` | Same as `shelltime cc projects`: the projects of both agents are grouped together | | `shelltime cursor install` | Add the ShellTime hooks to the current repository's `.cursor/hooks.json` (Cursor IDE, `cursor-agent` and Cloud Agents) | | `shelltime cursor uninstall` | Remove the ShellTime hooks from the current repository's `.cursor/hooks.json` and `~/.cursor/hooks.json` | -| `shelltime agy install` | Add the ShellTime hook group to the current repository's `.agents/hooks.json` (Antigravity app, `agy` CLI and the Antigravity agent's Gemini API sandbox); `shelltime antigravity` works too | +| `shelltime agy install` | Add the ShellTime hook group to the current repository's `.agents/hooks.json` (Antigravity app, `agy` CLI and the Antigravity agent's Gemini API sandbox; remote agents run no hooks, see [Cloud agents](#cloud-agents)); `shelltime antigravity` works too | | `shelltime agy uninstall` | Remove the ShellTime hook group from the current repository's `.agents/hooks.json` and `~/.gemini/config/hooks.json` | ### Environment helpers @@ -226,6 +226,8 @@ Token usage (used to calculate estimated USD cost on the server) is captured per In a Cursor Cloud Agent's environment, install ShellTime, sign it in (`shelltime auth --token …`), set `SHELLTIME_CLOUD=true` in the environment's variables or secrets, and keep `shelltime-daemon` running, started with that variable set: the daemon reads it once, when it starts (or put `aiCloudOnly: true` in its config). The committed hooks do the rest. Cursor marks a cloud run only in `sessionStart` (`is_background_agent`), which the daemon passes on to the session's later events, so the variable is what marks every event. The Antigravity agent's Gemini API sandbox needs the same setup (its environment takes variables too); its hooks are marked as cloud by the sandbox's OS user, `antigravity`, even without the variable. With the variable the machine collects AI coding agent usage only (see `aiCloudOnly` in [CONFIG.md](docs/CONFIG.md)). Claude Code cloud environments (`CLAUDE_CODE_REMOTE=true`) count as cloud too. +Antigravity **remote agents** (`antigravity.google.com/remote`) are different: the agent runs outside its VM and runs no hook there, neither `.agents/hooks.json` nor `~/.gemini/config/hooks.json`. It sends each command into the VM as `bash -l -c ` with `JULES_SESSION_ID` set. Add `curl -fsSL https://raw.githubusercontent.com/shelltime/installation/main/cloud.bash | bash` to the environment's setup script, with your token in `SHELLTIME_TOKEN`: it installs ShellTime and a login profile script that reports each command when its shell exits (`shelltime hook-ingest --agent agy --event ShellCommand --session --exit-code [--duration-ms ]`, command on stdin). Each conversation then shows as a cloud Antigravity session of `run_command` calls, failed when the command exited non-zero, in the folder it ended in. Prompts, replies and token usage never reach the VM, so these sessions have none. + ## Projects ShellTime groups your coding agent sessions into projects by the git repository they ran in, so a renamed or moved clone, a worktree or a subfolder stays one project. The repository comes from the folder's `origin` remote (else `upstream`, else the first remote), sent as `https:///` with any credentials in the remote URL removed. Claude Code reports it itself (`shelltime cc install` turns this on); for Codex and older Claude Code setups the daemon asks git about the session's folder. Sessions outside a repository, or in one without a remote, are grouped by machine and folder. diff --git a/agenthook/shell_command.go b/agenthook/shell_command.go new file mode 100644 index 0000000..0f3f334 --- /dev/null +++ b/agenthook/shell_command.go @@ -0,0 +1,133 @@ +package agenthook + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "strings" + "time" +) + +// HookEventShellCommand is the --event value for a shell command a cloud agent ran in its VM +// with no hook to see it. An Antigravity remote agent (antigravity.google.com/remote) runs +// outside its VM: it sends each command in through a launcher as `bash -l -c `, with +// JULES_SESSION_ID naming the conversation, and runs no hook there, neither the repository's +// .agents/hooks.json nor ~/.gemini/config/hooks.json. The login shell reports the command +// itself instead (the profile script cloud.bash installs), and it reads like one of the +// agent's own shell tool calls. +const HookEventShellCommand = "ShellCommand" + +// AntigravityShellTool is the tool Antigravity runs shell commands with. +const AntigravityShellTool = "run_command" + +var ( + // ErrShellCommandAgent is returned for a shell command of an agent other than Antigravity: + // the others run their hooks in their cloud VMs. + ErrShellCommandAgent = errors.New("shell commands are recorded for Antigravity only") + // ErrNoSessionID is returned for a shell command without the conversation it belongs to. + ErrNoSessionID = errors.New("no session id") +) + +// ShellCommand is one command a cloud agent ran, as its login shell saw it. +type ShellCommand struct { + // SessionID is the agent's conversation, JULES_SESSION_ID in an Antigravity remote VM. + SessionID string + Command string + // Workspace is the directory the command ended in. + Workspace string + ExitCode int + // DurationMs is how long the command ran. Zero or less sends none: Event.DurationMs leaves + // 0 out, so a command under a millisecond has no duration either. + DurationMs int64 +} + +// maxShellWorkspaceBytes caps the folder in the tool input: a path is never longer on Linux. +const maxShellWorkspaceBytes = 4096 + +// IsShellCommandEvent reports whether an --event value names HookEventShellCommand. +func IsShellCommandEvent(event string) bool { + return strings.EqualFold(strings.TrimSpace(event), HookEventShellCommand) +} + +// NormalizeShellCommand turns a command a cloud agent's login shell ran into an Event: a call +// of the agent's shell tool, failed when the command exited non-zero. agent is a --agent +// value; getenv reads the shell's environment (nil reads nothing). +func NormalizeShellCommand(agent string, cmd ShellCommand, now time.Time, getenv func(string) string) (Event, error) { + canonical, ok := ParseAgent(agent) + if !ok { + return Event{}, fmt.Errorf("%w %q", ErrUnknownAgent, agent) + } + if canonical != AgentAntigravity { + return Event{}, ErrShellCommandAgent + } + if getenv == nil { + getenv = func(string) string { return "" } + } + sessionID := strings.TrimSpace(cmd.SessionID) + if sessionID == "" { + return Event{}, ErrNoSessionID + } + command := strings.TrimSpace(cmd.Command) + if command == "" { + return Event{}, ErrEmptyPayload + } + workspace := capText(workspacePath(cmd.Workspace), maxShellWorkspaceBytes) + + input, err := shellToolInput(command, workspace) + if err != nil { + return Event{}, err + } + // capEvent would cut the JSON short: cut the command instead, in proportion, since escaping + // can make it up to six times longer + for len(input) > MaxTextBytes && command != "" { + command = capText(command, max(len(command)*MaxTextBytes/len(input)-1, 0)) + if input, err = shellToolInput(command, workspace); err != nil { + return Event{}, err + } + } + + ev := Event{ + ID: NewID(), + Agent: canonical, + SessionID: sessionID, + HookEventName: HookEventShellCommand, + Timestamp: now.UTC().Format(time.RFC3339Nano), + Workspace: workspace, + ToolName: AntigravityShellTool, + Command: strings.TrimSpace(cmd.Command), + ToolInput: input, + } + if cmd.DurationMs > 0 { + ev.DurationMs = cmd.DurationMs + } + if cmd.ExitCode == 0 { + ev.EventType = EventToolUse + ev.Status = StatusOK + } else { + ev.EventType = EventToolFailure + ev.Status = StatusError + ev.Error = fmt.Sprintf("exit status %d", cmd.ExitCode) + } + ev.SetMetadata("exit_code", int64(cmd.ExitCode)) + ev.SetMetadata("source", "login_shell") + ev.Cloud = cloudSignal(canonical, payload{}, getenv) + capEvent(&ev) + return ev, nil +} + +// shellToolInput is the input of Antigravity's own run_command calls, as JSON without HTML +// escaping: it is shown as the command reads, && and all. +func shellToolInput(command, workspace string) (string, error) { + args := map[string]string{"CommandLine": command} + if workspace != "" { + args["Cwd"] = workspace + } + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(args); err != nil { + return "", err + } + return strings.TrimSuffix(buf.String(), "\n"), nil +} diff --git a/agenthook/shell_command_test.go b/agenthook/shell_command_test.go new file mode 100644 index 0000000..31a1aef --- /dev/null +++ b/agenthook/shell_command_test.go @@ -0,0 +1,130 @@ +package agenthook + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNormalizeShellCommand(t *testing.T) { + ev, err := NormalizeShellCommand("agy", ShellCommand{ + SessionID: " f35305b9-fb6a-4f61-987f-f733f1dc4ee9 ", + Command: "cd ~/server && go test ./...\n", + Workspace: "/home/antigravity/server", + DurationMs: 1520, + }, testNow, nil) + require.NoError(t, err) + + assert.Regexp(t, `^[0-9a-f]{32}$`, ev.ID) + assert.Equal(t, AgentAntigravity, ev.Agent) + assert.Equal(t, "f35305b9-fb6a-4f61-987f-f733f1dc4ee9", ev.SessionID) + assert.Equal(t, HookEventShellCommand, ev.HookEventName) + assert.Equal(t, testNow.UTC().Format("2006-01-02T15:04:05.999999999Z07:00"), ev.Timestamp) + assert.Equal(t, EventToolUse, ev.EventType) + assert.Equal(t, StatusOK, ev.Status) + assert.Empty(t, ev.Error) + assert.Equal(t, AntigravityShellTool, ev.ToolName) + assert.Equal(t, "cd ~/server && go test ./...", ev.Command) + assert.Equal(t, "/home/antigravity/server", ev.Workspace) + assert.Equal(t, `{"CommandLine":"cd ~/server && go test ./...","Cwd":"/home/antigravity/server"}`, ev.ToolInput) + assert.Equal(t, int64(1520), ev.DurationMs) + assert.Equal(t, int64(0), ev.Metadata["exit_code"]) + assert.Equal(t, "login_shell", ev.Metadata["source"]) + assert.Empty(t, ev.Cloud, "the test process isn't the OS user antigravity") +} + +func TestNormalizeShellCommand_NonZeroExitFails(t *testing.T) { + ev, err := NormalizeShellCommand("antigravity", ShellCommand{SessionID: "s1", Command: "false", ExitCode: 2, DurationMs: -1}, testNow, nil) + require.NoError(t, err) + + assert.Equal(t, EventToolFailure, ev.EventType) + assert.Equal(t, StatusError, ev.Status) + assert.Equal(t, "exit status 2", ev.Error) + assert.Equal(t, int64(2), ev.Metadata["exit_code"]) + assert.Zero(t, ev.DurationMs, "an unknown duration is left out") + assert.Empty(t, ev.Workspace) + assert.Equal(t, `{"CommandLine":"false"}`, ev.ToolInput) +} + +func TestNormalizeShellCommand_Cloud(t *testing.T) { + cmd := ShellCommand{SessionID: "s1", Command: "ls"} + + asOSUser(t, "antigravity") + ev, err := NormalizeShellCommand("agy", cmd, testNow, nil) + require.NoError(t, err) + assert.Equal(t, CloudSignalAntigravitySandbox, ev.Cloud, "the remote VM runs commands as the OS user antigravity") + + ev, err = NormalizeShellCommand("agy", cmd, testNow, envOf(map[string]string{"SHELLTIME_CLOUD": "false"})) + require.NoError(t, err) + assert.Empty(t, ev.Cloud, "an explicit SHELLTIME_CLOUD=false wins") + + asOSUser(t, "me") + ev, err = NormalizeShellCommand("agy", cmd, testNow, envOf(map[string]string{"SHELLTIME_CLOUD": "true"})) + require.NoError(t, err) + assert.Equal(t, CloudSignalEnv, ev.Cloud) +} + +func TestNormalizeShellCommand_Refused(t *testing.T) { + tests := []struct { + name string + agent string + cmd ShellCommand + err error + }{ + {"unknown agent", "vim", ShellCommand{SessionID: "s1", Command: "ls"}, ErrUnknownAgent}, + {"Cursor runs its hooks in its cloud VMs", "cursor", ShellCommand{SessionID: "s1", Command: "ls"}, ErrShellCommandAgent}, + {"no session", "agy", ShellCommand{SessionID: " ", Command: "ls"}, ErrNoSessionID}, + {"no command", "agy", ShellCommand{SessionID: "s1", Command: " \n"}, ErrEmptyPayload}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NormalizeShellCommand(tt.agent, tt.cmd, testNow, nil) + assert.ErrorIs(t, err, tt.err) + }) + } +} + +func TestNormalizeShellCommand_CapsText(t *testing.T) { + long := strings.Repeat("é", MaxTextBytes) + ev, err := NormalizeShellCommand("agy", ShellCommand{SessionID: "s1", Command: "echo " + long}, testNow, nil) + require.NoError(t, err) + + assert.LessOrEqual(t, len(ev.Command), MaxTextBytes) + assert.LessOrEqual(t, len(ev.ToolInput), MaxTextBytes) + assert.True(t, json.Valid([]byte(ev.ToolInput)), "the input is cut before it is encoded") + assert.True(t, strings.HasPrefix(ev.Command, "echo é")) + + // Escaping makes the input up to six times the command + escaped := strings.Repeat("\x01\"", MaxTextBytes/2) + ev, err = NormalizeShellCommand("agy", ShellCommand{SessionID: "s1", Command: "echo " + escaped, Workspace: "/" + strings.Repeat("w", 10_000)}, testNow, nil) + require.NoError(t, err) + assert.LessOrEqual(t, len(ev.ToolInput), MaxTextBytes) + assert.True(t, json.Valid([]byte(ev.ToolInput))) + var args map[string]string + require.NoError(t, json.Unmarshal([]byte(ev.ToolInput), &args)) + assert.True(t, strings.HasPrefix(args["CommandLine"], "echo \x01\"")) + assert.Len(t, args["Cwd"], maxShellWorkspaceBytes) + assert.Equal(t, "echo "+escaped[:MaxTextBytes-len("echo ")], ev.Command, "the command itself keeps its 64 KB") +} + +func TestNormalizeShellCommand_InputIsJSON(t *testing.T) { + command := "printf '%s\\n' \"a\tb\" | jq -r '.x' # \x01" + ev, err := NormalizeShellCommand("agy", ShellCommand{SessionID: "s1", Command: command, Workspace: "file:///repo"}, testNow, nil) + require.NoError(t, err) + + var args map[string]string + require.NoError(t, json.Unmarshal([]byte(ev.ToolInput), &args)) + assert.Equal(t, command, args["CommandLine"]) + assert.Equal(t, "/repo", args["Cwd"]) + assert.Equal(t, "/repo", ev.Workspace) +} + +func TestIsShellCommandEvent(t *testing.T) { + assert.True(t, IsShellCommandEvent("ShellCommand")) + assert.True(t, IsShellCommandEvent(" shellcommand ")) + assert.False(t, IsShellCommandEvent("PostToolUse")) + assert.False(t, IsShellCommandEvent("")) +} diff --git a/commands/hook_ingest.go b/commands/hook_ingest.go index 4065e23..17e8127 100644 --- a/commands/hook_ingest.go +++ b/commands/hook_ingest.go @@ -33,6 +33,7 @@ var ( hookIngestStdout io.Writer = os.Stdout hookIngestGetenv = os.Getenv hookIngestNow = time.Now + hookIngestGetwd = os.Getwd // hookIngestRawArgs are the command line arguments, read when urfave/cli couldn't parse // them. hookIngestRawArgs = func() []string { return os.Args } @@ -41,6 +42,11 @@ var ( // HookIngestCommand is what the Cursor and Antigravity hooks run (`shelltime cursor install`, // `shelltime agy install`). It must never get in the agent's way: whatever happens, stdout // holds exactly the reply that lets the agent carry on, and the command exits 0. +// +// With --event ShellCommand it records a command an Antigravity remote agent ran instead: that +// agent runs outside its VM and no hook there, so cloud.bash's login profile reports each +// command (stdin) with --session, --exit-code and --duration-ms. Nothing is written to stdout +// then, since no agent waits for a reply. var HookIngestCommand = &cli.Command{ Name: "hook-ingest", Usage: "record a Cursor or Antigravity hook event (run by the agent's hooks)", @@ -50,14 +56,31 @@ var HookIngestCommand = &cli.Command{ &cli.StringFlag{Name: "agent", Usage: "the agent that runs the hook: cursor, or agy (antigravity)"}, &cli.StringFlag{Name: "event", Usage: "the hook event"}, &cli.BoolFlag{Name: "project", Usage: "run from a project's hook file (cursor/agy install)"}, + &cli.StringFlag{Name: "session", Usage: "with --event ShellCommand: the conversation the command belongs to"}, + &cli.IntFlag{Name: "exit-code", Usage: "with --event ShellCommand: the command's exit status"}, + &cli.Int64Flag{Name: "duration-ms", Value: -1, Usage: "with --event ShellCommand: how long the command ran"}, }, Action: func(c *cli.Context) error { + if agenthook.IsShellCommandEvent(c.String("event")) { + runShellCommandIngest(c.Context, c.String("agent"), agenthook.ShellCommand{ + SessionID: c.String("session"), + ExitCode: c.Int("exit-code"), + DurationMs: c.Int64("duration-ms"), + }) + return nil + } runHookIngest(c.Context, c.String("agent"), c.String("event"), c.Bool("project")) return nil }, OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { // The hook still answers. Read the flags from the arguments as they are. agent, event, project := hookIngestFlagsFromArgs(hookIngestRawArgs()) + if agenthook.IsShellCommandEvent(event) { + // No agent waits on a shell command's report, and its flags can't be trusted + SetupLogger(os.ExpandEnv("$HOME/" + model.COMMAND_BASE_STORAGE_FOLDER)) + slog.Warn("hook-ingest: shell command not recorded", slog.String("agent", agent), slog.Any("err", err)) + return nil + } runHookIngest(c.Context, agent, event, project) return nil }, @@ -119,6 +142,49 @@ func runHookIngest(ctx context.Context, agent, event string, project bool) { return } ev.YieldToUserHooks = project && ev.Cloud == "" && userHooksRecord(ev.Agent, ev.HookEventName) + recordHookEvent(ctx, ev) +} + +// runShellCommandIngest records a command a cloud agent's login shell ran (--event +// ShellCommand): the command is stdin, the folder it ended in this process's working directory, +// the rest comes from the flags. It writes nothing to stdout, and a panic is only logged. +func runShellCommandIngest(ctx context.Context, agent string, cmd agenthook.ShellCommand) { + if ctx == nil { + ctx = context.Background() + } + defer func() { + if r := recover(); r != nil { + slog.Error("hook-ingest failed", slog.Any("panic", r)) + } + }() + + // The log goes to a file (or stderr), never stdout + SetupLogger(os.ExpandEnv("$HOME/" + model.COMMAND_BASE_STORAGE_FOLDER)) + + // The profile pipes the command in, so stdin ends at once; the hooks' bound only matters for + // a caller that leaves it open, whose shell then waits that long to exit + readCtx, cancel := context.WithTimeout(ctx, hookIngestStdinTimeout) + stdin, readErr := readWithTimeout(readCtx, hookIngestStdin, hookIngestStdinLimit) + cancel() + // A command over the limit is kept from its start: the event holds 64 KB of it anyway + if readErr != nil && !errors.Is(readErr, errInputTooLarge) { + slog.Warn("hook-ingest: couldn't read the shell command", slog.String("agent", agent), slog.Any("err", readErr)) + return + } + cmd.Command = string(stdin) + cmd.Workspace, _ = hookIngestGetwd() + + ev, err := agenthook.NormalizeShellCommand(agent, cmd, hookIngestNow(), hookIngestGetenv) + if err != nil { + slog.Warn("hook-ingest: shell command not recorded", slog.String("agent", agent), slog.Any("err", err)) + return + } + recordHookEvent(ctx, ev) +} + +// recordHookEvent hands ev to the daemon, or without one keeps it in the pending file the +// daemon resends from. +func recordHookEvent(ctx context.Context, ev agenthook.Event) { ev.Hostname, _ = os.Hostname() // Fast path, before any config is read: the daemon applies the privacy settings, adds the diff --git a/commands/hook_ingest_test.go b/commands/hook_ingest_test.go index ee8c594..4b534d7 100644 --- a/commands/hook_ingest_test.go +++ b/commands/hook_ingest_test.go @@ -44,9 +44,11 @@ func setupHookIngest(t *testing.T, stdin io.Reader) *hookIngestTest { stdout := &bytes.Buffer{} origConfig, origIn, origOut := configService, hookIngestStdin, hookIngestStdout origEnv, origNow, origArgs, origSocket := hookIngestGetenv, hookIngestNow, hookIngestRawArgs, trackSocketPath + origGetwd := hookIngestGetwd t.Cleanup(func() { configService, hookIngestStdin, hookIngestStdout = origConfig, origIn, origOut hookIngestGetenv, hookIngestNow, hookIngestRawArgs, trackSocketPath = origEnv, origNow, origArgs, origSocket + hookIngestGetwd = origGetwd }) configService = mc hookIngestStdin = stdin @@ -54,6 +56,7 @@ func setupHookIngest(t *testing.T, stdin io.Reader) *hookIngestTest { hookIngestGetenv = func(string) string { return "" } hookIngestNow = func() time.Time { return time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC) } hookIngestRawArgs = func() []string { return nil } + hookIngestGetwd = func() (string, error) { return "/home/antigravity/server", nil } trackSocketPath = filepath.Join(home, "no-daemon.sock") return &hookIngestTest{home: home, stdout: stdout, config: mc} } @@ -604,3 +607,72 @@ func TestUserHooksRecord_ProjectCommandsInTheUserFile(t *testing.T) { assert.False(t, userHooksRecord(agenthook.AgentCursor, "stop"), "the project hook must not leave the event to itself") } + +func TestHookIngest_ShellCommandWithoutDaemonSavesEvent(t *testing.T) { + h := setupHookIngest(t, strings.NewReader("cd ~/server && go test ./...\n")) + h.config.On("ReadConfigFile", mock.Anything).Return(model.ShellTimeConfig{}, nil) + + h.run(t, "--agent", "agy", "--event", "ShellCommand", "--session", "f35305b9", "--exit-code", "1", "--duration-ms", "1520") + + assert.Empty(t, h.stdout.String(), "no agent waits for a reply") + events := pendingHookEvents(t) + require.Len(t, events, 1) + ev := events[0] + assert.Equal(t, agenthook.AgentAntigravity, ev.Agent) + assert.Equal(t, "f35305b9", ev.SessionID) + assert.Equal(t, agenthook.HookEventShellCommand, ev.HookEventName) + assert.Equal(t, agenthook.EventToolFailure, ev.EventType) + assert.Equal(t, "exit status 1", ev.Error) + assert.Equal(t, agenthook.AntigravityShellTool, ev.ToolName) + assert.Equal(t, "cd ~/server && go test ./...", ev.Command) + assert.Equal(t, "/home/antigravity/server", ev.Workspace, "the folder the command ended in") + assert.Equal(t, int64(1520), ev.DurationMs) + assert.Equal(t, "2026-11-27T09:00:00Z", ev.Timestamp) + assert.NotEmpty(t, ev.Hostname) +} + +func TestHookIngest_ShellCommandSendsToDaemon(t *testing.T) { + h := setupHookIngest(t, strings.NewReader("ls -la")) + socketPath, got := fakeHookDaemon(t, `{"status":"ok"}`) + trackSocketPath = socketPath + + h.run(t, "--agent", "agy", "--event", "ShellCommand", "--session", "s1") + + assert.Empty(t, h.stdout.String()) + select { + case msg := <-got: + assert.Equal(t, daemon.SocketMessageTypeAgentHook, msg.Type) + raw, err := json.Marshal(msg.Payload) + require.NoError(t, err) + var ev agenthook.Event + require.NoError(t, json.Unmarshal(raw, &ev)) + assert.Equal(t, "s1", ev.SessionID) + assert.Equal(t, agenthook.EventToolUse, ev.EventType) + assert.Equal(t, "ls -la", ev.Command) + assert.Zero(t, ev.DurationMs, "no --duration-ms, no duration") + assert.False(t, ev.YieldToUserHooks) + case <-time.After(2 * time.Second): + t.Fatal("the daemon got nothing") + } + assert.Empty(t, pendingHookEvents(t)) +} + +func TestHookIngest_ShellCommandRecordsNothingWithoutASession(t *testing.T) { + h := setupHookIngest(t, strings.NewReader("ls")) + + h.run(t, "--agent", "agy", "--event", "ShellCommand", "--exit-code", "0") + + assert.Empty(t, h.stdout.String()) + assert.Empty(t, pendingHookEvents(t)) +} + +func TestHookIngest_ShellCommandWithBadFlagsRecordsNothing(t *testing.T) { + args := []string{"--agent", "agy", "--event", "ShellCommand", "--session", "s1", "--exit-code", "abc"} + h := setupHookIngest(t, strings.NewReader("ls")) + hookIngestRawArgs = func() []string { return append([]string{"shelltime", "hook-ingest"}, args...) } + + h.run(t, args...) + + assert.Empty(t, h.stdout.String(), "not even a hook's reply") + assert.Empty(t, pendingHookEvents(t)) +}