Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions registry/coder/modules/agent-relay-cursor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
---
display_name: Agent Relay Cursor
description: Serves Cursor cloud agent requests in Coder workspaces that Agent Relay dispatches.
icon: ../../../../.icons/cursor.svg
verified: true
tags: [agent, cursor, agent-relay]
---

# Agent Relay Cursor

Makes a Coder template a target for [Agent Relay](https://coder.com/docs/ai-coder/agent-relay)
Cursor pools. Agent Relay dispatches [Cursor cloud agent](https://coder.com/docs/ai-coder/agent-relay/cursor)
requests to workspaces built from the template; the module declares the
parameters the relay stamps on each build and runs the Cursor CLI worker.

```tf
module "cursor_worker" {
source = "registry.coder.com/coder/agent-relay-cursor/coder"
version = "0.1.0"
agent_id = coder_agent.main.id

# Downloads the Cursor CLI at start when it is not in the image. Bake
# the CLI into the image and set this to false for faster workspaces.
install_cli = true
}

resource "coder_agent" "main" {
# ...
metadata {
key = "agent_relay_status"
display_name = "Worker"
script = module.cursor_worker.status_metadata_script
interval = 10
timeout = 5
}
}
```

The `agent_relay_status` metadata block is required. It has to live on the
`coder_agent`, which the module cannot declare; the relay reads it to decide
when to reap the workspace.

## Requirements

- The Cursor CLI (`agent`) must be in the workspace. `install_cli` (default
`true`) downloads it at start only when it is not already on PATH; bake it
into the image for the fastest start. `cli_binary` overrides the path.
- Repo-scoped pools: the template must clone `agent_relay_cursor_repo_url` and
provide SCM credentials before this module's script runs.
- `computer_use = true` needs the computer-use packages in the image.
- Builds must finish inside the pool's `dispatch_deadline` (default 10m, max
15m): pre-pulled images, no persistent volumes.

## Credential exposure

The pool's service-account API key is stamped on every dispatched workspace as
the ephemeral `agent_relay_credential` parameter and exported as
`CURSOR_API_KEY`, readable by the workspace owner. Use a dedicated key per
pool, scoped to the repository it serves. Rotating it affects new builds only.

## Parameters

Agent Relay verifies this contract against the template's active version at
startup and refuses to serve a pool that does not satisfy it. Every parameter
renders disabled with a "Set by Agent Relay on dispatch" placeholder; the
credential is masked.

| parameter | kind | value |
| ----------------------------------------- | ---------- | ----------------------------------------------------------------- |
| `agent_relay_session_id` | persistent | Cursor request this workspace serves |
| `agent_relay_delivery_id` | persistent | worker id the request was claimed with (`CURSOR_AGENT_WORKER_ID`) |
| `agent_relay_pool` | persistent | Agent Relay pool that dispatched the build |
| `agent_relay_cursor_pool_name` | persistent | Cursor-side pool the worker registers under |
| `agent_relay_cursor_idle_release_timeout` | persistent | seconds the worker idles after a turn before exiting (min 300) |
| `agent_relay_cursor_repo_url` | persistent | repository the request targets; empty for repo-less pools |
| `agent_relay_credential` | ephemeral | service-account API key (`CURSOR_API_KEY`) |

## Worker lifecycle

The script starts `agent worker --pool ... --idle-release-timeout ... start`
detached and exits, so the agent reaches `ready` immediately. The worker exits
`0` when its idle-release timer fires after a session; that clean exit is what
tells Agent Relay to delete the workspace. The timer starts when the agent
finishes a turn, not when the chat closes, so keep the timeout at or above
300 seconds.

`agent_relay_status` reports one of:

| value | meaning |
| ----------------- | -------------------------------------------------------------------------- |
| `pending` | no state recorded yet |
| `idle` | no credential: workspace was created manually |
| `working` | worker alive, no session attached |
| `serving` | worker alive, session attached (best effort, see `serving_log_pattern`) |
| `orphaned` | worker process gone without recording an exit |
| `done <code>` | worker exited with that status; `0` is the normal idle release |
| `failed <reason>` | worker could not start, e.g. `runner-agent-missing` when the CLI is absent |

Renaming the `agent_relay_status` key breaks reaping.
203 changes: 203 additions & 0 deletions registry/coder/modules/agent-relay-cursor/main.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import {
afterEach,
beforeAll,
describe,
expect,
it,
setDefaultTimeout,
} from "bun:test";
import {
execContainer,
findResourceInstance,
readFileContainer,
removeContainer,
runContainer,
runTerraformApply,
runTerraformInit,
testRequiredVariables,
writeFileContainer,
} from "~test";

// The worker script is exercised inside a throwaway container with a stub
// `agent` binary standing in for the Cursor CLI, so the supervisor lifecycle
// the relay's reaper depends on (idle, working, done, failed) is observed
// rather than grepped for. The real installer and the real worker are out
// of scope: both need the network and Cursor's side.

let cleanupFunctions: (() => Promise<void>)[] = [];
const registerCleanup = (cleanup: () => Promise<void>) => {
cleanupFunctions.push(cleanup);
};
afterEach(async () => {
const cleanupFnsCopy = cleanupFunctions.slice().reverse();
cleanupFunctions = [];
for (const cleanup of cleanupFnsCopy) {
try {
await cleanup();
} catch (error) {
console.error("Error during cleanup:", error);
}
}
});

const STATE_FILE = "/tmp/agent-relay/worker-state";
const DISPATCH_ENV = [
"CURSOR_API_KEY=test-service-account-key",
"CURSOR_AGENT_WORKER_ID=worker-123",
];

const setup = async (vars: Record<string, string> = {}) => {
const state = await runTerraformApply(import.meta.dir, {
agent_id: "foo",
...vars,
});
const script = findResourceInstance(state, "coder_script").script;
const id = await runContainer("lorello/alpine-bash");
registerCleanup(async () => {
await removeContainer(id);
});
return { id, script };
};

// Installs a fake Cursor CLI whose body is the given shell snippet.
const stubAgent = async (id: string, body: string) => {
await writeFileContainer(
id,
"/usr/local/bin/agent",
`#!/usr/bin/env bash\n${body}\n`,
{ user: "root" },
);
const chmod = await execContainer(id, [
"chmod",
"755",
"/usr/local/bin/agent",
]);
expect(chmod.exitCode).toBe(0);
};

const runDispatched = (id: string, script: string) =>
execContainer(id, ["env", ...DISPATCH_ENV, "bash", "-c", script]);

const readState = async (id: string) =>
(await readFileContainer(id, STATE_FILE)).trim();

// The supervisor writes terminal state after the worker exits; poll rather
// than sleep a fixed amount.
const waitForState = async (id: string, pattern: RegExp, timeoutMs = 5000) => {
const deadline = Date.now() + timeoutMs;
let last = "";
while (Date.now() < deadline) {
last = await readState(id);
if (pattern.test(last)) {
return last;
}
await Bun.sleep(200);
}
throw new Error(
`state never matched ${pattern}; last was ${JSON.stringify(last)}`,
);
};

setDefaultTimeout(60 * 1000);

describe("agent-relay-cursor", () => {
beforeAll(async () => {
await runTerraformInit(import.meta.dir);
});

testRequiredVariables(import.meta.dir, {
agent_id: "foo",
});

it("idles when no credential is set", async () => {
const { id, script } = await setup();
// No CURSOR_API_KEY: this is a workspace a human created by hand.
const exec = await execContainer(id, ["bash", "-c", script]);
expect(exec.exitCode).toBe(0);
expect(exec.stdout).toContain("created manually, not by Agent Relay");
expect(await readState(id)).toBe("idle");
});

it("reports runner-agent-missing when the CLI is absent", async () => {
const { id, script } = await setup({ install_cli: "false" });
const exec = await runDispatched(id, script);
expect(exec.exitCode).toBe(1);
expect(exec.stderr).toContain("The worker binary 'agent' is not available");
expect(await readState(id)).toBe("failed runner-agent-missing");
});

it("skips the download when the CLI is already present", async () => {
// install_cli defaults to true; a binary on PATH must short-circuit it.
const { id, script } = await setup();
await stubAgent(id, "sleep 30");
const exec = await runDispatched(id, script);
expect(exec.exitCode).toBe(0);
expect(exec.stdout).toContain(
"Cursor CLI already present; skipping the install.",
);
expect(exec.stdout).not.toContain("installing the latest release");
expect(await readState(id)).toMatch(/^working \d+$/);
});

it("starts the worker detached with the pool arguments", async () => {
const { id, script } = await setup();
await stubAgent(id, 'printf "%s\\n" "$@" >/tmp/agent-args; sleep 30');
const exec = await runDispatched(id, script);
expect(exec.exitCode).toBe(0);
expect(exec.stdout).toContain("Starting Cursor worker (detached)...");

const args = (await readFileContainer(id, "/tmp/agent-args")).split("\n");
expect(args[0]).toBe("worker");
expect(args).toContain("--pool");
expect(args).toContain("--idle-release-timeout");
// The parameter default when Agent Relay has not stamped a value.
expect(args[args.indexOf("--idle-release-timeout") + 1]).toBe("600");
expect(args).toContain("start");
expect(args).not.toContain("--computer-use");

// The worker inherits the CLI's own env var names, not the relay's.
const env = await execContainer(id, [
"sh",
"-c",
"cat /proc/$(pgrep -f 'agent worker' | head -1)/environ | tr '\\0' '\\n'",
]);
expect(env.stdout).toContain("CURSOR_API_KEY=test-service-account-key");
expect(env.stdout).toContain("CURSOR_AGENT_WORKER_ID=worker-123");
});

it("passes --computer-use when enabled", async () => {
const { id, script } = await setup({ computer_use: "true" });
await stubAgent(id, 'printf "%s\\n" "$@" >/tmp/agent-args; sleep 30');
const exec = await runDispatched(id, script);
expect(exec.exitCode).toBe(0);
const args = (await readFileContainer(id, "/tmp/agent-args")).split("\n");
expect(args).toContain("--computer-use");
});

it("records the exit code when the worker exits", async () => {
const { id, script } = await setup();
await stubAgent(id, "exit 3");
const exec = await runDispatched(id, script);
expect(exec.exitCode).toBe(0);
expect(await waitForState(id, /^done \d+$/)).toBe("done 3");
});

it("uses cli_binary and state_file overrides", async () => {
const { id, script } = await setup({
cli_binary: "/opt/cursor/agent",
state_file: "/var/lib/relay/state",
});
await execContainer(id, ["mkdir", "-p", "/opt/cursor"]);
await writeFileContainer(
id,
"/opt/cursor/agent",
"#!/usr/bin/env bash\nsleep 30\n",
{ user: "root" },
);
await execContainer(id, ["chmod", "755", "/opt/cursor/agent"]);
const exec = await runDispatched(id, script);
expect(exec.exitCode).toBe(0);
const state = (await readFileContainer(id, "/var/lib/relay/state")).trim();
expect(state).toMatch(/^working \d+$/);
});
});
Loading