An open-source, faster Devin alternative
TypeScript
merge main into docs/connected-services — main absorbed #728 and #735; kept both rows in the capabilities table and both nav entries, kept the callService pointer alongside the approvals section in tools.mdx, and added a note distinguishing the two GitHub paths #735 introduced: callService proxies the REST API, useConnection injects a token for git and gh
Brian Reardon78fce8a2ff16
diff --cc cli/src/api.tsindex 2572b5a8,7d9a91d2..1c42b452--- a/cli/src/api.ts+++ b/cli/src/api.ts@@@ -63,21 -63,26 +63,39 @@@ export interface ManagedSecretMetadataupdatedAt: string;}+ export interface ManagedGitHubStatus {+ environments: Array<{+ environment: "development" | "production";+ state: "not_connected" | "active" | "suspended" | "deleted";+ installation?: {+ id: string;+ githubInstallationId: number;+ accountLogin: string;+ accountType: string;+ repositorySelection: "all" | "selected";+ state: "active" | "suspended" | "deleted";+ createdAt: string;+ updatedAt: string;+ };+ }>;+ app: { slug: string } | null;+ }+// Model access (work 011). The provider token is write-only; these shapes// carry only normalized metadata.+/** An account the platform holds an OAuth credential for. */+export interface ServiceConnection {+ id: string;+ /** `google` or `github` — the grant, not the API being called. */+ provider: string;+ /** The alias it was connected under; what an agent passes as `label`. */+ label: string;+ /** Who the account belongs to, e.g. the mailbox address. */+ displayName?: string;+ scopes?: string[];+ status: string;+}+export interface ModelAccessConnection {id: string;organizationId: string;diff --cc docs/agents/capabilities.mdxindex c1036b1e,c4d70882..fa4cfb43--- a/docs/agents/capabilities.mdx+++ b/docs/agents/capabilities.mdx@@@ -9,7 -9,7 +9,8 @@@ the narrowest capability that fits the| Capability | Use it for | Where the work happens | How it is attached || --- | --- | --- | --- || Code-defined tool | One typed operation you implement | Your TypeScript `run()` function | `useTool(tool)` |+ | Tool that waits for approval | A write a person should agree to first | Your `preview()` shows it; your `apply()` runs after a decision | `useTool(tool)` — the same tool, defined with `preview`/`apply` instead of `run` |+| Connected service | Gmail, Calendar, Drive, Sheets or GitHub, on someone's connected account | OpenComputer attaches and refreshes the credential | `useService("gmail")`, then `callService()` in a tool || MCP server | A service that already publishes a collection of tools | The remote MCP server | `useMcpServer(server)` || Skill | A reusable procedure, checklist, or supporting files | The agent follows the loaded instructions | Place it under `skills/` || Subagent | Delegating a focused task to another project agent | The delegated agent | `useSubagent(agentId)` |diff --cc docs/agents/services.mdxindex e3b5e53b,00000000..6271b3bdmode 100644,000000..100644--- a/docs/agents/services.mdx+++ b/docs/agents/services.mdx@@@ -1,219 -1,0 +1,227 @@@+---+title: "Connected services"+description: "Call Gmail, Calendar, Drive, Sheets and GitHub with a credential the platform holds and refreshes"+---++Some credentials cannot be a secret you set. An OAuth token is short-lived,+belongs to a person rather than to your project, and has to be refreshed. So+the platform holds it: someone connects their account once, and your agent asks+for a service by name instead of a URL and a header.++The access token never enters your runtime — there is nothing to log, leak, or+hand to a model.++<Note>+This is the other half of [declared connections](/agents/secrets). Use+`defineConnection` when **you** hold the credential and it is a static secret.+Use `callService` when the **platform** holds it and has to refresh it.+</Note>++## 1. Connect an account++Do this first — the code below returns `404` until an account exists.++Each account is connected under a **label**, which is how your agent addresses+it.++```bash+opencomputer connection add gmail --alias support+```++That prints a link. Whoever opens it consents with their own account and it is+connected under that label — they never sign in to OpenComputer, and no+credential passes through the CLI. Send the link to the person whose account it+is.++Omitting `--alias` connects it as `default`, which is the label the examples+below assume. **`default` is a literal name, not a fallback**: if you connect an+account as `support`, a call that passes no `label` looks for one called+`default` and gets a `404` even though `support` is the only account you have.++```bash+opencomputer connection list+# support google connected [email protected]++opencomputer connection remove support+```++Each of these has a `--json` form, and the same routes are available directly+under `/api/managed-agents/connections` if you would rather script against the+API than shell out.++## 2. Declare the service++```tsx+import { useService, useTool } from "@opencomputer/agent";+import { unread } from "./tools/mail.js";++export default function Agent() {+ useService("gmail");+ useTool(unread);+ return "Answer questions about the triage queue.";+}+```++`useService` takes a literal string, read out of your source at build time. It+puts the service in the capability manifest, so what your agent can reach is+reviewable without running it, and it asks the deployment for that grant —+without it, `listServices()` returns nothing.++| Service | Reaches | Grant |+| --- | --- | --- |+| `gmail` | `gmail.googleapis.com` | Google |+| `calendar` | `www.googleapis.com` | Google |+| `drive` | `www.googleapis.com` | Google |+| `sheets` | `www.googleapis.com` | Google |+| `github` | GitHub's API | GitHub |++The four Google services are one consent; GitHub is its own. A name outside+that list fails the build rather than the request.+++<Note>++There are two ways to reach GitHub, and they are for different jobs. Use++`callService({ service: "github" })` to call the REST API on an account someone++connected. Use a [GitHub App connection](/agents/github) when the agent needs++to run `git` and `gh` itself — that one injects a token into the sandbox rather++than proxying requests.++</Note>+++## 3. Call it from a tool++`useService` goes in the agent; `callService` goes in a tool. An agent renders+synchronously and cannot wait for a request.++```tsx+import { callService, defineTool } from "@opencomputer/agent";++export const unread = defineTool({+ name: "unread_reports",+ description: "Count unread messages labelled triage",+ async run({ signal }) {+ const response = await callService({+ service: "gmail",+ path: "/gmail/v1/users/me/messages?q=label:triage+is:unread",+ signal,+ });+ if (!response.ok) {+ throw new Error(`gmail: ${response.status} ${await response.text()}`);+ }+ const { messages = [] } = (await response.json()) as {+ messages?: unknown[];+ };+ return { waiting: messages.length };+ },+});+```++Note what that counts. Gmail returns at most 100 message ids per page, so+`messages.length` is the size of the first page, not the total — real counting+means following `nextPageToken`. Most collection APIs behave this way.++`callService` returns the service's own response — status, headers and body — as+`fetch` would, so a `403` for a missing scope stays distinguishable from a `404` for a+deleted message. Check `response.ok`; a model told only "it failed" will retry+forever.++Writes take the same shape:++```tsx+await callService({+ service: "gmail",+ label: "support",+ method: "POST",+ path: "/gmail/v1/users/me/messages/abc/modify",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ removeLabelIds: ["UNREAD"] }),+ signal,+});+```++## 4. Several accounts++Accounts are connected and disconnected long after the artifact is built, so+ask for them rather than naming them in source.++```tsx+export const sweep = defineTool({+ name: "sweep_mailboxes",+ description: "Count unread mail in every connected mailbox",+ async run({ signal }) {+ const mailboxes = await listServices({ provider: "google", signal });+ const counts: Record<string, number> = {};++ for (const mailbox of mailboxes) {+ const response = await callService({+ service: "gmail",+ label: mailbox.label,+ path: "/gmail/v1/users/me/messages?q=is:unread",+ signal,+ });+ const { messages = [] } = (await response.json()) as {+ messages?: unknown[];+ };+ counts[mailbox.displayName ?? mailbox.label] = messages.length;+ }+ return counts;+ },+});+```++| Field | What it is |+| --- | --- |+| `id` | The connection's id, for the disconnect route |+| `label` | The alias it was connected under. Pass this as `label`. |+| `displayName` | Who the account belongs to, e.g. the mailbox address |+| `provider` | `google` or `github` |+| `scopes` | What was granted at consent |+| `status` | `connected` accounts are usable |++Only connected accounts are returned by default; pass `connectedOnly: false`+for pending ones too. Connecting an account needs no redeploy — the next run+sees it, and a consent finished seconds ago is reconciled before the list is+answered.++## Limits++A proxied request is not an unrestricted `fetch`.++| | |+| --- | --- |+| Methods | `GET`, `POST`, `PUT`, `PATCH`, `DELETE` |+| Request headers | Only `accept`, `content-type`, `if-match`, `if-none-match` |+| Request body | 4 MB |+| Response body | 4 MB |+| Time | 30 seconds |++**Other request headers are dropped, not rejected.** The request is still sent+without them, so an API that changes behaviour on a header you set will act as+though you never set it. There is no error to catch.++Authentication headers are dropped for the reason they are on a declared+connection: the credential is the platform's to attach, and a request that+could overwrite it could also send it elsewhere.++Both size limits raise an error rather than truncating, so an unexpectedly+large response fails loudly instead of arriving half-parsed. Page through large+collections rather than asking for them in one call.++## When something fails++| You see | It means | Do this |+| --- | --- | --- |+| `404 connection_not_found` | No account under **that label** — often a call with no `label` while the account was connected as something else | `opencomputer connection list` to see the labels, then pass the matching one — or connect an account |+| `409 connection_alias_required` | Several accounts connected, no `label` given | Pass `label`; the message lists them |+| `403` from the service | The consent is narrower than the call needs | Reconnect the account with wider access |+| `listServices()` returns `[]` | The service is not declared | Add `useService("gmail")` |+| A header you set is ignored | It is not in the allowlist above | Nothing — it cannot be sent |+| Throws *managed connections are unavailable* | No connection layer | You are running outside the platform |++A `403` cannot be fixed from the agent. What a request may do is fixed by the+consent that created the connection; read `scopes` from `listServices()` to see+what was actually granted.++## What this does not do++The platform does not proxy arbitrary hosts. A service reaches its own API and+nothing else — for anything outside the table above, declare an+[HTTP connection](/agents/secrets) instead.diff --cc docs/agents/tools.mdxindex 2abd707d,37e3db59..70906a5c--- a/docs/agents/tools.mdx+++ b/docs/agents/tools.mdx@@@ -125,10 -129,90 +129,94 @@@ Declare an HTTP connection, store the vcall the connection's `fetch()` method. See[Secrets and outbound requests](/agents/secrets) for a complete example.+For Gmail, Calendar, Drive, Sheets or GitHub, the credential belongs to whoever+connected the account and the platform refreshes it — call those with+[`callService`](/agents/services) instead.++ ## Wait for a person before writing++ Some writes should not happen because a model decided they should. Such a tool+ proposes instead: the model calls it, nothing is written, and the person the+ agent is talking to sees a card with the exact change and decides.++ There is no separate primitive for this. Give `defineTool` a `preview` and an+ `apply` instead of a `run`, and the model's call becomes a proposal. `run` is+ written for you. `useTool` selects the tool exactly as it selects any other,+ and the model cannot tell the difference — waiting for approval is a property+ of a tool, not a different kind of thing.++ ```tsx+ import { defineTool } from "@opencomputer/agent";+ import { billing } from "./connections/billing";++ export const attach = defineTool({+ name: "attach",+ description: "Move a customer onto a plan",+ input: {+ type: "object",+ required: ["customerId", "planId"],+ properties: {+ customerId: { type: "string" },+ planId: { type: "string" },+ },+ },+ // What the person sees. It may read; it must not write.+ async preview({ input, signal }) {+ const customer = await billing+ .fetch(`/customers/${String(input.customerId)}`, { signal })+ .then((response) => response.json());+ return {+ title: `Move ${customer.name} to ${String(input.planId)}`,+ facts: [+ { label: "Today", value: customer.plan },+ { label: "After", value: String(input.planId) },+ { label: "Charged now", value: customer.nextCharge },+ ],+ };+ },+ // Runs only once somebody approves, from the arguments on the card.+ async apply({ input, decision, signal }) {+ return billing.fetch("/subscriptions", {+ method: "POST",+ headers: { "Idempotency-Key": decision.id },+ body: JSON.stringify({+ customer: input.customerId,+ plan: input.planId,+ }),+ signal,+ });+ },+ });+ ```++ The model calls `attach` like any other tool and is told the change was+ recorded for approval, so it stops rather than reporting the work as done.++ `apply` runs later, with the arguments that were on the card — no second pass+ through the model, so what happens is what was agreed to. The proposing session+ is usually gone by then, and that is fine: `apply` needs its arguments, not the+ conversation.++ ### Always pass `decision.id`++ `decision.id` identifies this approval, and it is the same value on every+ attempt to carry it out. Give it to whatever you call as an idempotency key.++ If a write never reports back — the runtime died mid-flight, the answer was+ lost — it is recorded as unconfirmed rather than failed, because it may well+ have happened. That is only recoverable if running it again is safe, and this+ is what makes it safe.++ ### What this does and does not guarantee++ Approval is a convention your code cooperates with. Nothing stops a tool from+ writing inside `preview`. What the platform guarantees is narrower and+ still worth having: an approved write runs **once**, from the arguments the+ person agreed to, whether or not the session that proposed it still exists.++ A tool that waits needs a conversation to ask in. Called from the playground,+ a schedule or a webhook, there is nobody to ask, and the call fails saying so.+## Tools versus skills and MCP- A tool executes TypeScript you own.diff --cc docs/docs.jsonindex adfc606e,a242a78e..7679c6c3--- a/docs/docs.json+++ b/docs/docs.json@@@ -50,7 -50,7 +50,8 @@@"agents/channels","agents/outboxes","agents/secrets",+ "agents/services",+ "agents/github","agents/byok","agents/deployments"]