Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .surface-skill-drift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ CMD basecamp connect release
CMD basecamp connect shadow promote
CMD basecamp connect show
CMD basecamp connect status
# The connector doing the work itself (--orchestrator): hidden with the rest.
FLAG basecamp --orchestrator
FLAG basecamp --run
CMD basecamp connect restart
CMD basecamp connect say
CMD basecamp connect stop
CMD basecamp connect workers list
FLAG basecamp --unserve
# Per-Campfire policy flags on the hidden connect setup command.
FLAG basecamp --listen-campfire
Expand Down
56 changes: 56 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,62 @@ picker's `(Global)` row, the prose lists in the installers and the docs are the
by hand. `setup <id>` never fabricates an agent's home directory: a skill-only agent that is not
detected is reported missing, not created.

## The connector doing the work itself

`basecamp connect -P <profile>` prints each trusted request for the session that started it,
which is how the basecamp-connect skill runs in Claude Code. With `--orchestrator <agent>` the
connector does that session's job itself, on any coding agent that can take a prompt without a
terminal, run shell commands and continue an earlier session. `internal/connector/runner` is
all of it:

- **The workflow is the skill.** `skills/basecamp-connect/SKILL.md` and `subagent.md` are
embedded (`skills.Connect`) and given to the agents as they are. `instructions.go` adds only
the table that maps the Claude Code mechanisms they name (the monitor, background subagents)
onto the runner's commands. Change behavior in the skill, never there.
- **An adapter is one CLI**: the arguments of a headless turn and how its event stream reads
(`adapter.go`: `claude -p`, `codex exec`, `pi -p`). A new coding agent is a new adapter and a
stream fixture in `adapter_test.go`. `go test -tags runner_live ./internal/connector/runner
-run TestInstalled` holds each adapter to the installed CLI and spends a few model requests.
- **The orchestrator's tools are CLI commands** that reach the running connector over a unix
socket in its state directory: `basecamp connect dispatch`, `workers list|send|stop`, `say`,
`stop`, `restart` (`internal/commands/connect_runner.go`).
- **Which agent does what**: the start's flags, then `runner.json` beside the profile's
`connect.json` (hand-written, read again for every dispatch), whose rules choose a worker by
repo, project, card table, to-do list, any recording a request sits under, or a Ping.
- **A worker is kept for its thread.** A later request on the same card, to-do, message or
chat goes to the worker that handled the first, continued in its session, and waits its turn
if that worker is busy. A new worker starts only when the session cannot take it: the work
is in another repo or on another coding agent, `--again` was given, or the CLI no longer
has the session. The orchestrator's own session is never rotated; each CLI's compaction is
relied on, and both kinds of session are told where their instructions are kept.
- **State** is `runner/state.json` in the connector's state directory: the orchestrator's
inbox and session, and every worker. The handoff gives the runner each request before it
closes the record (`HandoffOptions.Deliver`), so a crash repeats a request rather than
losing it if the connector starts again within `HandoffGrace` (a minute), and a worker a
stop interrupted is continued in its own session at the next start. A start ends what a
crash left running first, and does not start beside a process it cannot confirm ended; a
turn's process is recorded before its agent is told anything, and a session is not given
another turn while what its last one started cannot be confirmed ended.

