An open-source, faster Devin alternative
TypeScript
Watches + working repo: dashboard picker, SDK & CLI, docs (design 010) (#470)
Igor Zalutskia1b8a8163c89
diff --git a/cmd/oc/internal/commands/session_watch.go b/cmd/oc/internal/commands/session_watch.gonew file mode 100644index 00000000..ccb30575--- /dev/null+++ b/cmd/oc/internal/commands/session_watch.go@@ -0,0 +1,164 @@+package commands++// `oc session watch|watches|unwatch` — PR watches (design 010). A watch wakes the+// session when a PR it opened changes (checks finish, a review/comment lands, it+// merges/closes). Only PRs the same session opened, on OpenComputer-App repos.++import (+ "fmt"+ "strings"++ "github.com/spf13/cobra"+)++type Watch struct {+ ID string `json:"id"`+ Type string `json:"type"`+ Repo string `json:"repo"`+ PR int `json:"pr"`+ WakeOn string `json:"wake_on"`+ Intent string `json:"intent,omitempty"`+ Status string `json:"status"`+ Origin string `json:"origin"`+ LastSnapshotAt string `json:"last_snapshot_at,omitempty"`+ ExpiresAt string `json:"expires_at,omitempty"`+ CreatedAt string `json:"created_at"`+}++type WatchEnvelope struct {+ Watch Watch `json:"watch"`+}++type WatchList struct {+ Data []Watch `json:"data"`+}++var wakeOns = []string{"checks", "review", "comment", "merge"}++var sessionWatchCmd = &cobra.Command{+ Use: "watch <id>",+ Short: "Watch a PR the session opened (wake it on PR changes)",+ Long: "Declare a watch: OpenComputer wakes the session when the watched PR changes.\n\n" ++ "wake_on picks the condition — checks (CI finishes, default), review (a review\n" ++ "decision), comment (a new comment), or merge (the PR merges/closes). --repo/--pr\n" ++ "are optional; omitted, they resolve to the PR this session opened.",+ Example: " oc session watch ses_123 --wake-on review --intent \"address review feedback\"\n" ++ " oc session watch ses_123 # wake_on=checks (default)",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ wakeOn, _ := cmd.Flags().GetString("wake-on")+ if !contains(wakeOns, wakeOn) {+ return fmt.Errorf("--wake-on must be one of %s", strings.Join(wakeOns, ", "))+ }+ repo, _ := cmd.Flags().GetString("repo")+ pr, _ := cmd.Flags().GetInt("pr")+ intent, _ := cmd.Flags().GetString("intent")++ body := map[string]interface{}{"type": "github_pr", "wake_on": wakeOn}+ if repo != "" {+ body["repo"] = repo+ }+ if pr > 0 {+ body["pr"] = pr+ }+ if intent != "" {+ body["intent"] = intent+ }+ var env WatchEnvelope+ if err := sc.Post(cmd.Context(), "/v3/sessions/"+args[0]+"/watches", body, &env); err != nil {+ return err+ }+ printer.Print(env.Watch, func() {+ w := env.Watch+ fmt.Printf("Watching %s#%d — wake on %s (%s)\n", w.Repo, w.PR, w.WakeOn, w.Status)+ fmt.Printf("Watch id: %s\n", w.ID)+ if w.Status == "auth_required" {+ fmt.Println("Note: the OpenComputer GitHub App needs its watch permissions re-accepted; re-declare once fixed.")+ }+ })+ return nil+ },+}++var sessionWatchesCmd = &cobra.Command{+ Use: "watches <id>",+ Short: "List a session's watches",+ Args: cobra.ExactArgs(1),+ Aliases: []string{"watch-list"},+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ var resp WatchList+ if err := sc.Get(cmd.Context(), "/v3/sessions/"+args[0]+"/watches", &resp); err != nil {+ return err+ }+ printer.Print(resp.Data, func() {+ if len(resp.Data) == 0 {+ fmt.Println("No watches.")+ return+ }+ headers := []string{"ID", "REPO", "PR", "WAKE ON", "STATUS", "INTENT"}+ var rows [][]string+ for _, w := range resp.Data {+ rows = append(rows, []string{w.ID, w.Repo, fmt.Sprintf("%d", w.PR), w.WakeOn, w.Status, truncStr(w.Intent, 40)})+ }+ printer.Table(headers, rows)+ })+ return nil+ },+}++var sessionUnwatchCmd = &cobra.Command{+ Use: "unwatch <id> <watch-id>",+ Short: "Remove a watch",+ Example: " oc session unwatch ses_123 wch_abc",+ Args: cobra.ExactArgs(2),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ if err := sc.Delete(cmd.Context(), "/v3/sessions/"+args[0]+"/watches/"+args[1]); err != nil {+ return err+ }+ fmt.Printf("Removed watch %s\n", args[1])+ return nil+ },+}++func contains(xs []string, x string) bool {+ for _, v := range xs {+ if v == x {+ return true+ }+ }+ return false+}++func truncStr(s string, n int) string {+ s = strings.ReplaceAll(s, "\n", " ")+ if len(s) <= n {+ return s+ }+ if n <= 1 {+ return s[:n]+ }+ return s[:n-1] + "…"+}++func init() {+ sessionWatchCmd.Flags().String("wake-on", "checks", "Wake condition: checks | review | comment | merge")+ sessionWatchCmd.Flags().String("repo", "", "owner/repo (default: the PR this session opened)")+ sessionWatchCmd.Flags().Int("pr", 0, "PR number (default: the session's sole owned PR)")+ sessionWatchCmd.Flags().String("intent", "", "Freeform note (\"why\"), replayed to the agent on wake")++ sessionCmd.AddCommand(sessionWatchCmd)+ sessionCmd.AddCommand(sessionWatchesCmd)+ sessionCmd.AddCommand(sessionUnwatchCmd)+}diff --git a/docs/agent-sessions/api-reference.mdx b/docs/agent-sessions/api-reference.mdxindex b5b37fa3..4901c49f 100644--- a/docs/agent-sessions/api-reference.mdx+++ b/docs/agent-sessions/api-reference.mdx@@ -82,7 +82,7 @@ oc agent deploy # deploy the agent directory in the cwd- `key?` — get-or-create (one session per key). Keyless: an `Idempotency-Key` header makes create retry-safe.- `metadata?` — opaque routing state (≤ 16 KB); on get/list + **verbatim in webhooks**; never sent to the model, not indexed.- `limits?` `{ tokens, turn_seconds, turns }` — non-monetary; tripping one ends the turn (matching `yield_reason`).-- `sources?` — repos checked out before turn 1 (the token never enters the sandbox; see [GitHub](#github-apps-and-repos)). Each `{ repo, ref, sha, name? }` or inline `{ url, ref, sha, name?, auth }`; `ref` + `sha` required.+- `sources?` — repos checked out before turn 1 (the token never enters the sandbox; see [GitHub](#github-apps-and-repos)). Each registered `{ repo, ref, sha?, name? }` or inline `{ url, ref, sha, name?, auth }`. `ref` is required; `sha` is required for inline sources but **optional for a registered repo** — omit it and the control plane resolves `ref`→HEAD and pins that commit at create.- Client tokens: `scopes?` (`read`/`steer`), `ttl?` 60–86400 s (SDK `ttlSeconds`).A session pins the agent's active revision for its whole life — editing the agent later never affects a running one.@@ -123,8 +123,8 @@ A turn's **`yield_reason`** tells you why it stopped:| Variant | Shape ||---|---|-| registered | `{ repo, ref, sha, name? }` — `repo` is a `repo_…` id or `"owner/repo"`; App-backed auth |-| inline | `{ url, ref, sha, name?, auth }` — `auth = { type:"risky_short_lived_token", token, expires_at }` (can't refresh) |+| registered | `{ repo, ref, sha?, name? }` — `repo` is a `repo_…` id or `"owner/repo"`; App-backed auth. `sha` is **optional** (omit → control plane resolves `ref`→HEAD and pins it at create) |+| inline | `{ url, ref, sha, name?, auth }` — `sha` **required**; `auth = { type:"risky_short_lived_token", token, expires_at }` (can't refresh) |**`SourceSummary`** (sanitized; on create + `GET …/sources`)@@ -217,6 +217,32 @@ Filter by `type` (exact or `prefix.*`), `turn_id`, `limit`. `after` resumes fromBody: `{ text, idempotency_key? }` or `{ envelope }`. Returns `202` (or `200` on idempotent replay) with `{ event: { id, seq }, session: { id, status, head } }`.+## Watches++*Managed with the SDK (`session.watches.create/list/delete`), the CLI (`oc session watch/watches/unwatch`), or REST — authenticate with your **org API key** (server-side). The agent-facing path is the [`watch_pull_request`](/agent-sessions/runtime-tools#github-tools) runtime tool. Full guide: [Watches](/agent-sessions/watches).*++| Method · Path | Purpose |+| --- | --- |+| `POST /sessions/:id/watches` | Declare a watch → `201 { watch }`. Body: `{ type:"github_pr", repo?, pr?, wake_on, intent? }`. |+| `GET /sessions/:id/watches` | List watches → `{ data: [watch] }`. |+| `DELETE /sessions/:id/watches/:watchId` | Remove a watch → `{ ok: true }`. |++`wake_on` is the wake condition (`checks` default · `review` · `comment` · `merge`); `intent` is the freeform "why," replayed on wake. `repo`/`pr` are optional — omitted, they resolve to the PR this session opened. A watch fires only on PRs the **same session** opened, on Connected-App (`oc_app`) repos. Limits: **10** active watches per session, **30-day** TTL (and never outlives the PR).++**`Watch`**++| Field | Notes |+|---|---|+| `id` `type` | `wch_…`; `type` = `github_pr` |+| `repo` `pr` | watched repo · PR number |+| `wake_on` | wake condition: `checks` (default) · `review` (a review decision) · `comment` · `merge` (merged/closed) |+| `intent?` | freeform note ("why"), replayed on wake |+| `status` | `active · closed · revoked · auth_required` |+| `origin` | how it was declared (runtime tool / management API) |+| `last_snapshot_at?` `expires_at` `created_at` | last authoritative PR re-read · 30-day TTL lapse · timestamp |++**Delivered events** — appended into the session log at level `user` with `source: "github"`, carrying a normalized summary (not the raw webhook): `github.pr.checks_completed` · `github.pr.review_submitted` · `github.pr.comment` · `github.pr.merged` · `github.pr.closed`.+## Agents<Tabs>diff --git a/docs/agent-sessions/events.mdx b/docs/agent-sessions/events.mdxindex 493fe78a..a01ad3df 100644--- a/docs/agent-sessions/events.mdx+++ b/docs/agent-sessions/events.mdx@@ -44,6 +44,18 @@ Treat **`type`** as the stable discriminator. Unknown types should render from t| `exec.completed` | `{ command, exit_code, summary, content_ref?, bytes? }` | a finished command || `error.runtime` · `error.model` · `error.task` | `{ code, message, retriable? }` | a failure |+### GitHub PR events++When a session [watches](/agent-sessions/watches) a PR it opened, OpenComputer wakes it with a normalized event — level `user`, `source: "github"`, `body` a summary (author, text, url), never the raw webhook.++| `type` | Fires on |+| --- | --- |+| `github.pr.checks_completed` | GitHub check runs/suites for the head commit finished (coalesced) |+| `github.pr.review_submitted` | a review decision landed (approved / changes requested) |+| `github.pr.comment` | a comment landed on the PR — issue-style or review (diff) comment |+| `github.pr.merged` | the PR merged |+| `github.pr.closed` | the PR closed without merging |+## Visibility levelsEvery event carries a `level`; use it to choose how much detail each client receives.diff --git a/docs/agent-sessions/quickstart.mdx b/docs/agent-sessions/quickstart.mdxindex 569cc878..f94551c8 100644--- a/docs/agent-sessions/quickstart.mdx+++ b/docs/agent-sessions/quickstart.mdx@@ -108,6 +108,34 @@ Response:}```+<Tip>**Working on a repo?** Pass [`sources`](/agent-sessions/repos) to check code out before turn 1 — the GitHub token never enters the sandbox. For a registered repo, `sha` is optional (OpenComputer resolves `ref`→HEAD and pins it):</Tip>++<CodeGroup>++```ts TypeScript SDK+const session = await oc.sessions.create({+ agent: agent.id,+ input: "Fix the failing test on this branch, then open a PR.",+ sources: [{ repo: "acme/web", ref: "main" }],+});+```++```http REST API+POST https://api.opencomputer.dev/v3/sessions+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{+ "agent": "agt_...",+ "input": "Fix the failing test on this branch, then open a PR.",+ "sources": [{ "repo": "acme/web", "ref": "main" }]+}+```++</CodeGroup>++The agent can then open a PR with `github_publish_pull_request` and [watch](/agent-sessions/watches) it — it wakes when checks finish or a reviewer comments.+## 3. Stream eventsUse the `client_token` in the browser. Ask for `progress` for a good activity feed, or `internal` for an operator/debug view.diff --git a/docs/agent-sessions/repos.mdx b/docs/agent-sessions/repos.mdxindex 4a173a53..5226c51c 100644--- a/docs/agent-sessions/repos.mdx+++ b/docs/agent-sessions/repos.mdx@@ -131,6 +131,8 @@ for checkout, write only to publish) — the agent never holds one.Use your own GitHub App so PRs, comments, and statuses come from **your** identity. OpenComputerstores the key encrypted and signs the same per-operation tokens with it.+<Note>[Watches](/agent-sessions/watches) currently require PRs opened through the **OpenComputer** App — a PR published with a bring-your-own App isn't watchable yet.</Note>+**Create one** — `createManifestUrl` returns a link; open it and GitHub walks you throughcreating the App, then OpenComputer captures the key and registers it. (Creating an App is aGitHub-UI flow, so it's a link to open, not a pure API call.)@@ -285,7 +287,9 @@ Authorization: Bearer $OPENCOMPUTER_API_KEY- **`ref`** (required) — the fetch ref (a branch or `refs/pull/N/head`); a private SHAcan't be fetched directly.-- **`sha`** (required) — the exact commit, pinned and verified after fetch.+- **`sha`** — the exact commit, pinned and verified after fetch. **Optional for a+ registered repo** (omit it and the control plane resolves `ref`→HEAD and pins that commit+ at create); **required for inline sources**.You can also reference `"owner/repo"` directly instead of a registered id. A session canlist several immutable sources, such as a PR's base and head.@@ -315,12 +319,6 @@ After checkout, the agent works with ordinary files. It can inspect, edit, test,make local commits. Anything needing GitHub credentials runs outside the agent sandbox, sothe agent never runs authenticated `git`/`gh` and never sees a token.-<Warning>-Opening PRs from the agent (`github_publish_pull_request`) is **temporarily unavailable**-while the runtime is being updated — checkout (read) works today; the agent-driven PR-open-described below will be re-enabled in an upcoming runtime release.-</Warning>-To open a pull request, the agent calls the[`github_publish_pull_request`](/agent-sessions/runtime-tools#github-tools) runtime tool —it is **not** an SDK method; the agent invokes it from inside the sandbox. It takes the@@ -330,6 +328,16 @@ agent's edits to an `oc/<session>/<source>-<id>` branch and opens the PR with ajust-in-time, write-scoped token. This requires a **configured GitHub App** — the inline`risky_short_lived_token` path is checkout-only and **cannot** open PRs.+**More repos mid-session.**+[`add_source(repo, ref, name?)`](/agent-sessions/runtime-tools#github-tools) checks out an+additional Connected-App repo into `/workspace/sources/<name>` after the first turn — same+zero-credential model as the initial checkout.++**React to PR events.** After opening a PR, the agent can+[watch](/agent-sessions/watches) it with `watch_pull_request`; OpenComputer wakes the session+when checks finish, a review or comment lands, or it merges, so the agent can respond (e.g.+push a fix). Own-PR only, Connected-App repos only.+## Guarantees- **GitHub App-backed tokens are never stored** — OpenComputer obtains short-lived,diff --git a/docs/agent-sessions/runtime-tools.mdx b/docs/agent-sessions/runtime-tools.mdxindex 46be961b..7f06eee0 100644--- a/docs/agent-sessions/runtime-tools.mdx+++ b/docs/agent-sessions/runtime-tools.mdx@@ -32,15 +32,12 @@ The agent's final `say` is the session result. `ask` ends the turn with `yield_r## GitHub tools-<Warning>-`github_publish_pull_request` is **temporarily unavailable** — the current agent runtime-does not expose it yet, while the runtime is being updated. The description below is the-intended behavior; the tool will be re-enabled in an upcoming runtime release.-</Warning>-| Tool | What it does || --- | --- || `github_publish_pull_request` | Open a pull request from a checked-out [Repo](/agent-sessions/repos) source. |+| `add_source` | Check out an additional repo into `/workspace/sources/<name>` mid-session. |+| `watch_pull_request` | Subscribe to events on a PR the session opened — the session is woken when checks finish, a review or comment lands, or it merges. |+| `unwatch_pull_request` | Stop watching a PR. |`github_publish_pull_request` lets the agent open a PR **without ever holding a GitHubcredential**. The agent edits files in `/workspace/sources/<source>` and makes local@@ -58,11 +55,32 @@ just-in-time, write-scoped token — outside the agent sandbox. It returns the P<Note>`github_publish_pull_request` requires a **configured GitHub App** (the OpenComputer App or-a [bring-your-own App](/agent-sessions/repos#github-app-modes)). It does **not** work with+a [bring-your-own App](/agent-sessions/repos#bring-your-own-app)). It does **not** work withinline (`risky_short_lived_token`) auth, which is **checkout-only** — see[Repos & GitHub](/agent-sessions/repos#inline-short-lived-token).</Note>+`add_source(repo, ref, name?)` checks out an **additional** repo into+`/workspace/sources/<name>` mid-session. `repo` is `"owner/repo"` (or a `repo_…` id), `ref` a+branch or `refs/pull/N/head`, `name` defaults to the repo name. Same zero-credential model as+the initial checkout — a Git operations sandbox mints a just-in-time, read-only token; the+agent never sees it. **Connected-App (`oc_app`) repos only.**++`watch_pull_request(wake_on?, repo?, pr?, intent?)` subscribes the session to a PR it opened;+OpenComputer wakes the session when the wake condition is met. It does **not** block — call it,+then finish the turn.++| Argument | Required | What it is |+| --- | --- | --- |+| `wake_on` | no | The wake condition: `checks` (default), `review` (a review decision), `comment` (a new comment), `merge` (merged/closed). |+| `repo` | no | The watched repo. Defaults to the most recent PR the session opened. |+| `pr` | no | The PR number. Defaults with `repo`. |+| `intent` | no | Freeform note (the *why*), replayed on wake. |++Watches cover PRs the **same session** opened, on **Connected-App (`oc_app`) repos only**.+`unwatch_pull_request(repo?, pr?)` stops watching; both args default to the session's only+active watch. Full flow, statuses, and delivered events: [Watches](/agent-sessions/watches).+## External systemsThese tools never hand the agent raw credentials for GitHub, Slack, Jira, or other externaldiff --git a/docs/agent-sessions/sessions.mdx b/docs/agent-sessions/sessions.mdxindex fbbb2280..587e1337 100644--- a/docs/agent-sessions/sessions.mdx+++ b/docs/agent-sessions/sessions.mdx@@ -10,7 +10,7 @@ A **session** is an [agent](/agent-sessions/agents) run with an append-only [eve## Session flow-1. You create a session from an [agent](/agent-sessions/agents). It **pins the agent's active [revision](/agent-sessions/revisions)** (prompt / model / skills) for its whole life — editing the agent later never affects a running session. Pass `revision` to pin a specific one instead (e.g. to test a [staged](/agent-sessions/revisions#staging-vs-activating) revision before promoting). The model runs **Managed** (billed to your credits, no key — the default) or on a [model credential](/agent-sessions/credentials) you supply. The session starts immediately.+1. You create a session from an [agent](/agent-sessions/agents). It **pins the agent's active [revision](/agent-sessions/revisions)** (prompt / model / skills) for its whole life — editing the agent later never affects a running session. Pass `revision` to pin a specific one instead (e.g. to test a [staged](/agent-sessions/revisions#staging-vs-activating) revision before promoting). The model runs **Managed** (billed to your credits, no key — the default) or on a [model credential](/agent-sessions/credentials) you supply. Pass [`sources`](/agent-sessions/repos) to check repos out into `/workspace/sources/` before turn 1 — the GitHub token never enters the sandbox. The session starts immediately.2. The [runtime](/agent-sessions/runtimes) executes the agent in a sandbox, appending [events](/agent-sessions/events) to the log as it works.3. With nothing left to do, the session goes **idle** and the sandbox **hibernates**.4. A [steer](/agent-sessions/messaging) message wakes it; it resumes with its prior context. Repeat.diff --git a/docs/agent-sessions/watches.mdx b/docs/agent-sessions/watches.mdxnew file mode 100644index 00000000..77a6526e--- /dev/null+++ b/docs/agent-sessions/watches.mdx@@ -0,0 +1,188 @@+---+mode: "wide"+title: "Watches"+description: "Wake a session when a PR it opened gets checks, reviews, comments, or merges"+---++A **watch** wakes a session when a PR it opened changes. The agent opens a PR, declares a watch, and ends the turn; when checks finish, a review or comment lands, or the PR merges, OpenComputer appends a normalized event and wakes the session to react. This is the open-a-PR-then-respond-to-CI loop without polling GitHub.++<Note>**Preview** — APIs may change before general availability.</Note>++Declare a watch from inside the sandbox with the [`watch_pull_request`](/agent-sessions/runtime-tools#github-tools) runtime tool, or from your backend with the REST endpoints [below](#management-api).++## How it works++Declaring a watch doesn't change session state — the session goes **idle** after the turn like any other. On a PR transition, OpenComputer appends an event and wakes the session, the same path as a [steer](/agent-sessions/messaging).++- **Authoritative re-read.** A webhook is a hint. Before waking, OpenComputer re-reads PR state from GitHub and wakes with that snapshot, so late, duplicate, or out-of-order webhooks converge.+- **Coalesced.** One wake per transition — a burst of check events for a commit is a single `checks_completed` wake.+- **Loop-suppressed.** The session's own comments and pushes don't wake it; only third-party changes do.+- **Delivered as `user` events.** The event is appended at level `user` (`source: "github"`) and the session resumes with prior context.++<Warning>+A watch lets the agent react; it doesn't grant a GitHub write path. There is no comment-write tool — the agent reads the event and responds by [pushing a fix](/agent-sessions/repos#what-the-agent-can-do) to the branch or opening a follow-up PR. It cannot post a reply comment to GitHub.+</Warning>++## What you can watch++A session can only watch a PR it opened itself via [`github_publish_pull_request`](/agent-sessions/runtime-tools#github-tools). The PR must have been opened through the **OpenComputer GitHub App** (`oc_app` sources) — that App's webhook and read token are what drive the watch. Inline `risky_short_lived_token` sources aren't watchable (the token is checkout-only and purged).++<Note>+**Owner-side prerequisite.** The OpenComputer GitHub App needs **Pull requests: Read**, **Checks: Read**, and **Issues: Read**, plus event subscriptions to **`pull_request`**, **`pull_request_review`**, **`pull_request_review_comment`**, **`check_suite`**, **`check_run`**, and **`issue_comment`**. Existing installs must **re-accept the new permissions**. Until they do, a watch is created but declares as `auth_required` and won't deliver events.+</Note>++## Wake conditions++`wake_on` is the **wake condition** — the PR state change that wakes the session. It's *what* the watch waits for; the *why* is [`intent`](#intent-why), replayed on wake.++| `wake_on` | Wakes when |+| --- | --- |+| `checks` | GitHub **check runs/suites** for the head commit finish (**default**). Legacy commit *statuses* aren't watched. |+| `review` | A review **decision** lands — approved or changes-requested (not plain comments). |+| `comment` | A new comment on the PR (review comment or issue comment). |+| `merge` | The PR reaches a terminal state — merged, or closed without merging. |++`events` is **derived** from `wake_on`; it is not part of the create request.++### intent (why)++`intent` is a freeform note — *why* the agent is watching (e.g. "Fix CI if it fails"). It doesn't affect *when* the session wakes; it's replayed back to the agent on wake so it knows what to do.++## Runtime tools++The agent declares and clears watches from inside the sandbox. Full signatures: [Runtime tools](/agent-sessions/runtime-tools#github-tools).++| Tool | What it does |+| --- | --- |+| `watch_pull_request(wake_on?, repo?, pr?, intent?)` | Subscribe to a PR the session opened. Does **not** block — call it, then finish the turn. Defaults to the most recent PR the session opened; `wake_on` defaults to `checks`. `intent` is a freeform note replayed on wake. |+| `unwatch_pull_request(repo?, pr?)` | Stop watching. Defaults to the only active watch. |++## Management API++Manage watches from your backend with the SDK, the `oc` CLI, or REST — authenticated with your **org API key** (server-side). `repo`/`pr` are optional; omitted, they resolve to the PR this session opened.++**Create a watch:**++<CodeGroup>++```ts TypeScript SDK+const session = await oc.sessions.get("ses_...");+const watch = await session.watches.create({+ repo: "acme/web", // optional — defaults to the PR this session opened+ pr: 42, // optional+ wakeOn: "review", // checks (default) · review · comment · merge+ intent: "Address review feedback on the auth refactor.",+});+// → { id: "wch_...", status: "active", ... }+```++```bash oc CLI+oc session watch ses_... \+ --repo acme/web --pr 42 \+ --wake-on review \+ --intent "Address review feedback on the auth refactor."+```++```http REST+POST https://api.opencomputer.dev/v3/sessions/ses_.../watches+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{ "type": "github_pr", "repo": "acme/web", "pr": 42,+ "wake_on": "review", "intent": "Address review feedback on the auth refactor." }+// → 201 { "watch": { … } }+```++</CodeGroup>++**List watches:**++<CodeGroup>++```ts TypeScript SDK+const watches = await session.watches.list();+```++```bash oc CLI+oc session watches ses_...+```++```http REST+GET https://api.opencomputer.dev/v3/sessions/ses_.../watches+Authorization: Bearer $OPENCOMPUTER_API_KEY+// → { "data": [ { … } ] }+```++</CodeGroup>++**Delete a watch:**++<CodeGroup>++```ts TypeScript SDK+await session.watches.delete("wch_...");+```++```bash oc CLI+oc session unwatch ses_... wch_...+```++```http REST+DELETE https://api.opencomputer.dev/v3/sessions/ses_.../watches/wch_...+Authorization: Bearer $OPENCOMPUTER_API_KEY+// → { "ok": true }+```++</CodeGroup>++## The watch object++| Field | Notes |+| --- | --- |+| `id` | `wch_…` |+| `type` | `github_pr` |+| `repo` `pr` | the watched repo and PR number |+| `wake_on` | the wake condition (table above) |+| `intent?` | freeform note, replayed on wake |+| `status` | lifecycle status (below) |+| `origin` | how it was declared (runtime tool or management API) |+| `last_snapshot_at?` | last authoritative PR re-read |+| `expires_at` | when the 30-day TTL lapses; past this the watch stops firing (status stays `active`) |+| `created_at` | timestamp |++### Statuses++| Status | Meaning |+| --- | --- |+| `active` | Watching; delivering events. |+| `closed` | The PR merged or closed, so the watch ended with it. |+| `revoked` | Removed via `unwatch_pull_request` or `DELETE`. |+| `auth_required` | The App lacks the required permissions or event subscriptions — [re-accept them](#what-you-can-watch). Re-declare the watch once fixed. |++A watch that hits its 30-day TTL simply stops firing (its `expires_at` passes) — re-declare to renew it.++### Delivered events++One event per transition, appended at level `user` with `source: "github"`. The `body` is a normalized summary (a comment event carries author, text, and URL), never the raw webhook.++| `type` | Fires on |+| --- | --- |+| `github.pr.checks_completed` | Check suites for the head commit finished (coalesced). |+| `github.pr.review_submitted` | A review decision was submitted (approved / changes requested). |+| `github.pr.comment` | A comment landed on the PR — issue-style **or** review (diff) comment. |+| `github.pr.merged` | The PR merged. |+| `github.pr.closed` | The PR closed without merging. |++These join the standard session [event types](/agent-sessions/events#event-types) — switch on `type`, don't parse prose.++## Limits++- Max **10** active watches per session.+- **30-day** TTL, and never outlives the PR — the watch ends when the PR closes or merges.++## Example++1. Agent calls `github_publish_pull_request("web", "Refactor auth")` → PR opened on branch `oc/<session>/web-<id>`.+2. Agent calls `watch_pull_request(wake_on: "review", intent: "Address review feedback")`, `say`s, ends the turn. Session goes idle.+3. Reviewer comments. OpenComputer re-reads the PR, appends `github.pr.comment` (author, text, URL) at level `user`, and wakes the session.+4. Agent edits the source and calls `github_publish_pull_request` again to push onto the same branch. Its own push is loop-suppressed. The watch runs until the PR merges or the TTL expires.diff --git a/docs/docs.json b/docs/docs.jsonindex 4980df39..c1991a89 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -85,6 +85,7 @@"agent-sessions/slack","agent-sessions/runtimes","agent-sessions/runtime-tools",+ "agent-sessions/watches","agent-sessions/api-reference",{"group": "Labs",diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex 02ddd8a0..3ec3388b 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "0.10.0",+ "version": "0.11.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "0.10.0",+ "version": "0.11.0","license": "MIT","devDependencies": {"@types/node": "^25.3.0",diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex 89739e1a..cde3931a 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.10.0",+ "version": "0.11.0","description": "TypeScript SDK for OpenComputer - cloud sandbox platform","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.tsindex e56f59f3..403b42ca 100644--- a/sdks/typescript/src/agents/index.ts+++ b/sdks/typescript/src/agents/index.ts@@ -30,6 +30,8 @@ export { Credentials } from "./credentials.js";export type { CreateCredentialParams } from "./credentials.js";export { Destinations, Deliveries } from "./destinations.js";export type { CreateDestinationParams, UpdateDestinationParams } from "./destinations.js";+export { Watches } from "./watches.js";+export type { Watch, WatchStatus, WakeOn, CreateWatchParams } from "./watches.js";export { verifyWebhook, WebhookVerificationError } from "./webhooks.js";export type { WebhookDelivery, VerifyWebhookOptions } from "./webhooks.js";diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.tsindex 10ccd7f2..989b8a5b 100644--- a/sdks/typescript/src/agents/sessions.ts+++ b/sdks/typescript/src/agents/sessions.ts@@ -2,6 +2,7 @@ import type { Http, Query } from "./http.js";import type { Event, Level, Limits, LastTurn, SessionData, SessionStatus, Turn } from "./types.js";import { parseEventStream } from "./sse.js";import { Destinations, Deliveries } from "./destinations.js";+import { Watches } from "./watches.js";export type Envelope = { text?: string; [k: string]: unknown };@@ -54,10 +55,13 @@ export interface RegisteredRepoSource {repo: string;url?: never;auth?: never;- /** Required fetch ref (branch or `refs/pull/N/head`). */+ /** Fetch ref (branch or `refs/pull/N/head`). */ref: string;- /** Required exact commit; fetched, then pinned + verified. */- sha: string;+ /**+ * Exact commit to pin. OPTIONAL for a registered repo: omit it and the control plane resolves+ * `ref`→HEAD and pins that sha at create. Pass it to pin an exact commit yourself.+ */+ sha?: string;/** Checkout slug → `/workspace/sources/<name>`. Defaults to the repo name. */name?: string;}@@ -232,6 +236,8 @@ export class Session extends ClientSession {/** Webhook destinations + delivery records for this session (org key). */readonly destinations: Destinations;readonly deliveries: Deliveries;+ /** PR watches for this session — wake it when a PR it opened changes (org key). */+ readonly watches: Watches;private data: SessionData;private _sources: SourceSummary[];@@ -241,6 +247,7 @@ export class Session extends ClientSession {this._sources = sources ?? [];this.destinations = new Destinations(http, data.id);this.deliveries = new Deliveries(http, data.id);+ this.watches = new Watches(http, data.id);}get status(): SessionStatus { return this.data.status; }diff --git a/sdks/typescript/src/agents/watches.ts b/sdks/typescript/src/agents/watches.tsnew file mode 100644index 00000000..7704d3ea--- /dev/null+++ b/sdks/typescript/src/agents/watches.ts@@ -0,0 +1,73 @@+import type { Http } from "./http.js";++/** The wake condition — the PR state change that wakes the session. */+export type WakeOn = "checks" | "review" | "comment" | "merge";++/** Watch lifecycle status. */+export type WatchStatus = "active" | "closed" | "revoked" | "auth_required";++export interface CreateWatchParams {+ /** Only `"github_pr"` today (the default). */+ type?: "github_pr";+ /** `"owner/repo"` — omitted, resolves to the PR this session opened. */+ repo?: string;+ /** PR number — omitted, resolves to the session's sole owned PR. */+ pr?: number;+ /** Wake condition. Default `"checks"`. */+ wakeOn?: WakeOn;+ /** Freeform note ("why"), replayed to the agent on wake. */+ intent?: string;+}++export interface Watch {+ id: string;+ /** `"github_pr"`. */+ type: string;+ /** Watched repo (`"owner/repo"`). */+ repo: string;+ /** Watched PR number. */+ pr: number;+ wakeOn: WakeOn;+ /** Freeform note, replayed on wake. */+ intent?: string;+ status: WatchStatus;+ /** How it was declared (runtime tool / management API). */+ origin: string;+ /** Last authoritative PR re-read. */+ lastSnapshotAt?: string;+ /** When the 30-day TTL lapses; past this the watch stops firing (status stays `active`). */+ expiresAt: string;+ createdAt: string;+}++/**+ * Watches for one session — wake the session when a PR it opened changes (checks finish, a review+ * or comment lands, the PR merges/closes). Management surface; needs the org key.+ *+ * A watch only fires on a PR the **same session** opened via `github_publish_pull_request`, on+ * OpenComputer-App (`oc_app`) repos. See the [Watches guide](https://docs.opencomputer.dev/agent-sessions/watches).+ */+export class Watches {+ constructor(private readonly http: Http, private readonly sessionId: string) {}++ /** Declare a watch. `repo`/`pr` omitted → the PR this session opened. */+ async create(params: CreateWatchParams = {}): Promise<Watch> {+ const r = await this.http.request<{ watch: Watch }>(+ "POST", `/sessions/${this.sessionId}/watches`, { body: params },+ );+ return r.watch;+ }++ /** List this session's watches. */+ async list(): Promise<Watch[]> {+ const r = await this.http.request<{ data?: Watch[] } | Watch[]>(+ "GET", `/sessions/${this.sessionId}/watches`,+ );+ return Array.isArray(r) ? r : r.data ?? [];+ }++ /** Remove a watch (equivalent to the agent's `unwatch_pull_request`). */+ delete(id: string): Promise<void> {+ return this.http.request("DELETE", `/sessions/${this.sessionId}/watches/${id}`);+ }+}diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 82346842..433f15b6 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -610,10 +610,16 @@ export const getSessions = (export const getSession = (id: string) =>apiFetch(`/v3/sessions/${id}`, {}, S.SessionSchema)-// The API wants { agent: <id>, input } (input required). The response is an envelope+// The API wants { agent: <id>, input } (input required). An optional `sources[]` attaches+// a WORKING repo the agent checks out + opens PRs from — the control plane pins the ref's+// HEAD when `sha` is omitted (design 010 §24.0). The response is an envelope// { session, client_token } — return the session.export const createSession = (- body: { agent: string; input: string },+ body: {+ agent: string+ input: string+ sources?: { repo: string; ref: string; name?: string }[]+ },idempotencyKey?: string,) =>apiFetch(diff --git a/web/src/components/agent-deploy-source.tsx b/web/src/components/agent-deploy-source.tsxindex 742c0da5..8abf8ace 100644--- a/web/src/components/agent-deploy-source.tsx+++ b/web/src/components/agent-deploy-source.tsx@@ -17,8 +17,8 @@ import {import { Panel, PanelContent } from '@/components/panel'import { Button } from '@/components/ui/button'import { Input, Select } from '@/components/form'+import { GithubMark } from '@/components/github-mark'-// GitHub mark (lucide's brand `Github` icon is deprecated/unexported — inline the SVG).// A connect / redeploy kicks off a GitHub deploy that runs ASYNC — the new revision (prompt +// skills) isn't live until it activates. Poll the source until the deploy lands// (active_deployed_sha caught up to latest_seen_sha), keeping the card in step, then refresh the@@ -41,14 +41,6 @@ async function pollDeployUntilActive(agentId: string, queryClient: QueryClient)}}-function GithubMark({ className }: { className?: string }) {- return (- <svg viewBox="0 0 16 16" fill="currentColor" className={className} aria-hidden="true">- <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />- </svg>- )-}-/*** Source card (Overview right rail) — minimal. Connect a GitHub repo as the agent's source:* not installed → a single Connect (install) button; installed → an editable repo / directory /diff --git a/web/src/components/github-mark.tsx b/web/src/components/github-mark.tsxnew file mode 100644index 00000000..0b35e220--- /dev/null+++ b/web/src/components/github-mark.tsx@@ -0,0 +1,14 @@+// GitHub wordmark glyph. lucide's `Github` icon is deprecated/unexported, so we inline the+// official mark path. Inherits color via `currentColor`; size via className (e.g. `size-4`).+export function GithubMark({ className }: { className?: string }) {+ return (+ <svg+ viewBox="0 0 16 16"+ fill="currentColor"+ className={className}+ aria-hidden="true"+ >+ <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />+ </svg>+ )+}diff --git a/web/src/components/working-repo-field.tsx b/web/src/components/working-repo-field.tsxnew file mode 100644index 00000000..be0591e8--- /dev/null+++ b/web/src/components/working-repo-field.tsx@@ -0,0 +1,175 @@+import { useMemo } from 'react'+import { useQuery } from '@tanstack/react-query'+import { Select as SelectPrimitive } from 'radix-ui'+import { Check, ChevronDown, GitBranch, X } from 'lucide-react'+import { getDeployApp } from '@/api/client'+import { GithubMark } from '@/components/github-mark'+import { markFloatingLayerPointerDismiss } from '@/components/ui/floating-layer'+import { cn } from '@/lib/utils'++// The WORKING repo a session checks out and opens PRs from (design 010 §2). Deliberately SEPARATE+// from the agent's config/"connected" repo (prompt + skills) — an agent is typically configured+// from one repo and works across others, so this never defaults to the connected repo. Optional:+// a session starts fine with none; when set, the agent can publish (and later watch) PRs.++export interface WorkingRepo {+ repo: string // "owner/repo"+ ref: string // branch+}++function splitRepo(full: string): [owner: string, name: string] {+ const i = full.indexOf('/')+ return i === -1 ? ['', full] : [full.slice(0, i), full.slice(i + 1)]+}++/**+ * Inline, secondary working-repo control for the session composer. A compact, GitHub-marked+ * dropdown — unselected by default (short "Working repo" placeholder); starting a session works+ * empty. Selecting a repo reveals a branch pill (prefilled with the repo's default branch) and a+ * clear (✕). Repos come from what the OpenComputer App can reach (getDeployApp). Custom-styled+ * on the Radix primitive (no new dependency) so it reads as a deliberate control, not stock.+ */+export function WorkingRepoField({+ value,+ onChange,+}: {+ value: WorkingRepo | null+ onChange: (v: WorkingRepo | null) => void+}) {+ const {+ data: app,+ isLoading,+ isError,+ refetch,+ } = useQuery({+ queryKey: ['deploy-app'],+ queryFn: getDeployApp,+ staleTime: 30_000,+ })+ const repoOptions = useMemo(() => app?.repositories ?? [], [app])+ const installed = app?.installed !== false // treat "still loading" as installed+ const disabled = !installed || repoOptions.length === 0++ const pickRepo = (fullName: string) => {+ const r = repoOptions.find((x) => x.full_name === fullName)+ // Keep the current branch when re-picking the same repo; else the repo's default.+ const ref = value?.repo === fullName ? value.ref : r?.default_branch || 'main'+ onChange({ repo: fullName, ref })+ }++ // Load failed → an explicit retry, not a silent "No repos available" dead-end.+ if (isError) {+ return (+ <button+ type="button"+ onClick={() => void refetch()}+ className="border-border inline-flex h-8 items-center gap-2 rounded-md border border-dashed px-2.5 text-sm text-red-600 transition-colors hover:border-red-400 dark:text-red-500"+ title="Couldn't load your repos — click to retry"+ >+ <GithubMark className="size-3.5" />+ Couldn’t load repos — retry+ </button>+ )+ }++ // Not installed → a quiet connect affordance instead of a dead control.+ if (installed === false && app?.install_url) {+ return (+ <a+ href={app.install_url}+ target="_blank"+ rel="noreferrer"+ className="border-border text-muted-foreground hover:text-foreground hover:border-foreground/25 inline-flex h-8 items-center gap-2 rounded-md border border-dashed px-2.5 text-sm transition-colors"+ title="Connect the OpenComputer GitHub App to work in a repo"+ >+ <GithubMark className="size-3.5" />+ Connect GitHub+ </a>+ )+ }++ const [owner, name] = value ? splitRepo(value.repo) : ['', '']++ return (+ <div className="flex flex-wrap items-center gap-1.5">+ <SelectPrimitive.Root value={value?.repo ?? ''} onValueChange={pickRepo} disabled={disabled}>+ <SelectPrimitive.Trigger+ aria-label="Working repo"+ title="Optional — the repo the agent works in and opens PRs from"+ className={cn(+ 'border-border bg-panel-2 hover:border-foreground/25 focus-visible:border-foreground/40 data-[state=open]:border-foreground/35 group inline-flex h-8 max-w-64 min-w-40 items-center gap-2 rounded-md border px-2.5 text-sm outline-none transition-colors disabled:cursor-not-allowed disabled:opacity-60',+ )}+ >+ <GithubMark className="text-muted-foreground group-hover:text-foreground/70 size-3.5 shrink-0 transition-colors" />+ <span className="min-w-0 flex-1 truncate text-left">+ {value ? (+ <span className="font-medium">+ <span className="text-muted-foreground">{owner}/</span>+ {name}+ </span>+ ) : (+ <span className="text-muted-foreground">+ {disabled ? (isLoading ? 'Loading repos…' : 'No repos available') : 'Working repo'}+ </span>+ )}+ </span>+ <ChevronDown className="text-muted-foreground/50 size-3.5 shrink-0" />+ </SelectPrimitive.Trigger>+ <SelectPrimitive.Portal>+ <SelectPrimitive.Content+ position="popper"+ sideOffset={5}+ onPointerDownOutside={markFloatingLayerPointerDismiss}+ className="bg-popover text-popover-foreground ring-foreground/10 shadow-overlay data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 z-50 max-h-(--radix-select-content-available-height) min-w-(--radix-select-trigger-width) origin-(--radix-select-content-transform-origin) overflow-hidden rounded-lg p-1 ring-1 duration-100"+ >+ <SelectPrimitive.Viewport>+ {repoOptions.map((r) => {+ const [o, n] = splitRepo(r.full_name)+ return (+ <SelectPrimitive.Item+ key={r.full_name}+ value={r.full_name}+ className="focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none"+ >+ <GithubMark className="text-muted-foreground size-3.5 shrink-0" />+ <SelectPrimitive.ItemText>+ <span className="text-muted-foreground">{o}/</span>+ {n}+ </SelectPrimitive.ItemText>+ <span className="absolute right-2 flex items-center">+ <SelectPrimitive.ItemIndicator>+ <Check className="size-4" />+ </SelectPrimitive.ItemIndicator>+ </span>+ </SelectPrimitive.Item>+ )+ })}+ </SelectPrimitive.Viewport>+ </SelectPrimitive.Content>+ </SelectPrimitive.Portal>+ </SelectPrimitive.Root>++ {value ? (+ <span className="border-border bg-panel-2 focus-within:border-foreground/40 inline-flex h-8 items-center gap-1 rounded-md border pr-1 pl-2 transition-colors">+ <GitBranch className="text-muted-foreground size-3.5 shrink-0" />+ <input+ value={value.ref}+ onChange={(e) => onChange({ ...value, ref: e.target.value })}+ placeholder="main"+ aria-label="Branch"+ spellCheck={false}+ className="w-24 bg-transparent font-mono text-xs outline-none"+ />+ <button+ type="button"+ title="Clear working repo"+ className="text-muted-foreground hover:text-foreground hover:bg-accent rounded p-0.5"+ onClick={() => onChange(null)}+ >+ <X className="size-3.5" />+ </button>+ </span>+ ) : null}+ </div>+ )+}diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxindex 0dfb9992..6d86b59c 100644--- a/web/src/pages/AgentDetail.tsx+++ b/web/src/pages/AgentDetail.tsx@@ -31,6 +31,10 @@ import { SlackConnect } from '@/components/slack-connect'import { AgentSkills } from '@/components/agent-skills'import { AgentDeploySource } from '@/components/agent-deploy-source'import { AgentRevisions } from '@/components/agent-revisions'+import {+ WorkingRepoField,+ type WorkingRepo,+} from '@/components/working-repo-field'import { ApiHint, type ApiRef } from '@/components/api-hint'import { getRuntime } from '@/lib/runtimes'@@ -113,10 +117,19 @@ export default function AgentDetail() {// ── Start a session (used by the Sessions tab composer) ────────────────────const [task, setTask] = useState('')+ // Optional working repo — the repo the agent checks out + opens PRs from. Explicitly chosen,+ // never derived from the connected/config repo (design 010 §2).+ const [workingRepo, setWorkingRepo] = useState<WorkingRepo | null>(null)const startMutation = useMutation({mutationFn: () =>createSession(- { agent: agentId, input: task.trim() },+ {+ agent: agentId,+ input: task.trim(),+ ...(workingRepo+ ? { sources: [{ repo: workingRepo.repo, ref: workingRepo.ref }] }+ : {}),+ },crypto.randomUUID(),),onSuccess: (session) => {@@ -452,12 +465,17 @@ export default function AgentDetail() {placeholder="Give this agent a task — it runs durably as a new session…"className="min-h-20"/>- <div className="flex justify-end">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <WorkingRepoField+ value={workingRepo}+ onChange={setWorkingRepo}+ /><Buttontype="submit"size="sm"title="Enter to start · Shift+Enter for newline"disabled={startMutation.isPending || !task.trim()}+ className="ml-auto"><Send className="size-4" />{startMutation.isPending ? 'Starting…' : 'Start session'}diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsxindex c9c40b9e..1df668d5 100644--- a/web/src/pages/Sessions.tsx+++ b/web/src/pages/Sessions.tsx@@ -17,6 +17,10 @@ import {DialogTitle,} from '@/components/ui/dialog'import { Field, Label, Select } from '@/components/form'+import {+ WorkingRepoField,+ type WorkingRepo,+} from '@/components/working-repo-field'import { ChatTextarea } from '@/components/chat-textarea'import { StatusBadge } from '@/components/status-badge'import { EmptyState } from '@/components/empty-state'@@ -39,17 +43,26 @@ export default function Sessions() {const [showStart, setShowStart] = useState(false)const [agentId, setAgentId] = useState('')const [message, setMessage] = useState('')+ // Optional working repo — explicitly chosen, per-agent (cleared when the agent changes).+ const [workingRepo, setWorkingRepo] = useState<WorkingRepo | null>(null)const openStart = () => {setAgentId(agents?.[0]?.id ?? '')setMessage('')+ setWorkingRepo(null)setShowStart(true)}const startMutation = useMutation({mutationFn: () =>createSession(- { agent: agentId, input: message.trim() },+ {+ agent: agentId,+ input: message.trim(),+ ...(workingRepo+ ? { sources: [{ repo: workingRepo.repo, ref: workingRepo.ref }] }+ : {}),+ },crypto.randomUUID(),),onSuccess: (session) => {@@ -186,7 +199,10 @@ export default function Sessions() {<Selectid="start-agent"value={agentId}- onValueChange={setAgentId}+ onValueChange={(v) => {+ setAgentId(v)+ setWorkingRepo(null) // a working repo is per-agent+ }}options={(agents ?? []).map((a) => ({value: a.id,label: a.name,@@ -211,6 +227,12 @@ export default function Sessions() {className="min-h-24"/></Field>+ {agentId ? (+ <WorkingRepoField+ value={workingRepo}+ onChange={setWorkingRepo}+ />+ ) : null}<DialogFooter className="mt-2"><Buttontype="button"