Skip to content

Commit 48b01aa

Browse files
authored
Let the connector do the work itself, on the coding agent you choose (#1026)
* Let the handoff deliver each request before it closes the record The handoff writes a trusted request to stdout and then closes its record, which is all a reader of the lines needs. A run that does the work itself needs the request kept somewhere of its own first: closed before it is kept, a crash between the two loses a request that was already acknowledged. HandoffOptions.Deliver is called after the line is written and before the record is closed, and returns once the request is kept. A delivery that fails leaves the record open, so the request is delivered again. Nil delivers nowhere, which is every run today. * Add the connector's runner: an orchestrator and workers on a coding agent's CLI The basecamp-connect skill runs in a Claude Code session and leans on two things only that harness has: a monitor that wakes the session for each request line, and background subagents. The runner supplies both from the CLI, so the same skill can run on any coding agent that takes a prompt without a terminal, runs shell commands and continues an earlier session. Each request the connector hands off is kept in the runner's state and given to an orchestrator, one turn of a headless session at a time. The orchestrator follows SKILL.md as it ships and hands the work to a worker, a session of its own that follows subagent.md and reports back as another turn. The runner adds only a table that maps the mechanisms the skill names onto its commands. An adapter is one CLI: the arguments of a turn and how its event stream reads. A turn is one process, started through driver.StartWorker as the leader of a process group the runner can end whole. - 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 that session cannot take it. - A worker a stop interrupted is continued at the next start and told so. A process a crash left running is ended, by its recorded process group, before its session is continued. - runner.json, beside connect.json, chooses a worker's coding agent, model and effort by repo, project, card table, to-do list, containing recording or Ping, and keeps what the connector was last started with. - Permissions are one switch. Full starts each CLI with its prompts off, since a headless turn has nobody to answer one. Guarded starts each under its own unattended guardrails, and refuses a CLI that has none. The adapters are held to the installed CLIs by an opt-in test: go test -tags runner_live ./internal/connector/runner -run TestInstalled * Run the connector with an orchestrator, and add the commands its agents use basecamp connect -P <profile> --orchestrator <agent> does the work itself instead of printing requests for a session to read. --worker names another coding agent for the work, the model and effort flags choose those, and --permissions chooses full or guarded. What a start names is kept for the profile, and --run starts with it. Without any of these the connector is what it was. The orchestrator's tools are commands that reach the running connector over a unix socket in its state directory: dispatch hands a request to a worker, workers list, send and stop see and steer them, say talks to the orchestrator from a terminal, and stop and restart end the connector or start it again. An agent the connector starts is told which runner started it, so these commands reach the socket from inside a coding agent's sandbox, where the ownership of connect.json cannot be checked. The check is unchanged. * Describe running without a session in the basecamp-connect skill The skill said running the connector requires Claude Code. Watching it from a session still does. A new section, after everything a session following the original flow reads, says how to start the connector with an orchestrator instead: which coding agent, that the choice is kept, that it has to be started where it outlives the session, what full and guarded permissions mean, and the commands for checking on it. The per-request steps stay inside the compaction budget, and the new hidden commands and flags are acknowledged in the drift baseline with the rest of connect. * Close the races and gaps the reviews found in the runner One request, one worker. Dispatch let go of its lock to read what a request sits under and did not ask again, under the lock, whether the event had got a worker meanwhile, so two dispatches arriving together could start two. A worker also has one goroutine now, whatever it is told: a message sent just after a stop, before the stopped turn had ended, started a second one on the same session. A leftover process is always ended. Starting with another orchestrator reset the session and, with it, the record of a process the last run had left, which then ran on beside the new one. What never ran is not counted. A turn refused under guarded permissions reached no agent, and no longer uses up one of a message's attempts. A `say` that could not be saved is taken back out, so a retry is not answered twice. Requests still waiting, or being worked on, are not pruned with the history. A rule's relative repo is refused when the file is read, since it could never match. What a request sits under is cached only when it was read, so a rule added later still gets its answer, and a card on hold is followed to its column and card table, which its On Hold section does not name. The socket no longer gives up on the first failed accept, and a client that sends half a request no longer holds a stop open. Standard input past its limit is refused rather than cut. A dispatch waits as long as its lookups can take. What a start names is kept once the start has its lock, not before. A failed turn's stderr has the agent's environment taken out of it, and the help's example and its claim about what is read again are corrected. * Hold the runner with the connector, and never continue beside a leftover A hold means nothing is dispatched or posted until it is released. The handoff honored it and the runner did not: started under a hold, it went on giving its orchestrator the messages it already held and starting the workers that were waiting. It now starts no agent while the hold stands, and takes up where it was when the hold is released. A process a crashed run left is ended before its session is continued. When it could not be confirmed ended, the session was continued all the same, beside whatever was still running. The recorded group now gets the rule's last step as well, which ends what a vanished leader left behind, and a group that still cannot be confirmed gone keeps its record: a worker is closed as failed, which the orchestrator is told, and an orchestrator's stops the start. The comments said a crash between writing a request and keeping it repeats the request. That holds only for a start within the handoff's grace: an older record is not run late, with a runner or without. They now say so. * Confirm every leftover ended, and keep the runner's socket to its owner A start now confirms each process a crash left is gone, after the signal as well as when the leader had already gone, and one that cannot be confirmed stops the start whichever session it was. A worker that was only set aside could still be told more, or take a later request on its thread, beside the process nobody ended. The socket's directory is checked wherever it is listened on or called: a real directory, this user's, closed to everyone else. The fallback for a long path sits under XDG_RUNTIME_DIR when there is one, and an agent is given the socket's path itself rather than the directory to derive it from. A failed lookup of a card's On Hold section is logged, and the accept loop only reads the run's end as the reason for an error when there was one. * Say where the runner's socket is, and vouch for nothing off Unix A socket that cannot sit in the runner's directory, because the path is too long for an address, went wherever the environment of the moment said, so a command started with another environment looked somewhere else and reported the running connector absent. The connector now keeps where it listens beside its state, and a call reads that. The runtime directory is used only when the whole path fits an address. The directory check compares the effective user, as the connector's other ownership checks do, and off Unix it refuses rather than passing everything. * Hold each turn to the rule a start keeps, and undo what could not be saved A start does not begin beside a process it cannot confirm ended. A turn is now held to the same: - The record of a turn's process goes only once nothing of its process group is left. One that stays fails its worker, is asked after again before that session's next turn, orchestrator or worker, and is the next start's to end. - An agent whose process could not be written to the state is ended before it is told anything, and reported as one that could not run. A worker continued after a stop is given what it was last on along with the notice that it was interrupted: a stop just after its turn began may have come before its session had the request. A dispatch to a thread's earlier worker, or a message sent to a worker, that could not be saved leaves the worker as it was, rather than queued with nobody to run it. * Say plainly why an interrupted worker is given its request again * Keep a finished worker whose process is still named
1 parent 6e7d817 commit 48b01aa

28 files changed

Lines changed: 6801 additions & 4 deletions

‎.surface-skill-drift‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ CMD basecamp connect release
3333
CMD basecamp connect shadow promote
3434
CMD basecamp connect show
3535
CMD basecamp connect status
36+
# The connector doing the work itself (--orchestrator): hidden with the rest.
37+
FLAG basecamp --orchestrator
38+
FLAG basecamp --run
39+
CMD basecamp connect restart
40+
CMD basecamp connect say
41+
CMD basecamp connect stop
42+
CMD basecamp connect workers list
3643
FLAG basecamp --unserve
3744
# Per-Campfire policy flags on the hidden connect setup command.
3845
FLAG basecamp --listen-campfire

‎AGENTS.md‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,62 @@ picker's `(Global)` row, the prose lists in the installers and the docs are the
5959
by hand. `setup <id>` never fabricates an agent's home directory: a skill-only agent that is not
6060
detected is reported missing, not created.
6161

62+
## The connector doing the work itself
63+
64+
`basecamp connect -P <profile>` prints each trusted request for the session that started it,
65+
which is how the basecamp-connect skill runs in Claude Code. With `--orchestrator <agent>` the
66+
connector does that session's job itself, on any coding agent that can take a prompt without a
67+
terminal, run shell commands and continue an earlier session. `internal/connector/runner` is
68+
all of it:
69+
70+
- **The workflow is the skill.** `skills/basecamp-connect/SKILL.md` and `subagent.md` are
71+
embedded (`skills.Connect`) and given to the agents as they are. `instructions.go` adds only
72+
the table that maps the Claude Code mechanisms they name (the monitor, background subagents)
73+
onto the runner's commands. Change behavior in the skill, never there.
74+
- **An adapter is one CLI**: the arguments of a headless turn and how its event stream reads
75+
(`adapter.go`: `claude -p`, `codex exec`, `pi -p`). A new coding agent is a new adapter and a
76+
stream fixture in `adapter_test.go`. `go test -tags runner_live ./internal/connector/runner
77+
-run TestInstalled` holds each adapter to the installed CLI and spends a few model requests.
78+
- **The orchestrator's tools are CLI commands** that reach the running connector over a unix
79+
socket in its state directory: `basecamp connect dispatch`, `workers list|send|stop`, `say`,
80+
`stop`, `restart` (`internal/commands/connect_runner.go`).
81+
- **Which agent does what**: the start's flags, then `runner.json` beside the profile's
82+
`connect.json` (hand-written, read again for every dispatch), whose rules choose a worker by
83+
repo, project, card table, to-do list, any recording a request sits under, or a Ping.
84+
- **A worker is kept for its thread.** A later request on the same card, to-do, message or
85+
chat goes to the worker that handled the first, continued in its session, and waits its turn
86+
if that worker is busy. A new worker starts only when the session cannot take it: the work
87+
is in another repo or on another coding agent, `--again` was given, or the CLI no longer
88+
has the session. The orchestrator's own session is never rotated; each CLI's compaction is
89+
relied on, and both kinds of session are told where their instructions are kept.
90+
- **State** is `runner/state.json` in the connector's state directory: the orchestrator's
91+
inbox and session, and every worker. The handoff gives the runner each request before it
92+
closes the record (`HandoffOptions.Deliver`), so a crash repeats a request rather than
93+
losing it if the connector starts again within `HandoffGrace` (a minute), and a worker a
94+
stop interrupted is continued in its own session at the next start. A start ends what a
95+
crash left running first, and does not start beside a process it cannot confirm ended; a
96+
turn's process is recorded before its agent is told anything, and a session is not given
97+
another turn while what its last one started cannot be confirmed ended.
98+
99+
**What agents may do** is one switch, `--permissions`, kept in `runner.json` and read for
100+
every turn. `full`, the default, starts each CLI with its permission prompts off: a headless
101+
turn has nobody to answer one. `guarded` starts each under its own unattended guardrails
102+
(`Adapter.Guarded`): Claude Code in its auto mode, and Codex in its workspace-write sandbox
103+
with the network on and its automatic review, which lets Codex's own reviewer answer a
104+
request to run a stopped command outside the sandbox. Without that review a sandboxed Codex
105+
can neither commit in a repo (its git data is read-only there) nor read `connect.json`
106+
(inside the sandbox `/` belongs to nobody the CLI knows, so the check that the file is the
107+
person's own fails). That check is the trust anchor's and is not loosened: instead an agent
108+
is told which runner started it (`runner.SocketEnv`), so `dispatch` and the other runner commands
109+
reach the socket without reading the file. Pi has no guardrails and is refused under
110+
`guarded`. What a mode means is told to the worker (`guardedNote`), the person at start
111+
(`PermissionsNotice`) and in the skill; keep the three in step. A `runner.json` that cannot
112+
be read starts no agent: it is never read as `full`.
113+
114+
**What a start names is kept** (`SaveStart`): the orchestrator, the worker and the
115+
permissions go into `runner.json`, and `--run` starts with them. Plain `basecamp connect`
116+
never reads them, so the Claude Code skill's path is untouched.
117+
62118
## Basecamp API Reference
63119

64120
API documentation: https://github.com/basecamp/bc3-api

‎internal/commands/connect.go‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,56 @@ off nothing. --hold sets this profile's durable hold: intake and admission run,
6464
nothing is handed off, and earlier records wait for review, until basecamp
6565
connect release for this profile. Linux and macOS only.
6666
67+
With --orchestrator the connector does the work itself, with no session
68+
reading its output: each trusted request goes to a headless session of the
69+
coding agent named (claude, codex or pi), which follows the basecamp-connect
70+
skill and hands the work to a worker, a session of its own on the coding
71+
agent --worker names (the orchestrator's by default), in the repo the request
72+
belongs to. --orchestrator-model, --orchestrator-effort, --worker-model and
73+
--worker-effort choose models and reasoning effort; without them each coding
74+
agent uses its own defaults.
75+
76+
basecamp connect -P <profile> --orchestrator claude --worker codex
77+
basecamp connect -P <profile> --run
78+
79+
What a start names is kept for the profile, so the next one is --run. Plain
80+
basecamp connect, with none of these, still only prints requests.
81+
82+
Agents run unattended, as you. --permissions says what they may do:
83+
84+
full Any command and any file, without asking first, since nobody is
85+
at the keyboard to approve each step. The default.
86+
guarded Each coding agent under its own guardrails. Claude Code runs in
87+
its auto mode: it judges each action and stops the ones it finds
88+
unsafe. Codex runs each command in its sandbox, where it writes
89+
only in the folder it works in and the temporary directory, and
90+
decides itself whether a command the sandbox stopped may run
91+
outside it. Nobody is asked either way. Pi has no guardrails, and
92+
is refused.
93+
94+
An agent that is stopped says so in its reply. Who may give the agent work
95+
is setup's, and by default it is only its operator: basecamp connect show.
96+
97+
A runner.json beside the profile's connect.json chooses workers by where a
98+
request came from and which repo its work goes in. The first rule that
99+
matches wins, and what its worker leaves out comes from how the connector was
100+
started:
101+
102+
{"worker": {"adapter": "codex", "effort": "medium"},
103+
"rules": [
104+
{"repo": "~/code/app", "worker": {"adapter": "claude", "model": "opus"}},
105+
{"card_table": 123, "worker": {"effort": "high"}},
106+
{"project": 456, "worker": {"adapter": "pi"}},
107+
{"ping": true, "worker": {"adapter": "claude", "model": "haiku"}}]}
108+
109+
The rules and the permissions are read again for each request, so an edit to
110+
them needs no restart. The worker at the top is what the connector starts
111+
with.
112+
113+
basecamp connect say "<message>" talk to the orchestrator
114+
basecamp connect workers list the workers and what each runs on
115+
basecamp connect stop stop it; restart starts it again
116+
67117
One connector runs per profile in this state directory. An agent can run
68118
several connections where Basecamp enables adding them for its kind; otherwise
69119
a new approval replaces the existing connection. Each profile
@@ -100,12 +150,19 @@ status and doctor say which this profile's does.
100150
"stdout_wire": "connect",
101151
},
102152
RunE: func(cmd *cobra.Command, _ []string) error {
103-
return runConnect(cmd, &run)
153+
err := runConnect(cmd, &run)
154+
if errors.Is(err, errConnectRestart) {
155+
// Everything the run held is released: the same command
156+
// takes this process over and starts from the beginning.
157+
return connectReexec()
158+
}
159+
return err
104160
},
105161
}
106162
addConnectRunFlags(cmd, &run)
107163
cmd.AddCommand(newConnectSetupCmd(), newConnectShowCmd(), newConnectStatusCmd(), newConnectDoctorCmd(),
108-
newConnectDiscardCmd(), newConnectAskCmd(), newConnectReleaseCmd(), newConnectShadowCmd(), newConnectImportCmd())
164+
newConnectDiscardCmd(), newConnectAskCmd(), newConnectReleaseCmd(), newConnectShadowCmd(), newConnectImportCmd(),
165+
newConnectDispatchCmd(), newConnectWorkersCmd(), newConnectSayCmd(), newConnectStopCmd(), newConnectRestartCmd())
109166
return cmd
110167
}
111168

