Hosted Agents

Hosted Agents

Guides the design of hosted background coding agents: sandboxed remote environments, warm pools, session persistence, multiplayer sessions and self-spawning sub-agents.

Skill files3 files

references/

scripts/

SKILL.md302 lines
1
---
2
name: hosted-agents
3
description: "This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes."
4
---
5
6
# Hosted Agent Infrastructure
7
8
Hosted agents run in remote sandboxed environments rather than on local machines. When designed well, they provide unlimited concurrency, consistent execution environments, and multiplayer collaboration. The critical insight is that session speed should be limited only by model provider time-to-first-token, with all infrastructure setup completed before the user starts their session.
9
10
## When to Activate
11
12
Activate this skill when:
13
- Building background coding agents that run independently of user devices
14
- Designing sandboxed execution environments for agent workloads
15
- Implementing multiplayer agent sessions with shared state
16
- Creating multi-client agent interfaces (Slack, Web, Chrome extensions)
17
- Scaling agent infrastructure beyond local machine constraints
18
- Building systems where agents spawn sub-agents for parallel work
19
20
Do not activate this skill for adjacent work owned by other skills:
21
- Designing the autonomous research loop, novelty gates, rollback policy, or merge boundaries: `harness-engineering`.
22
- Choosing supervisor, swarm, or handoff topology without hosted infrastructure concerns: `multi-agent-patterns`.
23
- Designing the tools used by a hosted agent, such as spawn/status tools or PR tools: `tool-design`.
24
- Managing file-backed state inside a session rather than the hosted runtime itself: `filesystem-context`.
25
26
## Core Concepts
27
28
Move agent execution to remote sandboxed environments to eliminate the fundamental limits of local execution: resource contention, environment inconsistency, and single-user constraints. Remote sandboxes unlock unlimited concurrency, reproducible environments, and collaborative workflows because each session gets its own isolated compute with a known-good environment image.
29
30
Design the architecture in three layers because each layer scales independently. Build sandbox infrastructure for isolated execution, an API layer for state management and client coordination, and client interfaces for user interaction across platforms. Keep these layers cleanly separated so sandbox changes do not ripple into clients.
31
32
## Detailed Topics
33
34
### Sandbox Infrastructure
35
36
**The Core Challenge**
37
Eliminate sandbox spin-up latency because users perceive anything over a few seconds as broken. Development environments require cloning repositories, installing dependencies, and running build steps -- do all of this before the user ever submits a prompt.
38
39
**Image Registry Pattern**
40
Pre-build environment images on a regular cadence (every 30 minutes works well) because this makes synchronization with the latest code a fast delta rather than a full clone. Include in each image:
41
- Cloned repository at a known commit
42
- All runtime dependencies installed
43
- Initial setup and build commands completed
44
- Cached files from running app and test suite once
45
46
When starting a session, spin up a sandbox from the most recent image. The repository is at most 30 minutes out of date, making the remaining git sync fast.
47
48
**Snapshot and Restore**
49
Take filesystem snapshots at key points to enable instant restoration for follow-up prompts without re-running setup:
50
- After initial image build (base snapshot)
51
- When agent finishes making changes (session snapshot)
52
- Before sandbox exit for potential follow-up
53
54
**Git Configuration for Background Agents**
55
Configure git identity explicitly in every sandbox because background agents are not tied to a specific user during image builds:
56
- Generate GitHub app installation tokens for repository access during clone
57
- Set git config `user.name` and `user.email` when committing and pushing changes
58
- Use the prompting user's identity for commits, not the app identity
59
60
**Warm Pool Strategy**
61
Maintain a pool of pre-warmed sandboxes for high-volume repositories because cold starts are the primary source of user frustration:
62
- Keep sandboxes ready before users start sessions
63
- Expire and recreate pool entries as new image builds complete
64
- Start warming a sandbox as soon as a user begins typing (predictive warm-up)
65
66
### Agent Framework Selection
67
68
**Server-First Architecture**
69
Structure the agent framework as a server first, with TUI and desktop apps as thin clients, because this prevents duplicating agent logic across surfaces:
70
- Multiple custom clients share one agent backend
71
- Consistent behavior across all interaction surfaces
72
- Plugin systems extend functionality without client changes
73
- Event-driven architectures deliver real-time updates to any connected client
74
75
**Code as Source of Truth**
76
Select frameworks where the agent can read its own source code to understand behavior. Prioritize this because having code as source of truth prevents the agent from hallucinating about its own capabilities -- an underrated failure mode in AI development.
77
78
**Plugin System Requirements**
79
Require a plugin system that supports runtime interception because this enables safety controls and observability without modifying core agent logic:
80
- Listen to tool execution events (e.g., `tool.execute.before`)
81
- Block or modify tool calls conditionally
82
- Inject context or state at runtime
83
84
### Speed Optimizations
85
86
**Predictive Warm-Up**
87
Start warming the sandbox as soon as a user begins typing their prompt, not when they submit it, because the typing interval (5-30 seconds) is enough to complete most setup:
88
- Clone latest changes in parallel with user typing
89
- Run initial setup before user hits enter
90
- For fast spin-up, sandbox can be ready before user finishes typing
91
92
**Parallel File Reading**
93
Allow the agent to start reading files immediately even if sync from latest base branch is not complete, because in large repositories incoming prompts rarely touch recently-changed files:
94
- Agent can research immediately without waiting for git sync
95
- Block file edits (not reads) until synchronization completes
96
- This separation is safe because read-time data staleness of 30 minutes rarely matters for research
97
98
**Maximize Build-Time Work**
99
Move everything possible to the image build step because build-time duration is invisible to users:
100
- Full dependency installation
101
- Database schema setup
102
- Initial app and test suite runs (populates caches)
103
104
### Self-Spawning Agents
105
106
**Agent-Spawned Sessions**
107
Build tools that allow agents to spawn new sessions because frontier models are capable of decomposing work and coordinating sub-tasks:
108
- Research tasks across different repositories
109
- Parallel subtask execution for large changes
110
- Multiple smaller PRs from one major task
111
112
Expose three primitives: start a new session with specified parameters, read status of any session (check-in capability), and continue main work while sub-sessions run in parallel.
113
114
**Prompt Engineering for Self-Spawning**
115
Engineer prompts that guide when agents should spawn sub-sessions rather than doing work inline:
116
- Research tasks that require cross-repository exploration
117
- Breaking monolithic changes into smaller PRs
118
- Parallel exploration of different approaches
119
120
### API Layer
121
122
**Per-Session State Isolation**
123
Isolate state per session (SQLite per session works well) because cross-session interference is a subtle and hard-to-debug failure mode:
124
- Dedicated database per session
125
- No session can impact another's performance
126
- Architecture handles hundreds of concurrent sessions
127
128
**Real-Time Streaming**
129
Stream all agent work in real-time because high-frequency feedback is critical for user trust:
130
- Token streaming from model providers
131
- Tool execution status updates
132
- File change notifications
133
134
Use WebSocket connections with hibernation APIs to reduce compute costs during idle periods while maintaining open connections.
135
136
**Synchronization Across Clients**
137
Build a single state system that synchronizes across all clients (chat interfaces, Slack bots, Chrome extensions, web interfaces, VS Code instances) because users switch surfaces frequently and expect continuity. All changes sync to the session state, enabling seamless client switching.
138
139
### Multiplayer Support
140
141
**Why Multiplayer Matters**
142
Design for multiplayer from day one because it is nearly free to add with proper synchronization architecture, and it unlocks high-value workflows:
143
- Teaching non-engineers to use AI effectively
144
- Live QA sessions with multiple team members
145
- Real-time PR review with immediate changes
146
- Collaborative debugging sessions
147
148
**Implementation Requirements**
149
Build the data model so sessions are not tied to single authors because multiplayer fails silently if authorship is hardcoded:
150
- Pass authorship info to each prompt
151
- Attribute code changes to the prompting user
152
- Share session links for instant collaboration
153
154
### Authentication and Authorization
155
156
**User-Based Commits**
157
Use GitHub authentication to open PRs on behalf of the user (not the app) because this preserves the audit trail and prevents users from approving their own AI-generated changes:
158
- Obtain user tokens for PR creation
159
- PRs appear as authored by the human, not the bot
160
161
**Sandbox-to-API Flow**
162
Follow this sequence because it keeps sandbox permissions minimal while letting the API handle sensitive operations:
163
1. Sandbox pushes changes (updating git user config)
164
2. Sandbox sends event to API with branch name and session ID
165
3. API uses user's GitHub token to create PR
166
4. GitHub webhooks notify API of PR events
167
168
### Client Implementations
169
170
**Slack Integration**
171
Prioritize Slack as the first distribution channel for internal adoption because it creates a virality loop as team members see others using it:
172
- No syntax required, natural chat interface
173
- Build a classifier (fast model with repo descriptions) to determine which repository to work in
174
- Include hints for common repositories; allow "unknown" for ambiguous cases
175
176
**Web Interface**
177
Build a web interface with these features because it serves as the primary power-user surface:
178
- Real-time streaming of agent work on desktop and mobile
179
- Hosted VS Code instance running inside sandbox
180
- Streamed desktop view for visual verification
181
- Before/after screenshots for PRs
182
- Statistics page: sessions resulting in merged PRs (primary metric), usage over time, live "humans prompting" count
183
184
**Chrome Extension**
185
Build a Chrome extension for non-engineering users because DOM and React internals extraction gives higher precision than raw screenshots at lower token cost:
186
- Sidebar chat interface with screenshot tool
187
- Extract DOM/React internals instead of raw images
188
- Distribute via managed device policy (bypasses Chrome Web Store)
189
190
## Practical Guidance
191
192
### Hosted Agent Design Checklist
193
194
Before building the system, decide these infrastructure properties explicitly:
195
196
1. **Sandbox lifecycle**: how sessions start, snapshot, restore, time out, and terminate.
197
2. **Image and warm-pool policy**: how often images rebuild, which caches are precomputed, and when warm sandboxes expire.
198
3. **Read/write synchronization**: whether agents may read before repository sync completes, and which events unblock writes.
199
4. **Per-session state isolation**: what storage belongs to one session, what is shared, and how cross-session interference is prevented.
200
5. **Auth and commit identity**: which operations use app tokens, which use user tokens, and how commits are attributed.
201
6. **Output extraction**: how branches, PRs, files, logs, screenshots, and session summaries leave the sandbox.
202
7. **Budget and teardown**: maximum runtime, cost ceilings, idle policy, and forced cleanup behavior.
203
204
### Follow-Up Message Handling
205
206
Choose between queueing and inserting follow-up messages sent during execution. Prefer queueing because it is simpler to manage and lets users send thoughts on next steps while the agent works. Build a mechanism to stop the agent mid-execution when needed, because without it users feel trapped.
207
208
### Metrics That Matter
209
210
Track these metrics because they indicate real value rather than vanity usage:
211
- Sessions resulting in merged PRs (primary success metric)
212
- Time from session start to first model response
213
- PR approval rate and revision count
214
- Agent-written code percentage across repositories
215
216
### Adoption Strategy
217
218
Drive internal adoption through visibility rather than mandates because forced usage breeds resentment:
219
- Work in public spaces (Slack channels) for visibility
220
- Let the product create virality loops
221
- Do not force usage over existing tools
222
- Build to people's needs, not hypothetical requirements
223
224
## Examples
225
226
**Example 1: Background coding session lifecycle**
227
228
```text
229
user prompt
230
-> API allocates warm sandbox from current image
231
-> sandbox syncs latest branch delta
232
-> reads allowed immediately, writes blocked until sync completes
233
-> agent edits and tests inside isolated workspace
234
-> sandbox snapshots final filesystem
235
-> branch is pushed
236
-> API creates PR using user token
237
-> session summary, logs, and PR URL are returned to clients
238
```
239
240
This sequence keeps setup work outside the user-visible path while preserving auditability and user ownership of code changes.
241
242
**Example 2: Boundary decision**
243
244
If the task is "make the agent loop run for days with locked rubrics and PR approval," use `harness-engineering`. If the task is "run that loop in remote sandboxes with warm pools, session snapshots, streaming clients, and user-authored PRs," use this skill.
245
246
## Guidelines
247
248
1. Pre-build environment images on regular cadence (30 minutes is a good default)
249
2. Start warming sandboxes when users begin typing, not when they submit
250
3. Allow file reads before git sync completes; block only writes
251
4. Structure agent framework as server-first with clients as thin wrappers
252
5. Isolate state per session to prevent cross-session interference
253
6. Attribute commits to the user who prompted, not the app
254
7. Track merged PRs as primary success metric
255
8. Build for multiplayer from the start; it is nearly free with proper sync architecture
256
257
## Gotchas
258
259
1. **Cold start latency**: First sandbox spin-up takes 30-60s and users perceive this as broken. Use warm pools and predictive warm-up on keystroke to eliminate perceived wait time.
260
2. **Image staleness**: Infrequent image rebuilds mean agents run with outdated dependencies or code. Set a 30-minute rebuild cadence and monitor image age; alert if builds fail silently.
261
3. **Sandbox cost runaway**: Long-running agents without timeout or budget caps accumulate unexpected costs. Set hard timeout limits (default 4 hours) and per-session cost ceilings.
262
4. **Auth token expiration mid-session**: Long tasks fail when GitHub tokens expire partway through. Implement token refresh logic and check token validity before sensitive operations like PR creation.
263
5. **Git config in sandboxes**: Missing `user.name` or `user.email` causes commit failures in background agents. Always set git identity explicitly during sandbox configuration, never assume it carries over from the image.
264
6. **State loss on sandbox recycle**: Agents lose completed work if the sandbox is recycled or times out before results are extracted. Always snapshot before termination and extract artifacts (branches, PRs, files) before letting the sandbox die.
265
7. **Oversubscribing warm pools**: Maintaining too many warm sandboxes wastes money during low-traffic periods. Scale pool size based on traffic patterns and time-of-day; use autoscaling rather than fixed pool sizes.
266
8. **Missing output extraction**: Agents complete work inside the sandbox but results never get pulled out to the user. Build explicit extraction steps (push branch, create PR, return file contents) into the session teardown flow.
267
268
## Integration
269
270
This skill owns hosted runtime infrastructure. Adjacent skills own the control system, topology, and tool contracts:
271
272
- `harness-engineering`: governance, locked evaluators, rollback, novelty gates, and human approval boundaries around autonomous work.
273
- `multi-agent-patterns`: self-spawning and supervisor patterns once hosted infrastructure exists.
274
- `tool-design`: spawn, status, teardown, and PR tools exposed to agents.
275
- `context-optimization`: managing context across distributed hosted sessions.
276
- `filesystem-context`: using the sandbox filesystem for durable session state and artifacts.
277
278
## References
279
280
Internal reference:
281
- [Infrastructure Patterns](./references/infrastructure-patterns.md) - Read when: implementing sandbox lifecycle, image builds, or warm pool logic for the first time
282
283
Related skills in this collection:
284
- multi-agent-patterns - Read when: designing self-spawning or supervisor coordination patterns
285
- tool-design - Read when: building tools for agent session management or status checking
286
- context-optimization - Read when: context windows fill up across distributed agent sessions
287
288
External resources:
289
- [Ramp](https://builders.ramp.com/post/why-we-built-our-background-agent) - Read when: evaluating whether to build vs. buy background agent infrastructure
290
- [Modal Sandboxes](https://modal.com/docs/guide/sandbox) - Read when: choosing a cloud sandbox provider or comparing isolation models
291
- [Cloudflare Durable Objects](https://developers.cloudflare.com/durable-objects/) - Read when: designing per-session state management with WebSocket hibernation
292
- [OpenCode](https://github.com/sst/opencode) - Read when: selecting a server-first agent framework or studying plugin architectures
293
294
---
295
296
## Skill Metadata
297
298
**Created**: 2026-01-12
299
**Last Updated**: 2026-05-15
300
**Author**: Agent Skills for Context Engineering Contributors
301
**Version**: 1.2.0
302

© Context Engineering Agent Skills Contributors · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…