**What agents may do** is one switch, `--permissions`, kept in `runner.json` and read for
every turn. `full`, the default, starts each CLI with its permission prompts off: a headless
turn has nobody to answer one. `guarded` starts each under its own unattended guardrails
(`Adapter.Guarded`): Claude Code in its auto mode, and Codex in its workspace-write sandbox
with the network on and its automatic review, which lets Codex's own reviewer answer a
request to run a stopped command outside the sandbox. Without that review a sandboxed Codex
can neither commit in a repo (its git data is read-only there) nor read `connect.json`
(inside the sandbox `/` belongs to nobody the CLI knows, so the check that the file is the
person's own fails). That check is the trust anchor's and is not loosened: instead an agent
is told which runner started it (`runner.SocketEnv`), so `dispatch` and the other runner commands
reach the socket without reading the file. Pi has no guardrails and is refused under
`guarded`. What a mode means is told to the worker (`guardedNote`), the person at start
(`PermissionsNotice`) and in the skill; keep the three in step. A `runner.json` that cannot
be read starts no agent: it is never read as `full`.

**What a start names is kept** (`SaveStart`): the orchestrator, the worker and the
permissions go into `runner.json`, and `--run` starts with them. Plain `basecamp connect`
never reads them, so the Claude Code skill's path is untouched.

## Basecamp API Reference

API documentation: https://github.com/basecamp/bc3-api
Expand Down
61 changes: 59 additions & 2 deletions internal/commands/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,56 @@ off nothing. --hold sets this profile's durable hold: intake and admission run,
nothing is handed off, and earlier records wait for review, until basecamp
connect release for this profile. Linux and macOS only.

With --orchestrator the connector does the work itself, with no session
reading its output: each trusted request goes to a headless session of the
coding agent named (claude, codex or pi), which follows the basecamp-connect
skill and hands the work to a worker, a session of its own on the coding
agent --worker names (the orchestrator's by default), in the repo the request
belongs to. --orchestrator-model, --orchestrator-effort, --worker-model and
--worker-effort choose models and reasoning effort; without them each coding
agent uses its own defaults.

basecamp connect -P <profile> --orchestrator claude --worker codex
basecamp connect -P <profile> --run

What a start names is kept for the profile, so the next one is --run. Plain
basecamp connect, with none of these, still only prints requests.

Agents run unattended, as you. --permissions says what they may do:

full Any command and any file, without asking first, since nobody is
at the keyboard to approve each step. The default.
guarded Each coding agent under its own guardrails. Claude Code runs in
its auto mode: it judges each action and stops the ones it finds
unsafe. Codex runs each command in its sandbox, where it writes
only in the folder it works in and the temporary directory, and
decides itself whether a command the sandbox stopped may run
outside it. Nobody is asked either way. Pi has no guardrails, and
is refused.

An agent that is stopped says so in its reply. Who may give the agent work
is setup's, and by default it is only its operator: basecamp connect show.

A runner.json beside the profile's connect.json chooses workers by where a
request came from and which repo its work goes in. The first rule that
matches wins, and what its worker leaves out comes from how the connector was
started:

{"worker": {"adapter": "codex", "effort": "medium"},
"rules": [
{"repo": "~/code/app", "worker": {"adapter": "claude", "model": "opus"}},
{"card_table": 123, "worker": {"effort": "high"}},
{"project": 456, "worker": {"adapter": "pi"}},
{"ping": true, "worker": {"adapter": "claude", "model": "haiku"}}]}

The rules and the permissions are read again for each request, so an edit to
them needs no restart. The worker at the top is what the connector starts
with.

basecamp connect say "<message>" talk to the orchestrator
basecamp connect workers list the workers and what each runs on
basecamp connect stop stop it; restart starts it again

One connector runs per profile in this state directory. An agent can run
several connections where Basecamp enables adding them for its kind; otherwise
a new approval replaces the existing connection. Each profile
Expand Down Expand Up @@ -100,12 +150,19 @@ status and doctor say which this profile's does.
"stdout_wire": "connect",
},
RunE: func(cmd *cobra.Command, _ []string) error {
return runConnect(cmd, &run)
err := runConnect(cmd, &run)
if errors.Is(err, errConnectRestart) {
// Everything the run held is released: the same command
// takes this process over and starts from the beginning.
return connectReexec()
}
return err
},
}
addConnectRunFlags(cmd, &run)
cmd.AddCommand(newConnectSetupCmd(), newConnectShowCmd(), newConnectStatusCmd(), newConnectDoctorCmd(),
newConnectDiscardCmd(), newConnectAskCmd(), newConnectReleaseCmd(), newConnectShadowCmd(), newConnectImportCmd())
newConnectDiscardCmd(), newConnectAskCmd(), newConnectReleaseCmd(), newConnectShadowCmd(), newConnectImportCmd(),
newConnectDispatchCmd(), newConnectWorkersCmd(), newConnectSayCmd(), newConnectStopCmd(), newConnectRestartCmd())
return cmd
}

Expand Down
6 changes: 6 additions & 0 deletions internal/commands/connect_process_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

package commands

import "errors"

