History

feat: refactor v2 execute wiring around run clients

Bind PM runtime at composition time and remove runtime selection from execute inputs so MCP and AI SDK share a simpler transport contract.

Rhys Sullivan committed 8 months ago

Commit 21fcb6b1 parent 432444f18 files · +670 −454Browse files

Unified · Split

18 files
  1. v2/PLAN.md +275 −334
  2. v2/apps/convex/convex/mcp.ts +7 −1
  3. v2/apps/convex/package.json +1 −0
  4. v2/apps/pm/README.md +8 −1
  5. v2/apps/pm/package.json +1 −0
  6. v2/apps/pm/src/config.ts +26 −0
  7. v2/apps/pm/src/http-server.ts +32 −0
  8. v2/apps/pm/src/main.ts +21 −91
  9. v2/apps/pm/src/mcp-handler.ts +43 −0
  10. v2/apps/pm/src/run-executor.ts +89 −0
  11. v2/bun.lock +7 −0
  12. v2/packages/ai-sdk-adapter/package.json +7 −0
  13. v2/packages/ai-sdk-adapter/src/index.ts +51 −1
  14. v2/packages/mcp-gateway/package.json +1 −0
  15. v2/packages/mcp-gateway/src/index.ts +0 −1
  16. v2/packages/mcp-gateway/src/server.ts +28 −24
  17. v2/packages/sdk/package.json +3 −0
  18. v2/packages/sdk/src/index.ts +70 −1
