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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,12 @@ Ids are time-ordered (UUIDv7) so they sort and page without a second index.
### Named agent definitions

A named agent has one permanent session on its home machine. On the encrypted host
connection, `agents.saveProfile` accepts `id`, `name`, `job`, `iconUrl`, `harness` and
`prompt`. The browser generates the ID once at creation. The host starts the chat in
the user's home directory with Ask permissions. It returns the session, including
connection, `agents.saveProfile` accepts `id`, `name`, `job`, `iconUrl`, `harness`,
`prompt` and the optional session settings `mode`, `plan` and `model`. An empty model
selects the harness default. Omitted settings keep their current values on edit.
The browser generates the ID once at creation and offers the account's default permissions.
The host starts the chat in the user's home directory, using Ask when no mode was supplied.
It returns the session, including
`agent: { job, iconUrl, revision }`. Agents appear in the existing session watch.
The name is the session title. Renaming through the profile editor preserves the chat ID.

Expand Down
4 changes: 4 additions & 0 deletions internal/e2e/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/modelcontextprotocol/go-sdk/mcp"

"github.com/andyjmorgan/outpost/internal/host/peer"
"github.com/andyjmorgan/outpost/internal/host/wire"
"github.com/andyjmorgan/outpost/internal/mcpserver"
)