‎internal/commands/connect_process_other.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
package commands
44

5+
import "errors"
6+
57
// Process presence, as much as a reader can say without taking a lock.
68
const (
79
pidPresent = "present"
@@ -12,3 +14,7 @@ const (
1214
// processPresence cannot be answered here — the connector runs on macOS and
1315
// Linux — so it says so rather than calling a pid absent.
1416
func processPresence(int) string { return pidUnknown }
17+
18+
// connectReexec cannot start the connector again here: it runs on macOS and
19+
// Linux.
20+
func connectReexec() error { return errors.New("the connector cannot restart itself on this platform") }

‎internal/commands/connect_process_unix.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package commands
44

55
import (
66
"errors"
7+
"os"
78
"syscall"
89
)
910

@@ -30,3 +31,14 @@ func processPresence(pid int) string {
3031
return pidUnknown
3132
}
3233
}
34+
35+
// connectReexec starts the connector again in this process, with the
36+
// arguments and environment it was started with. It returns only when it
37+
// could not.
38+
func connectReexec() error {
39+
executable, err := os.Executable()
40+
if err != nil {
41+
return err
42+
}
43+
return syscall.Exec(executable, os.Args, os.Environ()) //nolint:gosec // G204: this binary, with its own arguments
44+
}

‎internal/commands/connect_run.go‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"errors"
66
"fmt"
7+
"io"
78
"log/slog"
89
"net/http"
910
"os"
@@ -13,6 +14,7 @@ import (
1314
"strconv"
1415
"strings"
1516
"sync"
17+
"sync/atomic"
1618
"time"
1719

1820
"github.com/spf13/cobra"
@@ -26,6 +28,7 @@ import (
2628
"github.com/basecamp/basecamp-cli/internal/connector"
2729
"github.com/basecamp/basecamp-cli/internal/connector/admission"
2830
"github.com/basecamp/basecamp-cli/internal/connector/ndjson"
31+
"github.com/basecamp/basecamp-cli/internal/connector/runner"
2932
"github.com/basecamp/basecamp-cli/internal/connector/setup"
3033
"github.com/basecamp/basecamp-cli/internal/output"
3134
"github.com/basecamp/basecamp-cli/internal/richtext"
@@ -43,6 +46,8 @@ type connectRunFlags struct {
4346
// --pings=false is a choice, not the flag's absence.
4447
pingsSet bool
4548
noPingsSet bool
49+
// runner turns on the runner: the connector does the work itself.
50+
runner connectRunnerFlags
4651
}
4752

4853
func addConnectRunFlags(cmd *cobra.Command, f *connectRunFlags) {
@@ -55,6 +60,7 @@ func addConnectRunFlags(cmd *cobra.Command, f *connectRunFlags) {
5560
fl.BoolVar(&f.shadow, "shadow", false, "Admit and log in an isolated state directory; dispatch and post nothing")
5661
fl.Int64Var(&f.since, "since", 0, "Enter the feed just after this event id, whatever the ledger holds")
5762
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")
63+
addConnectRunnerFlags(cmd, &f.runner)
5864
}
5965

6066
func connectStateHome() (string, error) {
@@ -216,6 +222,18 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
216222
case err != nil:
217223
return output.ErrUsage("connect.json cannot be used: " + err.Error())
218224
}
225+
// Which coding agents do the work, when the run does it itself: settled
226+
// before anything is read from Basecamp, so a mistyped agent or one that
227+
// is not installed ends the start rather than the first request.
228+
var start connectRunnerStart
229+
if f.runner.requested() {
230+
if f.shadow {
231+
return output.ErrUsage("A shadow run hands nothing off, so it has no orchestrator: drop --shadow, or the orchestrator and worker flags")
232+
}
233+
if start, err = connectRunnerSettle(f.runner, connectRunnerConfigPath(path)); err != nil {
234+
return err
235+
}
236+
}
219237

220238
account, err := connectAccount(app, name)
221239
if err != nil {
@@ -317,6 +335,13 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
317335
return err
318336
}
319337
defer func() { _ = lock.Release() }()
338+
if f.runner.requested() {
339+
// Under the lock, the identity verified: what this start named is
340+
// kept for the profile only now that the start is going ahead.
341+
if err := start.keep(connectRunnerConfigPath(path)); err != nil {
342+
return err
343+
}
344+
}
320345
pings, savePings, err := connectRunPings(lock, name, file, f.shadow, pingsFlag, len(buckets) > 0, creds)
321346
if err != nil {
322347
return err
@@ -365,6 +390,20 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
365390
"since", hold.HeldAt, "by", richtext.SanitizeSingleLine(hold.HeldBy))
366391
}
367392
lines := ndjson.NewWriter(cmd.OutOrStdout())
393+
var connectorLog *os.File
394+
if f.runner.requested() {
395+
// The orchestrator searches the connector's output the way the skill
396+
// searches the output file of a connector it started, so the lines
397+
// are kept as well as printed.
398+
if _, err := ensurePrivateChain(stateDir, filepath.Base(connectRunnerDir(stateDir))); err != nil {
399+
return output.ErrUsage("The connector's state directory cannot be used: " + err.Error())
400+
}
401+
if connectorLog, err = openConnectorLog(connectRunnerDir(stateDir)); err != nil {
402+
return err
403+
}
404+
defer func() { _ = connectorLog.Close() }()
405+
lines = ndjson.NewWriter(io.MultiWriter(cmd.OutOrStdout(), connectorLog))
406+
}
368407

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

471+
// The runner, when the run does the work itself. Its stop is the one the
472+
// orchestrator or the person asks for with `basecamp connect stop`.
473+
var (
474+
work *runner.Runner
475+
restart atomic.Bool
476+
deliver func(context.Context, connector.HandoffLine) error
477+
)
478+
if f.runner.requested() {
479+
startLine := fmt.Sprintf("It runs as profile %s; pings=%t (%s).", name, heard.Hears, heard.Describe())
480+
work, err = newConnectRunner(name, stateDir, path, start.orchestrator, start.worker, connectorLog, startLine, reads.Summaries, connectOnHoldAbove(accountClient, logger), ledger.Held,
481+
func(again bool) {
482+
restart.Store(again)
483+
logger.Info("connector: stopping, asked through its runner", "restart", again)
484+
cancel()
485+
}, logger)
486+
if err != nil {
487+
return output.ErrUsage("The runner cannot start: " + err.Error())
488+
}
489+
deliver = work.Deliver
490+
}
491+
432492
stopState, stopDetail := connector.ConnectionStopped, ""
433493
defer func() {
434494
// Whatever ended the run, status says it is not running any more.
@@ -483,9 +543,13 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
483543
Ledger: ledger, Served: served.Current, Buckets: buckets, Pings: policy.HearsPings, AgentID: agentID,
484544
Lines: lines, Logger: logger, Started: started,
485545
AckContent: file.Ack().Content, Booster: connector.SDKBooster{Client: accountClient},
546+
Deliver: deliver,
486547
})
487548
})
488549
}
550+
if work != nil {
551+
runPart("runner", work.Run)
552+
}
489553
wg.Wait()
490554

491555
mu.Lock()
@@ -504,6 +568,8 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
504568
return err
505569
case ctx.Err() != nil:
506570
return ctx.Err()
571+
case restart.Load():
572+
return errConnectRestart
507573
}
508574
return nil
509575
}

0 commit comments

Comments
 (0)