v2/PLAN.md+275−334
@@ -1,488 +1,429 @@
1What is executor:
2
3- Approvals
4- Permission model
5- Code execution
6 - Support abitrary tool targets (API / GraphQL / MCP / in memory)
7- Authentication
8
9Usage locally:
10
11- Approvals are stored in memory
12- Permissions are stored to file system
13- Auth creds are stored to file system
14
15Usage via AI SDK
16
17const executor = new Executor({
18runtime: deno() | nodevm() | cloudflare-dynamic-worker(),
19// all the same RPC?
20approvals:
21authentication:
22permissions:
23})
24
25Usage via Cloud:
26
27- Everything in Convex
28- Runtime is cloudflare dynamic worker
29-
30
31# Executor v2 Plan1# Executor v2 Plan
32 2
33Reference implementations and inspiration for this plan:3Reference implementations and inspiration for this plan:
34`../AnswerOverflow`4`../AnswerOverflow`
35`../quickhub`5`../quickhub`
36`../create-epoch-app`6`../create-epoch-app`
37
38## 1) Why v2 exists7## 1) Why v2 exists
39 8
40Executor today is optimized for enterprise/team correctness (workspaces, org flows, cloud control), but has too much friction for per-user adoption.9Executor today is optimized for enterprise/team correctness (workspaces, org flows, cloud control), but has too much friction for per-user adoption.
41 10
42v2 changes the default:11v2 changes the default:
43 12
44- **First-run must be local and immediate** (`npx executor <agent>` works fast).13- First run is local and immediate (`npx executor <agent>` works fast).
45- **No database dependency** in local-lite mode.14- No database dependency in local-lite mode.
46- **Cloud/self-host are upgrade targets**, not prerequisites.15- Cloud/self-host are upgrade targets, not prerequisites.
47- **One architecture for all modes** via adapters and shared contracts.16- One architecture for local and remote via shared contracts and thin adapters.
48 17
49---18---
50 19
51## 2) Product principles20## 2) Product principles
52 21
531. **Local-first**221. Local-first
54 - User gets value without login, org setup, or web onboarding.23 - User gets value without login, org setup, or web onboarding.
552. **One mental model**242. One mental model
56 - Same commands, same execution semantics across local and remote targets.25 - Same execution semantics across local and remote.
573. **Schema-first**263. Schema-first
58 - Effect Schema is the single source of truth for persisted/domain models.27 - Effect Schema is canonical for domain and persistence contracts.
594. **Execute-first tooling**284. Execute-first
60 - Top-level model tool surface is minimal; code execution is primary.29 - Keep top-level model-facing surface minimal (`execute` first).
615. **Progressive complexity**305. Service-first architecture
62 - Advanced controls exist but are hidden until needed.31 - Effect orchestration is exposed via services and layers.
636. **Service-first Effect architecture**326. Progressive complexity
64 - Effectful orchestration is exposed as `Context.Tag` services + Layers; plain functions are for pure transforms.33 - Advanced control and infra stay out of the default happy path.
65 34
66---35---
67 36
68## 3) Product modes and targets37## 3) The architecture (locked)
69
70### Modes
71
72- **local-lite**: PM daemon + in-memory hot state + file persistence. No DB.
73- **remote**: Convex-backed target (applies to both cloud and self-hosted).
74
75### Key simplification
76 38
77- `cloud` and `self-hosted` are not separate architecture branches.39v2 is split into three planes. This is the key simplification.
78- They are both **remote Convex targets**; only URL/auth/deployment ownership differs.
79 40
80### Runtime targets (adapter-based)41### Execution plane
81 42
82- **`deno-subprocess`**: local sandbox runtime (current local secure target in v2).43Runs code and resolves `tools.*` calls.
83- **`cloudflare-worker-loader`**: production cloud runtime target.
84- **`node:vm`**: explicit unsafe/dev fallback only, not default.
85 44
86---45- run lifecycle
87 46- runtime dispatch
88## 4) Control + execution model47- tool invocation pipeline
48- approvals/policy enforcement
49- credential resolution for tool calls
89 50
90### Control role (conceptual)51### Control plane
91 52
92Control includes source registry, policies, approvals/input workflow, identity/link state, and sync metadata.53Mutates and queries executor configuration/state.
93 54
94- In local-lite: handled by `apps/pm`.55- source registration/removal
95- In remote: handled by Convex + web stack.56- tool artifact refresh/rebuild
57- policy management
58- sync metadata
96 59
97### Execution role60Control is optional capability, not required for execute-only environments.
98 61
99Execution is provider-based: the runtime engine runs generated TypeScript, resolves `tools.*` calls, and routes invocation through source/tool providers (OpenAPI, MCP, GraphQL, in-memory, and future formats).62### Transport plane
100 63
101---64How clients talk to executor.
102 65
103## 5) Monorepo shape (Executor-only)66- MCP server/gateway
67- OpenAPI/RPC control API
68- AI SDK tool bridge
104 69
105```text70Transport does not own core execution semantics.
106v2/
107 apps/
108 cli/
109 pm/
110 web/
111 convex/
112
113 packages/
114 confect/ # imported from quickhub; Effect<->Convex schema bridge
115 schema/ # canonical Effect schemas
116 persistence-ports/
117 persistence-local/
118 persistence-convex/
119 domain/
120 approvals/
121 source-manager/
122 engine/
123 mcp-gateway/
124 oauth/
125 secrets/
126 sync/
127 rpc/
128 sdk/
129 ai-sdk-adapter/
130```
131 71
132---72---
133 73
134## 6) Dependency order (high-level)74## 4) Core contracts
135
136```text
137confect -> schema -> persistence-ports
138 75
139persistence-ports -> persistence-local76We do not need a mandatory public `new Executor()` product surface.
140persistence-ports -> persistence-convex
141 77
142schema + persistence-ports + oauth + secrets -> domain78Primary internal shape is a kernel service (name can vary, e.g. `createExecutorKernel`).
143 79
144domain -> approvals/source-manager/engine80### Kernel contract
145approvals/source-manager/engine -> mcp-gateway
146 81
147domain/features -> rpc -> sdk -> ai-sdk-adapter82- `execute(request) -> terminal result` (or async run id if configured)
83- `handleRuntimeToolCall(call) -> encoded tool-call result`
84- optional `control` capability
148 85
149apps/pm -> mcp-gateway + domain + persistence-local + rpc86### Adapter contracts
150apps/convex -> mcp-gateway + domain + persistence-convex + rpc
151apps/cli/web -> sdk
152```
153 87
154Rules:88- RuntimeDispatchAdapter
89 - only decides where code runs (`local-inproc`, `deno-subprocess`, `cloudflare-worker-loader`)
90- ToolInvocationService
91 - resolves tool path and invokes tool with policy/approval checks
92- CredentialResolver
93 - resolves credential headers during tool invocation callback
94- ControlService (optional)
95 - source/tool/policy management commands
155 96
156- `schema` has no dependency on feature/runtime packages.97Important boundary:
157- `domain` depends on interfaces, not concrete state adapters.98- Credential resolution is not part of runtime dispatch.
158- apps are leaves; packages do not import apps.99- Credential resolution happens in callback-time tool invocation.
159- packages expose effectful orchestration through services (`Context.Tag`), with Layers wiring implementations.
160 100
161---101---
162 102
163## 7) Local-lite PM architecture103## 5) Modes and targets
164
165`apps/pm` is the local daemon and source of hot truth.
166
167Responsibilities:
168 104
169- MCP endpoint surface105### Modes
170- source registration and status lifecycle
171- approvals/input broker
172- task orchestration and runtime execution coordination
173- persistence (snapshot + event log)
174
175### Persistence model
176 106
177- Hot state: in-memory107- local-lite: PM daemon + in-memory hot state + file durability
178- Durable: file-based108- remote: Convex-backed target (cloud and self-host are deployment variants of same target)
179 - `snapshot.json`
180 - `events.jsonl` (WAL)
181 - `artifacts/` (compiled tool manifests)
182 - secrets in secure store / dedicated protected file
183 109
184Crash/restart behavior:110### Runtime targets
185 111
186- Rehydrate from snapshot + events.112- `deno-subprocess`: local secure default
187- Rebuild derived indexes in memory.113- `cloudflare-worker-loader`: remote production default
188- Mark previously running tasks terminally with restart reason.114- `node:vm`: explicit unsafe/dev fallback only
189 115
190---116---
191 117
192## 8) Data model strategy118## 6) Local and cloud runtime flows
193 119
194Effect Schema is canonical (`packages/schema`).120### Local flow
121
1221. Request starts run (`execute`).
1232. Runtime dispatch executes locally (`inproc` or `deno-subprocess`).
1243. Runtime `tools.*` call hits local callback handler.
1254. Callback handler invokes shared tool invocation pipeline:
126 - resolve tool
127 - policy check
128 - approval gating
129 - credential resolution (if needed)
130 - provider invoke
1315. Runtime resumes and completes.
1326. Run/events persisted locally.
133
134### Cloud flow (Convex + Cloudflare worker loader)
135
1361. Request starts run in Convex.
1372. Convex dispatches run to Cloudflare loader.
1383. Worker `tools.*` call hits Convex runtime callback action (`handleToolCall`).
1394. Callback action invokes shared tool invocation pipeline:
140 - resolve tool
141 - policy check
142 - approval gating
143 - credential resolution from Convex/vault
144 - provider invoke
1455. Worker resumes and returns terminal status.
1466. Convex marks run terminal and emits events.
147
148Serverless note:
149- There is no long-lived in-memory `onToolCall` loop in cloud.
150- Callback requests are stateless/durable and reconstruct context per request.
195 151
196Current scaffold includes:152---
197
198- domain IDs (`src/ids.ts`)
199- enums/common primitives
200- model schemas:
201 - profile, workspace
202 - source, tool artifact
203 - credential ref, oauth token
204 - policy, approval
205 - task run, sync state
206 - event envelope
207- local snapshot/WAL schemas in `persistence-local`
208 153
209### Convex ID compatibility154## 7) Blocking and non-blocking execution
210 155
211IDs are now intentionally split by layer:156Both are first-class and share one implementation path.
212 157
213- **Domain IDs** live in `packages/schema` as portable branded IDs.158- Async canonical path:
214- **Convex table IDs** live in `packages/persistence-convex/src/convex-ids.ts` via `Id("table")` from `@executor-v2/confect`.159 - submit run -> return `runId`
160 - query/watch run status -> terminal result
161- Blocking convenience path:
162 - submit run
163 - wait/watch internally
164 - return terminal result
215 165
216This keeps canonical schema backend-agnostic while preserving strict table-typed IDs inside the Convex adapter boundary.166This is mostly transport/API behavior; core runtime pipeline stays the same.
217 167
218---168---
219 169
220## 9) Tooling, providers, and MCP surface170## 8) MCP, RPC, and AI SDK strategy
221 171
222### Top-level model-facing tools172### MCP
223 173
224Keep top-level surface minimal:174MCP remains the main execution transport surface.
225 175
176Top-level model-facing tools stay minimal:
226- `execute` (primary)177- `execute` (primary)
227- optional diagnostics (`health`, `version`) only if needed178- optional diagnostics (`health`, `version`)
228
229### Configuration model
230 179
231Executor config is handled as tool calls from inside `execute` via built-in namespace:180### Control API
232 181
233- `tools.executor.sources.add(...)`182Control is exposed through Executor OpenAPI/RPC contracts.
234- `tools.executor.sources.list(...)`
235- `tools.executor.sources.remove(...)`
236- other `tools.executor.*` controls as needed
237 183
238No mandatory top-level `set_enabled` in v1 (remove/add is enough for initial UX).184- Host/app control calls should use control API directly.
185- Model control calls can use `tools.executor.*` inside `execute` code.
186- Both host and model control paths must hit the same underlying control handlers.
239 187
240### Provider architecture (source-agnostic)188### AI SDK
241 189
242Use a provider registry, not format-specific execution in core runtime.190AI SDK is a bridge over executor execute capability.
243 191
244- Each provider implements:192- `toAiSdkTools(executorLike)` maps to regular AI SDK tools.
245 - `discover(source) -> ToolManifest`193- Local and remote both work if they expose `execute(...)` semantics.
246 - `invoke(call) -> ToolResult`194- If client is MCP-native, AI SDK bridge is optional.
247- Core runtime stays source-format agnostic; it resolves tool identity and dispatches to provider.
248- Initial provider kinds:
249 - `openapi`
250 - `mcp`
251 - `graphql`
252 - `in_memory` (host-registered tools; AI-SDK style)
253- Future source formats are added as new providers, without changing core execution semantics.
254 195
255### Canonical tool descriptor196AI SDK should not become a second control-plane abstraction.
256 197
257All providers publish into one canonical descriptor used by runtime and SDK:198---
258 199
259- stable tool id200## 9) Tooling and provider model
260- display metadata (name, description)
261- invocation metadata (kind + provider payload)
262- availability metadata (`local_only` vs `remote_capable`)
263 201
264Provider-specific details remain in a typed payload at the edge.202Provider registry is canonical.
265 203
266### Execution semantics204Each provider implements:
205- discover(source) -> ToolManifest
206- invoke(call) -> ToolResult
267 207
268- Agent writes TS using `tools.*`.208Initial provider kinds:
269- Runtime proxy resolves tool calls against the canonical registry.209- `openapi`
270- Provider receives invocation and returns canonical result envelope.210- `in_memory`
271- Credentials/policies/approvals are applied server-side during invocation.211- `mcp` (planned)
212- `graphql` (planned)
272 213
273---214Canonical descriptor includes:
215- stable tool id/path
216- display metadata
217- invocation metadata
218- capability metadata
274 219
275## 10) Dynamic source registration220Provider-specific details remain in provider payload types.
276 221
277Goal: user can ask the agent to use a service; agent can register the source through Executor tooling.222---
278 223
279- Discovery itself may happen outside Executor (model/web).224## 10) Persistence and registry model
280- Registration happens via Executor control tools (`tools.executor.sources.add`).
281- `source.kind` selects provider (`openapi`, `mcp`, `graphql`, etc.).
282- In-memory tools are host-registered (runtime side), not persisted remote source records by default.
283 225
284Registration flow states (networked providers):226Persistence is source of truth. Runtime registry is derived.
285 227
286- `draft -> probing -> auth_required -> connected | error`228### Persisted
287 229
288Registration flow states (in-memory provider):230- sources
231- tool artifacts/manifests
232- runs/events
233- approvals/policies
234- credential references (secret values in secure backing store)
289 235
290- `registered -> connected | error`236### Derived
291 237
292Auth handling:238- in-memory runnable tool index/registry
239- discovery indexes
293 240
294- MCP: dynamic auth/OAuth detection, client registration where needed241Mutation rule:
295- OpenAPI/GraphQL: inspect auth schemes, prompt for API key/OAuth when required2421. persist authoritative record
2432. refresh/rebuild derived artifact/index
2443. bump registry version
296 245
297Secrets are entered through host UX, not model transcript.246Run rule:
247- each run snapshots tool registry version at start
248- in-flight runs keep snapshot semantics
249- new runs see newest version
298 250
299---251---
300 252
301## 11) Approvals and elicitation/input253## 11) Approval and secret boundaries
302
303Use one internal broker for human-required inputs:
304 254
255Approvals/input are host UX concerns, not model tools.
305- approval256- approval
306- confirm257- confirm
307- form input258- form input
308- secret input259- secret input
309 260Secrets/credentials:
310### Capability-aware delivery261- never emitted to model transcript
311 262- resolved server-side during invocation
312- If client supports MCP elicitation: inline prompt.263- converted to headers/token material for provider calls
313- If not: out-of-band path (tmux pane, local web, notifications).
314
315### Terminal UX
316
317For fullscreen terminal clients:
318
319- tmux split/popup watcher
320- auto-show when pending approvals appear
321- auto-hide after queue drains (with debounce)
322
323### Important boundary
324
325Approval/input actions are **host UX callbacks**, not AI SDK model tools.
326 264
327---265---
328 266
329## 12) AI SDK strategy267## 12) Security posture
330 268- PM binds to loopback by default.
331API shape should be Executor session/adapters, not single-source helper APIs.269- Runtime callbacks require internal token validation.
332 270- Secrets do not pass through model args/transcripts.
333### Adapter-first target design271- Credential refs in state; secret values in secure stores.
334 272- Audit events store actions/decisions, not raw secret material.
335`Executor.create({ adapter })` with adapters such as:
336
337- `inproc` (embedded runtime, no install)
338- `pm` (local daemon transport)
339- `remote` (Convex target transport)
340
341### Public SDK shape
342
343Primary operations:
344
345- execute code
346- register/list/remove sources
347- register/list/remove in-memory tools (AI-SDK style)
348- stream run status/results
349
350Do not expose approval/input-response as model tools.
351Use host callbacks (e.g. `onInputRequest`) instead.
352 273
353---274---
354 275
355## 13) Security posture276## 13) Monorepo shape (Executor v2)
356 277
357- PM binds to loopback by default.278```text
358- Secrets never pass through model args/transcripts.279v2/
359- Credential references in state; secret values in secure store.280 apps/
360- Strict origin/token checks if hosted web talks to localhost target.281 cli/
361- Audit events store decisions/actions, not raw secret material.282 pm/
362 283 web/
363---284 convex/
285 packages/
286 confect/
287 schema/
288 state-contracts/
289 state-local-file/
290 state-convex/
291 domain/
292 approvals/
293 source-manager/
294 engine/
295 mcp-gateway/
296 oauth/
297 secrets/
298 sync/
299 rpc/
300 sdk/
301 ai-sdk-adapter/
302```
364 303
365## 14) Upgrade and sync304Planned follow-up split (after behavior stabilizes):
305- runtime adapters as dedicated packages
306- transport adapters as dedicated packages
366 307
367Primary path:308---
368 309
369- `local-lite -> remote`310## 14) Dependency direction
370 311
371Optional reverse:312```text
313confect -> schema -> state-contracts
372 314
373- `remote -> local-lite` export/backup315state-contracts -> state-local-file
316state-contracts -> state-convex
374 317
375Sync principles:318schema + state-contracts + oauth + secrets -> domain
319domain -> approvals/source-manager/engine
320approvals/source-manager/engine -> mcp-gateway
321domain/features -> rpc -> sdk -> ai-sdk-adapter
376 322
377- deterministic source identity323apps/pm -> mcp-gateway + domain + state-local-file + rpc
378- idempotent imports324apps/convex -> mcp-gateway + domain + state-convex + rpc
379- explicit credential migration policy325apps/cli/web -> sdk (and/or ai-sdk bridge)
380- migration cursor/mapping persisted in local state326```
327Rules:
328- `schema` is backend-agnostic.
329- apps are leaves.
330- packages do not import apps.
331- orchestration services are injected via interfaces/tags/layers.
381 332
382---333---
383 334
384## 15) Rollout phases335## 15) Rollout phases
385 336
386### Phase 0: Architecture + contracts337### Phase 0: lock contracts
387 338
388- finalize package boundaries339- finalize kernel + adapter contracts
389- finalize schema model set and invariants340- finalize execution/control/transport boundaries
390- define state/repository interfaces341- align package names/imports to current v2 structure
391 342
392### Phase 1: Local-lite core343### Phase 1: local-lite execute vertical slice
393 344
394- PM daemon skeleton345- PM execute path with persisted run lifecycle
395- file persistence (snapshot + WAL)346- runtime callback path wired through shared invocation service
396- execute path with runtime proxy integration347- openapi + in_memory providers
397- provider registry + canonical tool descriptor
398- basic source add/list/remove through `tools.executor.*`
399- first provider slices: `openapi` + `in_memory`
400 348
401### Phase 2: Input/approval UX349### Phase 2: control vertical slice
402 350
403- InputBroker + pending state persistence351- source add/list/remove via control handlers
404- tmux watcher + local web fallback352- same handlers callable from host control API and `tools.executor.*`
405- capability-aware elicitation fallback paths353- artifact refresh + registry versioning
406 354
407### Phase 3: Remote parity355### Phase 3: approvals and credentials hardening
408 356
409- persistence-convex adapter and Convex app wiring357- persisted pending/resume/deny flow
410- shared RPC contracts for pm/convex358- capability-aware UX fallbacks
411- target switching in CLI/web359- callback-time credential resolver implementations (local + convex)
412- runtime/provider capability checks for local vs remote
413 360
414### Phase 4: Sync + upgrades361### Phase 4: remote parity
415 362
416- local->remote promotion pipeline363- Convex adapter wiring for kernel and control
417- idempotent mapping/cursor strategy364- cloudflare loader integration through runtime dispatch adapter
418- conflict handling and dry-run reporting365- parity/conformance suite across local and remote
419 366
420### Phase 5: AI SDK adapters367### Phase 5: transport polish
421 368
422- inproc adapter369- MCP surface stabilization
423- pm transport adapter370- OpenAPI/RPC control surface stabilization
424- remote transport adapter371- AI SDK bridge (`toAiSdkTools`) and docs/examples
425- host callback API for inputs
426 372
427---373---
428 374
429## 16) Success criteria375## 16) Success criteria
430 376
431- First successful `npx executor <agent>` run with no login in <2 minutes.377- First successful local run with no login in under 2 minutes.
432- No required database for local-lite mode.378- No required DB in local-lite mode.
433- Same execution semantics across local and remote targets.379- Same execution semantics across local and remote.
434- Agent can add sources and execute against them in one flow.380- Callback-time approvals/policy/credentials work in both local and cloud.
435- Provider-based execution works for at least `openapi` + `in_memory` in local-lite.381- Control operations are callable both by host API and from inside execute namespace.
436- Approval/input is usable in fullscreen terminal clients.382- Blocking and non-blocking execution both available via shared run pipeline.
437 383
438---384---
439 385
440## 17) Non-goals (initial)386## 17) Non-goals (initial)
441 387
442- Recreating all enterprise admin UX in local-lite.388- Recreating full enterprise admin UX in local-lite.
443- Exposing huge top-level tool catalogs to the model by default.389- Expanding model-facing top-level tool catalog by default.
444- Maintaining separate cloud vs self-host architecture branches.390- Maintaining separate cloud vs self-host architecture branches.
391- Coupling runtime adapters with credential/secrets responsibilities.
445 392
446---393---
447 394
448## 18) Current scaffold status395## 18) Current scaffold status
449 396
450Implemented in `v2` so far:397Implemented in `v2` so far:
451
452- monorepo app/package skeleton398- monorepo app/package skeleton
453- `confect` imported from quickhub399- `confect` imported from quickhub
454- schema package scaffold with Effect models and event envelope400- schema package scaffold with Effect models/event envelope
455- schema-driven runtime tool models (canonical descriptor + OpenAPI invocation/manifest)401- shared state contracts for source/tool artifacts
456- domain ID groundwork in `schema/src/ids.ts`402- local file adapters for source/tool artifacts + snapshot/WAL state store
457- Convex table ID groundwork in `persistence-convex/src/convex-ids.ts`403- source manager OpenAPI extraction + artifact refresh/reuse
458- shared persistence ports for `SourceStore` and `ToolArtifactStore`404- provider registry contracts and routing in engine
459- local persistence adapters for source/tool artifacts
460- local-only snapshot/WAL contract and persistence implementation
461- OpenAPI extraction + artifact refresh/reuse flow
462- provider registry contracts and routing in `engine`
463- OpenAPI provider invocation + in-memory provider path through registry405- OpenAPI provider invocation + in-memory provider path through registry
464- local in-process JS runner with `tools.*` proxy dispatch406- local in-process JS runner with `tools.*` proxy
465- Deno subprocess runtime path with IPC tool-call proxying and tests407- Deno subprocess runtime path with IPC tool-call proxying and tests
466- runtime adapter contract + registry scaffold in `engine` with mapped adapters (`local-inproc`, `deno-subprocess`, `cloudflare-worker-loader`)408- runtime adapter contract + registry scaffold
467- minimal PM execute lifecycle wired through MCP `executor.execute` -> runtime adapter registry (single run, no persisted run state yet)409- PM execute lifecycle scaffold via MCP execute path
468- vertical test: OpenAPI spec -> manifest -> execute code -> HTTP tool call
469- service-first wiring (`Context.Tag` + Layer) across source manager and persistence/local runtime orchestration
470 410
471Not implemented yet:411Still missing:
472 412
473- `tools.executor.sources.add/list/remove` end-to-end PM + MCP gateway wiring413- fully wired control handlers (`tools.executor.sources.add/list/remove`) end-to-end
474- approval adapter/state machine integration (pending/resume/deny persistence) in v2 runtime path414- shared tool invocation service wired with persisted approval lifecycle in v2 path
475- provider/runtime conformance suite beyond current baseline tests (timeouts, cancellation, pending approval)415- cloudflare-worker-loader runtime adapter implementation in v2 runtime path
476- Cloudflare worker loader adapter execution integration (current adapter is explicit scaffold/not-implemented)416- parity conformance tests for runtime/provider/pending-approval/cancel flows
477- MCP/GraphQL provider implementations417- full rpc/sdk/ai-sdk adapter wiring and usage examples
478- full rpc/sdk adapter wiring and sync engine
479 418
480---419---
481 420
482## 19) Immediate next steps421## 19) Immediate next steps
483 422
4841. Add first `tools.executor.sources.add/list/remove` control operations end-to-end in PM + MCP gateway.4231. Land shared `ToolInvocationService` contract in v2 and wire PM execute callback path through it.
4852. Implement approval adapter contract with persisted pending/resume/deny flow for runtime tool calls.4242. Add `CredentialResolver` interfaces and local/convex implementations; integrate at invocation-time only.
4863. Add provider/runtime conformance tests (invoke success/failure, timeout, pending approval, cancel).4253. Implement control handlers for sources (`add/list/remove`) and route both host API and `tools.executor.*` through same code path.
4874. Add Cloudflare worker loader adapter integration against the runtime adapter contract.4264. Implement cloudflare-worker-loader runtime dispatch adapter in v2 and wire Convex callback endpoints.
4885. Extend PM execute lifecycle from single-run scaffold to persisted run state + streaming status.4275. Add run API split for async + blocking convenience (`submit` + `wait/watch`) without duplicating execution logic.
4286. Add conformance tests that run same scenarios across local and remote adapters.
429
v2/apps/convex/convex/mcp.ts+7−1
@@ -1,9 +1,15 @@
1import { handleMcpHttpRequest } from "@executor-v2/mcp-gateway";1import { handleMcpHttpRequest } from "@executor-v2/mcp-gateway";
2import { createExecutorRunClient } from "@executor-v2/sdk";
2import { httpAction } from "./_generated/server";3import { httpAction } from "./_generated/server";
3 4const runClient = createExecutorRunClient(async () => ({
5 runId: `run_${Date.now()}`,
6 status: "failed" as const,
7 error: "Convex run client is not wired yet",
8}));
4export const mcpHandler = httpAction(async (_ctx, request) =>9export const mcpHandler = httpAction(async (_ctx, request) =>
5 handleMcpHttpRequest(request, {10 handleMcpHttpRequest(request, {
6 target: "remote",11 target: "remote",
7 serverName: "executor-v2-convex",12 serverName: "executor-v2-convex",
8 serverVersion: "0.0.0",13 serverVersion: "0.0.0",
14 runClient,
9 }));15 }));
v2/apps/convex/package.json+1−0
@@ -10,6 +10,7 @@ · 9 unmodified lines
10 "dependencies": {10 "dependencies": {
11 "@executor-v2/mcp-gateway": "workspace:*",11 "@executor-v2/mcp-gateway": "workspace:*",
12 "@executor-v2/persistence-convex": "workspace:*",12 "@executor-v2/persistence-convex": "workspace:*",
13 "@executor-v2/sdk": "workspace:*",
13 "convex": "catalog:"14 "convex": "catalog:"
14 }15 }
15}16}
v2/apps/pm/README.md+8−1
@@ -6,4 +6,11 @@ Current scaffold includes: · 5 unmodified lines
6- local MCP endpoint at `POST /mcp`6- local MCP endpoint at `POST /mcp`
7- health endpoint at `GET /healthz`7- health endpoint at `GET /healthz`
8- MCP tool routing via `@executor-v2/mcp-gateway`8- MCP tool routing via `@executor-v2/mcp-gateway`
9- `executor.execute` wired to engine runtime adapters (`local-inproc` default, `deno-subprocess` optional)9- local runtime adapter injection (`makeLocalInProcessRuntimeAdapter()` in entry wiring)
10
11App wiring is now split by responsibility:
12- `src/config.ts`: Effect config service (`PORT`)
13- `src/run-executor.ts`: run execution service for an injected runtime adapter
14- `src/mcp-handler.ts`: MCP transport wiring to run client
15- `src/http-server.ts`: Bun server startup
16- `src/main.ts`: Layer composition + process entrypoint
v2/apps/pm/package.json+1−0
@@ -10,6 +10,7 @@ · 9 unmodified lines
10 "dependencies": {10 "dependencies": {
11 "@executor-v2/engine": "workspace:*",11 "@executor-v2/engine": "workspace:*",
12 "@executor-v2/mcp-gateway": "workspace:*",12 "@executor-v2/mcp-gateway": "workspace:*",
13 "@executor-v2/sdk": "workspace:*",
13 "effect": "catalog:"14 "effect": "catalog:"
14 }15 }
15}16}
v2/apps/pm/src/config.ts+26−0
@@ -0,0 +1,26 @@
1import * as Config from "effect/Config";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5
6export type PmConfigService = {
7 port: number;
8};
9
10export class PmConfig extends Context.Tag("@executor-v2/app-pm/PmConfig")<
11 PmConfig,
12 PmConfigService
13>() {}
14
15export const PmConfigLive = Layer.effect(
16 PmConfig,
17 Effect.gen(function* () {
18 const port = yield* Config.integer("PORT").pipe(
19 Config.orElse(() => Config.succeed(8787)),
20 );
21
22 return PmConfig.of({
23 port,
24 });
25 }),
26);
v2/apps/pm/src/http-server.ts+32−0
@@ -0,0 +1,32 @@
1import * as Effect from "effect/Effect";
2
3import { PmConfig } from "./config";
4import { PmMcpHandler } from "./mcp-handler";
5
6export const startPmHttpServer = Effect.fn("@executor-v2/app-pm/http.start")(function* () {
7 const { port } = yield* PmConfig;
8 const { handleMcp } = yield* PmMcpHandler;
9
10 const server = Bun.serve({
11 port,
12 routes: {
13 "/healthz": {
14 GET: () => Response.json({ ok: true, service: "pm" }, { status: 200 }),
15 },
16 "/mcp": {
17 GET: handleMcp,
18 POST: handleMcp,
19 DELETE: handleMcp,
20 },
21 "/v1/mcp": {
22 GET: handleMcp,
23 POST: handleMcp,
24 DELETE: handleMcp,
25 },
26 },
27 });
28
29 yield* Effect.logInfo(`executor-v2 PM listening on http://127.0.0.1:${server.port}`);
30
31 return server;
32});
v2/apps/pm/src/main.ts+21−91
@@ -1,97 +1,27 @@
1import {1import { makeLocalInProcessRuntimeAdapter } from "@executor-v2/engine";
2 makeCloudflareWorkerLoaderRuntimeAdapter,
3 makeDenoSubprocessRuntimeAdapter,
4 makeLocalInProcessRuntimeAdapter,
5 makeRuntimeAdapterRegistry,
6 makeToolProviderRegistry,
7 ToolProviderRegistryService,
8} from "@executor-v2/engine";
9import {
10 handleMcpHttpRequest,
11 type ExecuteToolInput,
12 type ExecuteToolResult,
13} from "@executor-v2/mcp-gateway";
14import * as Effect from "effect/Effect";
15import * as Either from "effect/Either";
16
17const port = Number(Bun.env.PORT ?? 8787);
18
19const runtimeRegistry = makeRuntimeAdapterRegistry([
20 makeLocalInProcessRuntimeAdapter(),
21 makeDenoSubprocessRuntimeAdapter(),
22 makeCloudflareWorkerLoaderRuntimeAdapter(),
23]);
24
25const toolRegistry = makeToolProviderRegistry([]);
26 2
27const errorToText = (error: unknown): string => {3import * as Effect from "effect/Effect";
28 if (error instanceof Error) {4import * as Layer from "effect/Layer";
29 return error.message;
30 }
31
32 if (
33 typeof error === "object" &&
34 error !== null &&
35 "message" in error &&
36 typeof error.message === "string"
37 ) {
38 return error.message;
39 }
40
41 return String(error);
42};
43
44const executeTool = async (input: ExecuteToolInput): Promise<ExecuteToolResult> => {
45 const result = await Effect.runPromise(
46 Effect.either(
47 runtimeRegistry
48 .execute({
49 runtimeKind: input.runtimeKind ?? "local-inproc",
50 code: input.code,
51 tools: [],
52 })
53 .pipe(Effect.provideService(ToolProviderRegistryService, toolRegistry)),
54 ),
55 );
56 5
57 if (Either.isLeft(result)) {6import { PmConfigLive } from "./config";
58 return {7import { startPmHttpServer } from "./http-server";
59 isError: true,8import { PmMcpHandlerLive } from "./mcp-handler";
60 error: errorToText(result.left),9import {
61 };10 PmRunExecutorLive,
62 }11 PmToolProviderRegistryLive,
12} from "./run-executor";
63 13
64 return {14const runtimeAdapter = makeLocalInProcessRuntimeAdapter();
65 isError: false,15const PmMcpDependenciesLive = Layer.merge(
66 output: result.right,16 PmRunExecutorLive(runtimeAdapter),
67 };17 PmToolProviderRegistryLive,
68};18);
69 19
70const handleMcp = async (request: Request): Promise<Response> =>20const PmAppLive = Layer.merge(
71 handleMcpHttpRequest(request, {21 PmConfigLive,
72 target: "local",22 PmMcpHandlerLive.pipe(Layer.provide(PmMcpDependenciesLive)),
73 serverName: "executor-v2-pm",23);
74 serverVersion: "0.0.0",
75 execute: executeTool,
76 });
77 24
78const server = Bun.serve({25const program = startPmHttpServer().pipe(Effect.provide(PmAppLive));
79 port,
80 routes: {
81 "/healthz": {
82 GET: () => Response.json({ ok: true, service: "pm" }, { status: 200 }),
83 },
84 "/mcp": {
85 GET: handleMcp,
86 POST: handleMcp,
87 DELETE: handleMcp,
88 },
89 "/v1/mcp": {
90 GET: handleMcp,
91 POST: handleMcp,
92 DELETE: handleMcp,
93 },
94 },
95});
96 26
97console.log(`executor-v2 PM listening on http://127.0.0.1:${server.port}`);27await Effect.runPromise(program);
v2/apps/pm/src/mcp-handler.ts+43−0
@@ -0,0 +1,43 @@
1import { ToolProviderRegistryService } from "@executor-v2/engine";
2import { handleMcpHttpRequest } from "@executor-v2/mcp-gateway";
3import { createExecutorRunClient } from "@executor-v2/sdk";
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Runtime from "effect/Runtime";
8
9import { PmRunExecutor } from "./run-executor";
10
11export type PmMcpHandlerService = {
12 handleMcp: (request: Request) => Promise<Response>;
13};
14
15export class PmMcpHandler extends Context.Tag("@executor-v2/app-pm/PmMcpHandler")<
16 PmMcpHandler,
17 PmMcpHandlerService
18>() {}
19
20export const PmMcpHandlerLive = Layer.effect(
21 PmMcpHandler,
22 Effect.gen(function* () {
23 const runExecutor = yield* PmRunExecutor;
24 const runtime = yield* Effect.runtime<ToolProviderRegistryService>();
25 const runPromise = Runtime.runPromise(runtime);
26
27 const runClient = createExecutorRunClient((input) =>
28 runPromise(runExecutor.executeRun(input)),
29 );
30
31 const handleMcp = (request: Request): Promise<Response> =>
32 handleMcpHttpRequest(request, {
33 target: "local",
34 serverName: "executor-v2-pm",
35 serverVersion: "0.0.0",
36 runClient,
37 });
38
39 return PmMcpHandler.of({
40 handleMcp,
41 });
42 }),
43);
v2/apps/pm/src/run-executor.ts+89−0
@@ -0,0 +1,89 @@
1import {
2 makeToolProviderRegistry,
3 ToolProviderRegistryService,
4 type RuntimeAdapter,
5} from "@executor-v2/engine";
6import type { ExecuteRunInput, ExecuteRunResult } from "@executor-v2/sdk";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10
11export type PmRunExecutorService = {
12 executeRun: (
13 input: ExecuteRunInput,
14 ) => Effect.Effect<ExecuteRunResult, never, ToolProviderRegistryService>;
15};
16
17export class PmRunExecutor extends Context.Tag("@executor-v2/app-pm/PmRunExecutor")<
18 PmRunExecutor,
19 PmRunExecutorService
20>() {}
21
22const errorToText = (error: unknown): string => {
23 if (error instanceof Error) {
24 return error.message;
25 }
26
27 if (
28 typeof error === "object" &&
29 error !== null &&
30 "message" in error &&
31 typeof error.message === "string"
32 ) {
33 return error.message;
34 }
35
36 return String(error);
37};
38
39const makeExecuteRun = (runtimeAdapter: RuntimeAdapter) =>
40 Effect.fn("@executor-v2/app-pm/run-executor.executeRun")(function* (
41 input: ExecuteRunInput,
42 ) {
43 const runId = `run_${crypto.randomUUID()}`;
44
45 const isAvailable = yield* runtimeAdapter.isAvailable();
46 if (!isAvailable) {
47 return {
48 runId,
49 status: "failed",
50 error: `Runtime '${runtimeAdapter.kind}' is not available in this PM process.`,
51 } satisfies ExecuteRunResult;
52 }
53
54 return yield* runtimeAdapter
55 .execute({
56 code: input.code,
57 timeoutMs: input.timeoutMs,
58 tools: [],
59 })
60 .pipe(
61 Effect.map(
62 (result): ExecuteRunResult => ({
63 runId,
64 status: "completed",
65 result,
66 }),
67 ),
68 Effect.catchAll((error) =>
69 Effect.succeed({
70 runId,
71 status: "failed",
72 error: errorToText(error),
73 } satisfies ExecuteRunResult),
74 ),
75 );
76 });
77
78export const PmRunExecutorLive = (runtimeAdapter: RuntimeAdapter) =>
79 Layer.succeed(
80 PmRunExecutor,
81 PmRunExecutor.of({
82 executeRun: makeExecuteRun(runtimeAdapter),
83 }),
84 );
85
86export const PmToolProviderRegistryLive = Layer.succeed(
87 ToolProviderRegistryService,
88 makeToolProviderRegistry([]),
89);
v2/bun.lock+7−0
@@ -19,6 +19,7 @@ · 18 unmodified lines
19 "dependencies": {19 "dependencies": {
20 "@executor-v2/mcp-gateway": "workspace:*",20 "@executor-v2/mcp-gateway": "workspace:*",
21 "@executor-v2/persistence-convex": "workspace:*",21 "@executor-v2/persistence-convex": "workspace:*",
22 "@executor-v2/sdk": "workspace:*",
22 "convex": "catalog:",23 "convex": "catalog:",
23 },24 },
24 },25 },
@@ -27,6 +28,7 @@ · 2 unmodified lines
27 "dependencies": {28 "dependencies": {
28 "@executor-v2/engine": "workspace:*",29 "@executor-v2/engine": "workspace:*",
29 "@executor-v2/mcp-gateway": "workspace:*",30 "@executor-v2/mcp-gateway": "workspace:*",
31 "@executor-v2/sdk": "workspace:*",
30 "effect": "catalog:",32 "effect": "catalog:",
31 },33 },
32 },34 },
@@ -35,6 +37,10 @@ · 2 unmodified lines
35 },37 },
36 "packages/ai-sdk-adapter": {38 "packages/ai-sdk-adapter": {
37 "name": "@executor-v2/ai-sdk-adapter",39 "name": "@executor-v2/ai-sdk-adapter",
40 "dependencies": {
41 "@executor-v2/sdk": "workspace:*",
42 "zod": "^4.3.6",
43 },
38 },44 },
39 "packages/approvals": {45 "packages/approvals": {
40 "name": "@executor-v2/approvals",46 "name": "@executor-v2/approvals",
@@ -76,6 +82,7 @@ · 35 unmodified lines
76 "packages/mcp-gateway": {82 "packages/mcp-gateway": {
77 "name": "@executor-v2/mcp-gateway",83 "name": "@executor-v2/mcp-gateway",
78 "dependencies": {84 "dependencies": {
85 "@executor-v2/sdk": "workspace:*",
79 "@modelcontextprotocol/sdk": "^1.26.0",86 "@modelcontextprotocol/sdk": "^1.26.0",
80 "zod": "^4.3.6",87 "zod": "^4.3.6",
81 },88 },
v2/packages/ai-sdk-adapter/package.json+7−0
@@ -2,7 +2,14 @@ · 1 unmodified line
2 "name": "@executor-v2/ai-sdk-adapter",2 "name": "@executor-v2/ai-sdk-adapter",
3 "private": true,3 "private": true,
4 "type": "module",4 "type": "module",
5 "exports": {
6 ".": "./src/index.ts"
7 },
5 "scripts": {8 "scripts": {
6 "typecheck": "bunx tsc --noEmit -p tsconfig.json"9 "typecheck": "bunx tsc --noEmit -p tsconfig.json"
10 },
11 "dependencies": {
12 "@executor-v2/sdk": "workspace:*",
13 "zod": "^4.3.6"
7 }14 }
8}15}
v2/packages/ai-sdk-adapter/src/index.ts+51−1
@@ -1 +1,51 @@
1export {};1import type {
2 ExecuteRunInput,
3 ExecuteRunResult,
4 ExecutorRunClient,
5} from "@executor-v2/sdk";
6import { z } from "zod";
7
8export const ExecuteToolInputSchema = z.object({
9 code: z.string(),
10 timeoutMs: z.number().int().positive().optional(),
11});
12
13export type ExecuteToolInput = z.infer<typeof ExecuteToolInputSchema>;
14
15export type ExecuteToolOutput = ExecuteRunResult;
16
17export type AiToolFactory<TTool, TInput, TOutput> = (definition: {
18 description: string;
19 inputSchema: z.ZodType<TInput>;
20 execute: (input: TInput) => Promise<TOutput>;
21}) => TTool;
22
23export type ToAiSdkToolsOptions<TTool> = {
24 runClient: ExecutorRunClient;
25 makeTool: AiToolFactory<TTool, ExecuteToolInput, ExecuteToolOutput>;
26 defaults?: {
27 timeoutMs?: number;
28 };
29};
30const withDefaults = (
31 input: ExecuteToolInput,
32 defaults?: {
33 timeoutMs?: number;
34 },
35): ExecuteRunInput => ({
36 code: input.code,
37 timeoutMs: input.timeoutMs ?? defaults?.timeoutMs,
38});
39
40export const toAiSdkTools = <TTool>(
41 options: ToAiSdkToolsOptions<TTool>,
42): {
43 execute: TTool;
44} => ({
45 execute: options.makeTool({
46 description: "Execute JavaScript against configured Executor runtime",
47 inputSchema: ExecuteToolInputSchema,
48 execute: async (input) =>
49 options.runClient.execute(withDefaults(input, options.defaults)),
50 }),
51});
v2/packages/mcp-gateway/package.json+1−0
@@ -9,6 +9,7 @@ · 8 unmodified lines
9 "typecheck": "bunx tsc --noEmit -p tsconfig.json"9 "typecheck": "bunx tsc --noEmit -p tsconfig.json"
10 },10 },
11 "dependencies": {11 "dependencies": {
12 "@executor-v2/sdk": "workspace:*",
12 "@modelcontextprotocol/sdk": "^1.26.0",13 "@modelcontextprotocol/sdk": "^1.26.0",
13 "zod": "^4.3.6"14 "zod": "^4.3.6"
14 }15 }
v2/packages/mcp-gateway/src/index.ts+0−1
@@ -2,7 +2,6 @@ export { · 1 unmodified line
2 handleMcpHttpRequest,2 handleMcpHttpRequest,
3 type ExecuteToolInput,3 type ExecuteToolInput,
4 type ExecuteToolResult,4 type ExecuteToolResult,
5 type GatewayRuntimeKind,
6 type GatewayTarget,5 type GatewayTarget,
7 type McpGatewayOptions,6 type McpGatewayOptions,
8} from "./server";7} from "./server";
v2/packages/mcp-gateway/src/server.ts+28−24
@@ -1,17 +1,13 @@
1import type { ExecuteRunResult, ExecutorRunClient } from "@executor-v2/sdk";
1import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";2import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";3import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
3import { z } from "zod";4import { z } from "zod";
4 5
5export type GatewayTarget = "local" | "remote";6export type GatewayTarget = "local" | "remote";
6 7
7export type GatewayRuntimeKind =
8 | "local-inproc"
9 | "deno-subprocess"
10 | "cloudflare-worker-loader";
11
12export type ExecuteToolInput = {8export type ExecuteToolInput = {
13 code: string;9 code: string;
14 runtimeKind?: GatewayRuntimeKind;10 timeoutMs?: number;
15};11};
16 12
17export type ExecuteToolResult = {13export type ExecuteToolResult = {
@@ -20,11 +16,27 @@ export type ExecuteToolResult = { · 2 unmodified lines
20 isError: boolean;16 isError: boolean;
21};17};
22 18
19const toGatewayExecuteResult = (
20 result: ExecuteRunResult,
21): ExecuteToolResult => {
22 if (result.status === "completed") {
23 return {
24 isError: false,
25 output: result.result,
26 };
27 }
28
29 return {
30 isError: true,
31 error: result.error ?? `Run ${result.runId} ended with status ${result.status}`,
32 };
33};
34
23export type McpGatewayOptions = {35export type McpGatewayOptions = {
24 target: GatewayTarget;36 target: GatewayTarget;
25 serverName?: string;37 serverName?: string;
26 serverVersion?: string;38 serverVersion?: string;
27 execute?: (input: ExecuteToolInput) => Promise<ExecuteToolResult>;39 runClient: ExecutorRunClient;
28};40};
29 41
30const DEFAULT_SERVER_NAME = "executor-v2";42const DEFAULT_SERVER_NAME = "executor-v2";
@@ -38,9 +50,7 @@ const PingToolInput = z.object({ · 7 unmodified lines
38 50
39const ExecuteToolInputSchema = z.object({51const ExecuteToolInputSchema = z.object({
40 code: z.string(),52 code: z.string(),
41 runtimeKind: z53 timeoutMs: z.number().int().positive().optional(),
42 .enum(["local-inproc", "deno-subprocess", "cloudflare-worker-loader"])
43 .optional(),
44});54});
45 55
46const contentText = (value: unknown): string => {56const contentText = (value: unknown): string => {
@@ -87,24 +97,18 @@ const createStubMcpServer = (options: McpGatewayOptions): McpServer => { · 40 unmodified lines
87 mcp.registerTool(97 mcp.registerTool(
88 EXECUTE_TOOL_NAME,98 EXECUTE_TOOL_NAME,
89 {99 {
90 description: "Execute JavaScript against configured runtime adapter",100 description: "Execute JavaScript against configured runtime",
91 inputSchema: ExecuteToolInputSchema,101 inputSchema: ExecuteToolInputSchema,
92 },102 },
93 async (input: ExecuteToolInput) => {103 async (input: ExecuteToolInput) => {
94 if (!options.execute) {
95 return {
96 content: [
97 {
98 type: "text" as const,
99 text: "executor.execute is not configured for this gateway target",
100 },
101 ],
102 isError: true,
103 };
104 }
105
106 try {104 try {
107 const result = await options.execute(input);105 const result = toGatewayExecuteResult(
106 await options.runClient.execute({
107 code: input.code,
108 timeoutMs: input.timeoutMs,
109 }),
110 );
111
108 return {112 return {
109 content: [113 content: [
110 {114 {
v2/packages/sdk/package.json+3−0
@@ -2,6 +2,9 @@ · 1 unmodified line
2 "name": "@executor-v2/sdk",2 "name": "@executor-v2/sdk",
3 "private": true,3 "private": true,
4 "type": "module",4 "type": "module",
5 "exports": {
6 ".": "./src/index.ts"
7 },
5 "scripts": {8 "scripts": {
6 "typecheck": "bunx tsc --noEmit -p tsconfig.json"9 "typecheck": "bunx tsc --noEmit -p tsconfig.json"
7 }10 }
v2/packages/sdk/src/index.ts+70−1
@@ -1 +1,70 @@
1export {};1export type RunTerminalStatus =
2 | "completed"
3 | "failed"
4 | "timed_out"
5 | "denied";
6
7export type ExecuteRunInput = {
8 code: string;
9 timeoutMs?: number;
10};
11
12export type ExecuteRunResult = {
13 runId: string;
14 status: RunTerminalStatus;
15 result?: unknown;
16 error?: string;
17 exitCode?: number;
18 durationMs?: number;
19};
20
21export interface ExecutorRunClient {
22 execute(input: ExecuteRunInput): Promise<ExecuteRunResult>;
23}
24
25export type RuntimeToolCallRequest = {
26 runId: string;
27 callId: string;
28 toolPath: string;
29 input?: Record<string, unknown>;
30};
31
32export type RuntimeToolCallResult =
33 | {
34 ok: true;
35 value: unknown;
36 }
37 | {
38 ok: false;
39 kind: "pending";
40 approvalId: string;
41 retryAfterMs: number;
42 error?: string;
43 }
44 | {
45 ok: false;
46 kind: "denied";
47 error: string;
48 }
49 | {
50 ok: false;
51 kind: "failed";
52 error: string;
53 };
54
55export interface RuntimeToolCallHandler {
56 handleToolCall(input: RuntimeToolCallRequest): Promise<RuntimeToolCallResult>;
57}
58
59export type ExecutorServer = {
60 runClient: ExecutorRunClient;
61 toolCallHandler: RuntimeToolCallHandler;
62};
63
64export const createExecutorRunClient = (
65 execute: ExecutorRunClient["execute"],
66): ExecutorRunClient => ({
67 execute,
68});
69
70

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t