// Process presence, as much as a reader can say without taking a lock.
const (
pidPresent = "present"
Expand All @@ -12,3 +14,7 @@ const (
// processPresence cannot be answered here — the connector runs on macOS and
// Linux — so it says so rather than calling a pid absent.
func processPresence(int) string { return pidUnknown }

// connectReexec cannot start the connector again here: it runs on macOS and
// Linux.
func connectReexec() error { return errors.New("the connector cannot restart itself on this platform") }
12 changes: 12 additions & 0 deletions internal/commands/connect_process_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package commands

import (
"errors"
"os"
"syscall"
)

Expand All @@ -30,3 +31,14 @@ func processPresence(pid int) string {
return pidUnknown
}
}

// connectReexec starts the connector again in this process, with the
// arguments and environment it was started with. It returns only when it
// could not.
func connectReexec() error {
executable, err := os.Executable()
if err != nil {
return err
}
return syscall.Exec(executable, os.Args, os.Environ()) //nolint:gosec // G204: this binary, with its own arguments
}
66 changes: 66 additions & 0 deletions internal/commands/connect_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
Expand All @@ -13,6 +14,7 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"

"github.com/spf13/cobra"
Expand All @@ -26,6 +28,7 @@ import (
"github.com/basecamp/basecamp-cli/internal/connector"
"github.com/basecamp/basecamp-cli/internal/connector/admission"
"github.com/basecamp/basecamp-cli/internal/connector/ndjson"
"github.com/basecamp/basecamp-cli/internal/connector/runner"
"github.com/basecamp/basecamp-cli/internal/connector/setup"
"github.com/basecamp/basecamp-cli/internal/output"
"github.com/basecamp/basecamp-cli/internal/richtext"
Expand All @@ -43,6 +46,8 @@ type connectRunFlags struct {
// --pings=false is a choice, not the flag's absence.
pingsSet bool
noPingsSet bool
// runner turns on the runner: the connector does the work itself.
runner connectRunnerFlags
}

func addConnectRunFlags(cmd *cobra.Command, f *connectRunFlags) {
Expand All @@ -55,6 +60,7 @@ func addConnectRunFlags(cmd *cobra.Command, f *connectRunFlags) {
fl.BoolVar(&f.shadow, "shadow", false, "Admit and log in an isolated state directory; dispatch and post nothing")
fl.Int64Var(&f.since, "since", 0, "Enter the feed just after this event id, whatever the ledger holds")
fl.BoolVar(&f.hold, "hold", false, "Set this profile's durable hold: intake and admission run, nothing is dispatched or posted until release, and earlier records wait for review")
addConnectRunnerFlags(cmd, &f.runner)
}

func connectStateHome() (string, error) {
Expand Down Expand Up @@ -216,6 +222,18 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
case err != nil:
return output.ErrUsage("connect.json cannot be used: " + err.Error())
}
// Which coding agents do the work, when the run does it itself: settled
// before anything is read from Basecamp, so a mistyped agent or one that
// is not installed ends the start rather than the first request.
var start connectRunnerStart
if f.runner.requested() {
if f.shadow {
return output.ErrUsage("A shadow run hands nothing off, so it has no orchestrator: drop --shadow, or the orchestrator and worker flags")
}
if start, err = connectRunnerSettle(f.runner, connectRunnerConfigPath(path)); err != nil {
return err
}
Comment thread
robzolkos marked this conversation as resolved.
Resolved
}

account, err := connectAccount(app, name)
if err != nil {
Expand Down Expand Up @@ -317,6 +335,13 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
return err
}
defer func() { _ = lock.Release() }()
if f.runner.requested() {
// Under the lock, the identity verified: what this start named is
// kept for the profile only now that the start is going ahead.
if err := start.keep(connectRunnerConfigPath(path)); err != nil {
return err
}
}
pings, savePings, err := connectRunPings(lock, name, file, f.shadow, pingsFlag, len(buckets) > 0, creds)
if err != nil {
return err
Expand Down Expand Up @@ -365,6 +390,20 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
"since", hold.HeldAt, "by", richtext.SanitizeSingleLine(hold.HeldBy))
}
lines := ndjson.NewWriter(cmd.OutOrStdout())
var connectorLog *os.File
if f.runner.requested() {
// The orchestrator searches the connector's output the way the skill
// searches the output file of a connector it started, so the lines
// are kept as well as printed.
if _, err := ensurePrivateChain(stateDir, filepath.Base(connectRunnerDir(stateDir))); err != nil {
return output.ErrUsage("The connector's state directory cannot be used: " + err.Error())
}
if connectorLog, err = openConnectorLog(connectRunnerDir(stateDir)); err != nil {
return err
}
defer func() { _ = connectorLog.Close() }()
lines = ndjson.NewWriter(io.MultiWriter(cmd.OutOrStdout(), connectorLog))
}

queue, err := connector.NewQueue(connector.DefaultBacklogWarn, connector.DefaultBacklogPause)
if err != nil {
Expand Down Expand Up @@ -429,6 +468,27 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
os.Exit(connector.ExitCodeForSignal(sig))
}()

// The runner, when the run does the work itself. Its stop is the one the
// orchestrator or the person asks for with `basecamp connect stop`.
var (
work *runner.Runner
restart atomic.Bool
deliver func(context.Context, connector.HandoffLine) error
)
if f.runner.requested() {
startLine := fmt.Sprintf("It runs as profile %s; pings=%t (%s).", name, heard.Hears, heard.Describe())
work, err = newConnectRunner(name, stateDir, path, start.orchestrator, start.worker, connectorLog, startLine, reads.Summaries, connectOnHoldAbove(accountClient, logger), ledger.Held,
func(again bool) {
restart.Store(again)
logger.Info("connector: stopping, asked through its runner", "restart", again)
cancel()
}, logger)
if err != nil {
return output.ErrUsage("The runner cannot start: " + err.Error())
}
deliver = work.Deliver
}

stopState, stopDetail := connector.ConnectionStopped, ""
defer func() {
// Whatever ended the run, status says it is not running any more.
Expand Down Expand Up @@ -483,9 +543,13 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
Ledger: ledger, Served: served.Current, Buckets: buckets, Pings: policy.HearsPings, AgentID: agentID,
Lines: lines, Logger: logger, Started: started,
AckContent: file.Ack().Content, Booster: connector.SDKBooster{Client: accountClient},
Deliver: deliver,
})
})
}
if work != nil {
runPart("runner", work.Run)
Comment thread
robzolkos marked this conversation as resolved.
Resolved
}
wg.Wait()

mu.Lock()
Expand All @@ -504,6 +568,8 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
return err
case ctx.Err() != nil:
return ctx.Err()
case restart.Load():
return errConnectRestart
}
return nil
}
Expand Down
Loading
Loading