Expand Down Expand Up @@ -169,6 +170,9 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) {
if err := delegated.Call(r.ctx, "agents.create", map[string]string{"id": created.SessionID, "revision": "spoof"}, nil); err == nil {
t.Fatal("create accepted a target ID and revision")
}
if err := delegated.Call(r.ctx, "agents.create", map[string]string{"requestKey": "other", "name": "Other", "job": "Review", "harness": "codex", "prompt": "Review changes", "mode": "full-access"}, nil); code(err) != wire.CodeBadParams {
t.Fatalf("delegated creation accepted owner run settings: %v", err)
}
delegated.Close()

// Another OAuth client in the same sign-in session is a different key, not yet approved.
Expand Down
5 changes: 4 additions & 1 deletion internal/host/agent/definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,9 @@ func registerDefinitions(router *rpc.Router, root, endpoint, home string, svc *s
router.Handle("agents.saveDefinition", rpc.Typed(func(c *rpc.Call, p *profileRequest) (any, error) { return save(c, p, false) }), false)
if svc != nil {
router.Handle("agents.create", rpc.Typed(func(c *rpc.Call, p *profileRequest) (any, error) {
if p.Mode != "" || p.Model != nil || p.Plan != nil {
return nil, wire.Errorf(wire.CodeBadParams, "agent run settings belong to the profile editor")
}
if p.ID != "" || p.Revision != "" {
return nil, wire.Errorf(wire.CodeBadParams, "agents.create cannot target an existing profile")
}
Expand All @@ -213,7 +216,7 @@ func registerDefinitions(router *rpc.Router, root, endpoint, home string, svc *s
}
if sess != nil {
_, prompt, _ := strings.Cut(doc, promptDivider)
return &profileRequest{definitionRequest: definitionRequest{ID: p.ID, Prompt: prompt}, AgentSettings: session.AgentSettings{Name: *sess.Title, Job: sess.Agent.Job, IconURL: sess.Agent.IconURL, Harness: sess.Harness, Revision: sess.Agent.Revision}}, nil
return &profileRequest{definitionRequest: definitionRequest{ID: p.ID, Prompt: prompt}, AgentSettings: session.AgentSettings{Name: *sess.Title, Job: sess.Agent.Job, IconURL: sess.Agent.IconURL, Harness: sess.Harness, Revision: sess.Agent.Revision, Mode: sess.Mode, Plan: &sess.Plan, Model: sess.Model}}, nil
}
}
data, err := os.ReadFile(path)
Expand Down
41 changes: 35 additions & 6 deletions internal/host/session/named_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ import (
)

type AgentSettings struct {
Name string `json:"name"`
Job string `json:"job"`
IconURL string `json:"iconUrl"`
Harness string `json:"harness"`
Revision string `json:"revision"`
Name string `json:"name"`
Job string `json:"job"`
IconURL string `json:"iconUrl"`
Harness string `json:"harness"`
Revision string `json:"revision"`
Mode string `json:"mode,omitempty"`
Plan *bool `json:"plan,omitempty"`
Model *string `json:"model,omitempty"`
}

type AgentDocument struct {
Expand Down Expand Up @@ -69,7 +72,28 @@ func (s *Service) SaveAgent(ctx context.Context, id, cwd string, settings AgentS
if sess.Agent == nil || sess.Harness != settings.Harness {
return nil, errf("conflict", "this identity already belongs to another conversation")
}
if *sess.Title == settings.Name && sess.Agent.Job == settings.Job && sess.Agent.IconURL == settings.IconURL {
}
currentModel := ""
if sess.Model != nil {
currentModel = *sess.Model
}
mode := pick(settings.Mode, sess.Mode)
if !validMode(mode) {
return nil, errf("invalid", "unknown permission mode %q", mode)
}
plan := sess.Plan
if settings.Plan != nil {
plan = *settings.Plan
if plan && settings.Harness != "claude" {
return nil, errf("invalid", "Plan is only available for Claude Code")
}
}
model := currentModel
if settings.Model != nil {
model = *settings.Model
}
if sess.Agent != nil {
if mode == sess.Mode && plan == sess.Plan && model == currentModel && *sess.Title == settings.Name && sess.Agent.Job == settings.Job && sess.Agent.IconURL == settings.IconURL {
current, err := s.store.agentDocument(ctx, id)
if err != nil {
return nil, err
Expand All @@ -82,6 +106,11 @@ func (s *Service) SaveAgent(ctx context.Context, id, cwd string, settings AgentS
return nil, errf("conflict", "the profile changed; reopen the editor to load the latest version")
}
}
sess.Mode, sess.Plan = mode, plan
sess.Model = nil
if model != "" {
sess.Model = &model
}
sess.Agent = &AgentProfile{Job: settings.Job, IconURL: settings.IconURL, Revision: newID("rev")}
sess.Title, sess.TitleBy = &settings.Name, "user"
w.Changes = []any{touch(sess)}
Expand Down
7 changes: 6 additions & 1 deletion internal/host/session/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,10 @@ func (s *Service) ExecuteAs(ctx context.Context, cmd Command, may Allowed) (int6
Effort *string `json:"effort"`
}
_ = json.Unmarshal(cmd.Args, &a)
if sess.Agent != nil && ((a.Mode != nil && *a.Mode != sess.Mode) ||
(a.Plan != nil && *a.Plan != sess.Plan) || (a.Model != nil && (sess.Model == nil || *a.Model != *sess.Model))) {
sess.Agent.Revision = newID("rev")
}
if a.Mode != nil {
if !validMode(*a.Mode) {
return 0, errf("invalid", "unknown permission mode %q", *a.Mode)
Expand Down Expand Up @@ -1112,7 +1116,8 @@ func (s *Service) apply(ctx context.Context, sessionID string, rt Runtime, ev Ad
if ev.Title != nil && strings.TrimSpace(*ev.Title) != "" && sess.TitleBy != "user" && (sess.TitleBy != "" || sess.Title == nil) {
sess.Title, sess.TitleBy = ptr(clipTitle(*ev.Title)), "harness"
}
if ev.Model != nil {
// A named agent keeps the model selected by its owner, including a harness default or alias.
if ev.Model != nil && sess.Agent == nil {
sess.Model = ev.Model
}
if ev.ContextUsage != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/mcpserver/agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type AgentCreateInput struct {
Job string `json:"job" jsonschema:"short description of the agent's job"`
Harness string `json:"harness" jsonschema:"claude or codex"`
Prompt string `json:"prompt" jsonschema:"standing instructions for the agent, preserved verbatim"`
IconURL string `json:"iconUrl,omitempty" jsonschema:"optional HTTP or HTTPS icon URL; the web UI displays same-origin icons"`
IconURL string `json:"iconUrl,omitempty" jsonschema:"optional icon URL (HTTPS or a URL on the Outpost site)"`
RequestKey string `json:"requestKey,omitempty" jsonschema:"stable creation key for this connection on this machine; defaults to the name. Reuse it for retries, or choose another to create a second agent with the same name"`
}

Expand Down
2 changes: 1 addition & 1 deletion internal/server/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func WebApp(dir string) http.Handler {
files := http.FileServer(http.Dir(dir))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'sha256-"+themeScriptHash+"'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'sha256-"+themeScriptHash+"'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
h.Set("Referrer-Policy", "no-referrer")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
Expand Down
13 changes: 7 additions & 6 deletions web/src/agents/AgentIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ import { useState } from 'react'

const graphemes = new Intl.Segmenter()

export function AgentIcon({ name, iconUrl, small }: { name: string; iconUrl: string; small?: boolean }) {
export function AgentIcon({ name, iconUrl, px = 18 }: { name: string; iconUrl: string; px?: number }) {
const [failedUrl, setFailedUrl] = useState('')
const size = small ? 'size-6 rounded-md text-xs' : 'size-8 rounded-lg text-sm'
const localIcon = URL.canParse(iconUrl) && new URL(iconUrl).origin === window.location.origin
if (localIcon && iconUrl !== failedUrl) {
return <img src={iconUrl} alt="" referrerPolicy="no-referrer" className={size + ' shrink-0 object-cover'} onError={() => setFailedUrl(iconUrl)} />
const style = { width: px, height: px, fontSize: Math.round(px * 0.68) }
const url = URL.canParse(iconUrl) ? new URL(iconUrl) : null
const allowed = url && (url.protocol === 'https:' || (url.protocol === 'http:' && url.origin === location.origin))
if (allowed && iconUrl !== failedUrl) {
return <img src={iconUrl} alt="" referrerPolicy="no-referrer" style={style} className="shrink-0 rounded-[3px] bg-accent object-contain" onError={() => setFailedUrl(iconUrl)} />
}
return (
<span aria-hidden="true" className={size + ' grid shrink-0 place-items-center bg-accent leading-none font-semibold text-on-accent'}>
<span aria-hidden="true" style={style} className="grid shrink-0 place-items-center rounded-[3px] bg-accent leading-none font-semibold text-on-accent">
{graphemes.segment(name.trim()).containing(0)?.segment}
</span>
)
Expand Down
58 changes: 49 additions & 9 deletions web/src/agents/AgentProfileDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { useId, useRef, useState } from 'react'
import { useEffect, useId, useRef, useState } from 'react'
import { Maximize2, Minimize2 } from 'lucide-react'
import { HarnessLabel, type Harness } from '../components/HarnessIcon'
import { Pick, Row, plain } from '../components/SettingsList'
import { Button } from '../ui/components/button'
import { Dialog, DialogBody, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '../ui/components/dialog'
import { inputClassName } from '../ui/components/input'
import { listModels, type Model, type Models } from '../outpost/catalog'
import { getPreferences } from '../preferences'
import { MODES } from '../session/modes'
import type { Mode } from '../outpost/sessions'
import { AgentIcon } from './AgentIcon'
import { refusal } from '../outpost/sessions'
import { cn } from '../lib'

Expand All @@ -13,20 +18,42 @@ export type AgentProfile = {
job: string
machine: string
harness: Harness
model: string
mode: Mode
plan: boolean
iconUrl: string
prompt: string
}

export function AgentProfileDialog({ profile, machines, onSave, onClose }: {
export function AgentProfileDialog({ profile, machines, loadModels = listModels, onSave, onClose }: {
profile?: AgentProfile
machines: { id: string; name: string }[]
loadModels?: (machine: string, harness: Harness) => Promise<Models>
onSave: (profile: AgentProfile) => void | Promise<void>
onClose: () => void
}) {
const [draft, setDraft] = useState<AgentProfile>(profile ?? {
name: '', job: '', machine: machines[0]?.id ?? '', harness: 'codex', iconUrl: '', prompt: '',
name: '', job: '', machine: machines[0]?.id ?? '', harness: 'codex', mode: getPreferences().defaultMode, plan: false, model: '', iconUrl: '', prompt: '',
})
const change = (patch: Partial<AgentProfile>) => setDraft((current) => ({ ...current, ...patch }))
const [catalog, setCatalog] = useState<{ key: string; models: Model[] }>()
const catalogKey = JSON.stringify([draft.machine, draft.harness])
const models = catalog?.key === catalogKey ? catalog.models : undefined
useEffect(() => {
let live = true
if (!draft.machine) return
loadModels(draft.machine, draft.harness).then(({ models }) => {
if (!live) return
setCatalog({ key: catalogKey, models })
const last = getPreferences().defaultModel?.[draft.harness]
if (!profile && last && models.some((m) => m.id === last)) {
setDraft((d) => ({ ...d, model: last }))
}
}, () => live && setCatalog({ key: catalogKey, models: [] }))
return () => { live = false }
}, [catalogKey, draft.machine, draft.harness, profile, loadModels])
const modes = MODES.filter((m) => draft.harness === 'claude' || !m.plan)
const permission = modes.find((m) => m.id === (draft.plan ? 'plan' : draft.mode))!
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const valid = draft.machine && draft.name.trim() && draft.job.trim() && draft.prompt.trim()
Expand All @@ -48,7 +75,7 @@ export function AgentProfileDialog({ profile, machines, onSave, onClose }: {
setSaving(true)
setError('')
try {
await onSave({ ...draft, name: draft.name.trim(), job: draft.job.trim(), iconUrl: draft.iconUrl.trim() })
await onSave({ ...draft, name: draft.name.trim(), job: draft.job.trim(), model: draft.model.trim(), iconUrl: draft.iconUrl.trim() })
} catch (e) {
setError(refusal(e))
} finally {
Expand All @@ -60,22 +87,36 @@ export function AgentProfileDialog({ profile, machines, onSave, onClose }: {
<Row label="Name"><input aria-label="Name" className={plain} autoFocus required value={draft.name} placeholder="Navi" onChange={(e) => change({ name: e.target.value })} /></Row>
<Row label="Job"><input aria-label="Job" className={plain} required value={draft.job} placeholder="Release coordinator" onChange={(e) => change({ job: e.target.value })} /></Row>
<Row label="Home machine">
<Pick label="Home machine" value={draft.machine} disabled={!!profile} options={machines.map((m) => [m.id, m.name])} onChange={(machine) => change({ machine })} />
<Pick label="Home machine" value={draft.machine} disabled={!!profile} options={machines.map((m) => [m.id, m.name])} onChange={(machine) => change({ machine, model: '' })} />
</Row>
<Row label="Harness">
{profile ? <HarnessLabel harness={draft.harness} /> : <div role="radiogroup" aria-label="Harness" className="inline-flex items-center rounded-lg border border-border bg-background p-0.5">
{(['codex', 'claude'] as const).map((harness) => (
<label key={harness} className="relative cursor-pointer">
<input type="radio" name="harness" className="peer absolute inset-0 size-full cursor-pointer opacity-0" value={harness} checked={draft.harness === harness} onChange={() => change({ harness })} />
<input type="radio" name="harness" className="peer absolute inset-0 size-full cursor-pointer opacity-0" value={harness} checked={draft.harness === harness} onChange={() => change({ harness, model: '', plan: false })} />
<span className="flex h-7 items-center rounded-md px-2 text-xs text-muted-foreground peer-checked:bg-elevated peer-checked:text-foreground peer-focus-visible:outline-2 peer-focus-visible:outline-accent">
<HarnessLabel harness={harness} />
</span>
</label>
))}
</div>}
</Row>
<Row label="Icon URL" hint={draft.iconUrl && 'Images hosted on this Outpost site appear here. Other URLs use the initial.'}>
<Row label="Model">
{models?.length === 0
? <input aria-label="Model" className={plain} value={draft.model} placeholder="Harness default" onChange={(e) => change({ model: e.target.value })} />
: <Pick label="Model" value={draft.model} disabled={!models} onChange={(model) => change({ model })}
options={[['', 'Harness default'], ...(draft.model && !models?.some((m) => m.id === draft.model) ? [[draft.model, draft.model] as [string, string]] : []), ...(models ?? []).map((m): [string, string] => [m.id, m.label])]} />}
</Row>
<Row label="Permissions">
<Pick label="Permissions" value={permission.id} danger={permission.yolo} options={modes.map((m) => [m.id, m.label])}
onChange={(id) => {
const selected = modes.find((m) => m.id === id)!
change({ mode: selected.mode, plan: !!selected.plan })
}} />
</Row>
<Row label="Icon URL">
<input aria-label="Icon URL" type="url" pattern="https?://.+" className={plain} value={draft.iconUrl} placeholder="Optional" onChange={(e) => change({ iconUrl: e.target.value })} />
<span className="ml-2 self-center"><AgentIcon name={draft.name} iconUrl={draft.iconUrl.trim()} px={16} /></span>
</Row>
</div>
<div className={cn('flex min-h-0 flex-col gap-1.5', expanded && 'flex-1')}>
Expand All @@ -86,9 +127,8 @@ export function AgentProfileDialog({ profile, machines, onSave, onClose }: {
</Button>
</div>
<textarea id={promptId} ref={promptRef} required value={draft.prompt} onChange={(e) => change({ prompt: e.target.value })} rows={4}
aria-describedby={promptId + '-hint'} className={cn(inputClassName, 'h-auto py-2 leading-5', expanded ? 'min-h-0 flex-1 resize-none' : 'resize-y')}
className={cn(inputClassName, 'h-auto py-2 leading-5', expanded ? 'min-h-0 flex-1 resize-none' : 'resize-y')}
placeholder="What should this agent do each time it wakes?" />
<p id={promptId + '-hint'} className="text-xs text-muted-foreground">Appended below Outpost’s built-in instructions in AGENT.md.</p>
</div>
</DialogBody>
{error && <p role="alert" className="px-5 pb-2 text-sm text-danger">{error}</p>}
Expand Down
18 changes: 13 additions & 5 deletions web/src/agents/profiles.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import type { Session } from '../outpost/sessions'
import { command, type Session } from '../outpost/sessions'
import { connect } from '../outpost/hosts'
import type { AgentProfile } from './AgentProfileDialog'

export async function readProfile(machine: string, id: string) {
export async function readProfile(machine: string, session: Session) {
const conn = await connect(machine)
const data = await conn.call<Omit<AgentProfile, 'machine'> & { revision: string }>('agents.readDefinition', { id })
return { ...data, machine }
const data = await conn.call<Omit<AgentProfile, 'machine' | 'mode' | 'model' | 'plan'> &
Partial<Pick<AgentProfile, 'mode' | 'model' | 'plan'>> & { revision: string }>('agents.readDefinition', { id: session.id })
// Earlier hosts return only the definition. Their session watch carries the run settings.
return { ...data, machine, mode: data.mode ?? session.mode, plan: data.plan ?? session.plan, model: (data.mode ? data.model : session.model) ?? '' }
}

export async function saveProfile(id: string, { machine, ...fields }: AgentProfile, revision?: string) {
const conn = await connect(machine)
return conn.call<Session>('agents.saveProfile', { id, ...fields, revision }, 30000)
const saved = await conn.call<Session>('agents.saveProfile', { id, ...fields, revision }, 30000)
// Older machines ignore the new fields. Use their existing session command for any
// difference. Retrying the same profile save keeps its original permanent chat.
if (saved.mode !== fields.mode || saved.plan !== fields.plan || (saved.model ?? '') !== fields.model) {
await command(machine, 'session.configure', id, { mode: fields.mode, plan: fields.plan, model: fields.model })
}
return saved
}
Loading
Loading