---
title: "Capability-Passing Script Host — Named Parameters, Boxed Units and Scope Combinators"
description: "Capability-Passing Script Host — Named Parameters, Boxed Units and Scope Combinators DROPCUT Studio's users write machining jobs in JavaScript. That choice makes the tool expressive, and it means us…"
doc_version: 1
last_updated: 2026-11-10
canonical_url: "http://parc.yolo.scapegoat.dev/note/research/software-architecture-garden/dropcut-studio/claude-opus/07-capability-passing-script-host-named-parameters-boxed-units-and-scope-combinators"
---

# Capability-Passing Script Host — Named Parameters, Boxed Units and Scope Combinators

Capability-Passing Script Host — Named Parameters, Boxed Units and Scope Combinators DROPCUT Studio's users write machining jobs in JavaScript. That choice makes the tool expressive, and it means us…

## Tags

- `architecture-garden`
- `dropcut-studio`
- `dsl`
- `scripting`
- `sandbox`
- `capabilities`
- `units`

## Content

# Capability-Passing Script Host — Named Parameters, Boxed Units and Scope Combinators

DROPCUT Studio's users write machining jobs in JavaScript. That choice makes the tool expressive, and it means user code runs inside the application. This chapter explains how the script host limits what a script can reach, why scripts produce a declarative plan rather than machine motion, how units are enforced in code that is never type-checked, and how scope combinators make unbalanced state changes inexpressible. It also records, with a demonstration, what the host does not protect against — a limit the module documents honestly.

> [!summary]
> - The script is compiled with `new Function(...)`, with the **capability API bound as named parameters** and denied globals shadowed as `undefined` parameters, in strict mode.
> - The API is built **fresh per run** in a closure; a script's only output is a serialisable `ManufacturingPlan` plus diagnostics, harvested after it returns.
> - Units are **boxed at runtime** (`{ __unit, v }`). A wrong unit throws; a bare number works and warns.
> - `withTool` and `withSpindle` are **scope combinators** with `try/finally`; spindle start and stop commands are inserted by the planner, not by the script.
> - Errors are mapped back to the user's line with a **measured** line offset.
> - The module states that shadowing is defence in depth, not a sandbox. `(() => {}).constructor("return globalThis")()` reaches `process` in the CLI. Worker isolation and `timeoutMs` are declared but not built.

## 1. What a machining script is allowed to do

A useful way to design a script host is to start from the output and ask what the script needs to produce it. A machining script needs to declare tools, set up stock, place a mesh, and request operations with parameters. It does not need the DOM, the network, storage, timers or the filesystem. The host's design follows from making exactly the first list available and nothing else.

The threat model in `packages/script-host/src/sandbox.ts` is broader than malice: *a script is untrusted even when the user trusts themselves, because scripts get shared, pasted from forums, and generated by LLMs.* The prototype ran `new Function(code)` on the main thread with full ambient authority. The rewrite narrows that authority and is explicit about how far.

## 2. Capability passing by named parameters

A **capability** in this sense is a reference that grants the authority to perform an operation. **Capability passing** means code receives exactly the references it may use, instead of finding them in ambient global scope.

`runScript` builds the API object and compiles the user's source with each API member as a named parameter:

```ts
const { api, harvest } = createScriptApi({ meshNames: opts.meshNames });
const names = Object.keys(api);            // job, tools, strategy, entry, geometry, mm, rpm, ...
const values = Object.values(api);
const shadowed = DENIED_GLOBALS.filter((n) => !names.includes(n));

compiled = new Function(
  ...names,
  ...shadowed,
  `"use strict";\n${source}\n//# sourceURL=${SCRIPT_FILENAME}`,
);
compiled(...values, ...shadowed.map(() => undefined));
```

The denied globals — `fetch`, `XMLHttpRequest`, `WebSocket`, `indexedDB`, `localStorage`, `postMessage`, `require`, `process`, `globalThis` and others — become parameters bound to `undefined`. Inside the function body, a parameter shadows the global of the same name, so `fetch(...)` fails with a `TypeError` instead of making a request. This works where `delete globalThis.fetch` would not, because some globals are non-configurable. Strict mode makes `this` inside the body `undefined` rather than the global object.

### 2.1 What shadowing does not do

Shadowing removes *names*. It does not remove *reachability*. Every function value in JavaScript has a `constructor` property that is the `Function` constructor, and functions created by it run in sloppy mode at global scope. A probe script compiled through the CLI at the analysed commit shows both halves:

```js
const direct = typeof process + "/" + typeof fetch + "/" + typeof globalThis;
const g = (() => {}).constructor("return globalThis")();
throw new Error(`direct=${direct} viaConstructor=${typeof g.process}/${typeof g.fetch}`);
```

```text
compile failed at the script stage:
  ERROR script.error: direct=undefined/undefined/undefined viaConstructor=object/function (line 5)
```

The direct names are gone; the global object is one expression away. The module comment says exactly this: *deleting globals is defence in depth, not a security boundary … Real isolation needs a null-origin iframe or a JS-in-JS interpreter.* Shadowing still has value. It makes accidental use of ambient APIs fail loudly, and it documents the intended surface.

The other unbuilt half is resource control. `RunOptions.timeoutMs` exists with the comment *enforced by the caller in a worker context*, but no worker exists yet and no caller reads it. The README lists it: *a runaway script has no watchdog.* A `while (true) {}` in the editor blocks the tab until the browser intervenes.

The correct isolation boundary for this design is a dedicated worker per compile, terminated on timeout, possibly hosting a JS-in-JS interpreter (QuickJS compiled to WebAssembly) for scripts from untrusted sources. The capability API carries over unchanged, because it already returns plain data.

## 3. The script's output is a plan, not motion

The API does not let a script emit a G-code word, a traverse or a cut. Every `job.*` call appends a declarative `Operation` to a closure-local list:

```ts
job.rectPocket({ x: mm(19), y: mm(15), w: mm(32), h: mm(20),
                 depth: mm(6), stepdown: mm(2), stepover: 0.45,
                 feed: mmPerMin(600), plungeFeed: mmPerMin(200) });
// appends { kind: "pocket", id: "pocket#1", toolId: "T1", feed, area, depth, stepdown, ... }
```

After the script returns, `harvest()` produces a `ManufacturingPlan { setup, operations, tools }`. The planner types document why the plan is declarative and serialisable: *that is what lets the plan cross a postMessage boundary from the script sandbox, and what makes it the natural save format.*

This separation has three effects beyond isolation.

1. **The script cannot bypass the planner's safety logic.** Linking, entry selection, retract heights and spindle interlocks are decided downstream from the plan (see [[Research/Software Architecture Garden/dropcut-studio/claude-opus/08 - Strategies Produce Geometry, the Planner Owns the Gaps|chapter 08]]).
2. **Scripts are cheap to run.** A script runs in milliseconds; the expensive geometry happens after it returns, in code the host controls.
3. **State is per run.** `createScriptApi` keeps all mutable state — tools, operations, diagnostics, the active tool and spindle speed — in its closure. Two concurrent runs cannot observe each other.

A small detail in `runScript` shows how carefully the boundary is handled. The host exposes `meshName` as a getter, and the code deliberately does not destructure it:

```ts
// NOT destructured: `meshName` is a getter, and spreading would evaluate it
// now — before the script has had a chance to set it.
const host = createScriptApi({ meshNames: opts.meshNames });
```

## 4. Units enforced at runtime

The core packages use TypeScript brands (`Mm`, `Rpm`, `MmPerMin`) that erase to `number` at runtime. That protects the compiler's own code and gives no protection to a user script, which is never type-checked. The script API therefore boxes units as values:

```ts
const units = {
  mm:       (v: number) => box("mm", v),
  inch:     (v: number) => box("mm", v * 25.4),   // normalised at construction
  rpm:      (v: number) => box("rpm", v),
  mmPerMin: (v: number) => box("mm/min", v),
  deg:      (v: number) => box("deg", v),
};
```

Every API parameter goes through `unwrap(value, unit, context)`, which implements a deliberately asymmetric policy:

| Argument | Result | Reason |
|---|---|---|
| `mm(6)` where mm is expected | accepted | correct |
| `rpm(6)` where mm is expected | **`TypeError: tools.flatEndMill diameter: expected mm, got rpm`** | a wrong unit is never a typo the user meant |
| `6` where mm is expected | accepted with `units.bareNumber` **warning** | a first-time user should get a working program and a yellow note, not a red wall |
| `NaN`, `Infinity`, `"6"`, missing | `TypeError` | not a quantity |

The asymmetry is the point. Rejecting bare numbers would make the DSL hostile to newcomers; accepting wrong units would make it dangerous. `inch()` converts to millimetres at construction, so no code downstream of the boundary ever asks which unit a length is in — the same rule the core `@cam/units` package follows.

## 5. Scope combinators

A **scope combinator** is a function that takes a configuration and a body, establishes a state for the duration of the body, and restores the previous state afterwards — even if the body throws.

```ts
withTool(tool: Tool, body: () => void) {
  const previous = activeToolId;
  job.toolChange(tool);
  try { body(); } finally { activeToolId = previous; }
},

withSpindle(o: { speed: RpmArg }, body: () => void) {
  const previous = activeSpindle;
  activeSpindle = toRpm(unwrap(o?.speed, "rpm", "withSpindle speed"));
  try { body(); } finally { activeSpindle = previous; }
},
```

Operations declared inside the body capture the active tool id and spindle speed. Because a scope is a lexical block, there is no way to write "start the spindle" without a matching end; nesting is checked by the language's own block structure.

The README's phrasing — *you cannot forget the `M5`* — is accurate in outcome but slightly misattributes the mechanism. `withSpindle` emits no spindle commands at all; it scopes a speed. The commands are inserted by `runPlan` in `packages/planner/src/run.ts`: it stops the spindle before every tool change, starts it before each operation if it is not running, and appends a final spindle-off if the program ends with it running. `validate()` independently errors on a tool change with the spindle running. The guarantee comes from the planner owning spindle state and the scope combinator owning only the *parameter*. That is a better design than a combinator that emits `M3`/`M5` itself, because the planner can then merge adjacent operations under one spindle start.

### 5.1 Relation to the Kleisli design note

`original/DESIGN-02-kleisli-composition-for-machine-commands.md` develops a monadic reading of the DSL: each command is an arrow $\Sigma \rightsquigarrow \Sigma$ carrying machine state, failure and a trace, and Kleisli composition gives the associativity law $(P;Q);R = P;(Q;R)$ that lets programs be regrouped. The implementation encodes the same structure without a monadic API:

| Effect in the design note | Encoding in `createScriptApi` |
|---|---|
| State $\Sigma$ (active tool, spindle, setup) | variables in the closure |
| Writer (trace, warnings) | the `operations` and `diagnostics` arrays |
| Failure | exceptions, caught once at the `runScript` boundary and turned into a `script.error` diagnostic |
| Scoped state | `try/finally` combinators |

Associativity holds because a script is sequential JavaScript and the closure is the only state. The encoding trades the explicitness of a monadic interface for a surface a CNC user can read without knowing what a monad is.

## 6. Mapping errors back to the user's line

A runtime error inside `new Function` reports a line in the generated function, not in the user's text. The host compiles with `//# sourceURL=program.cam.js` so the user's frames are identifiable in a stack trace, then subtracts the wrapper's line offset.

The offset is an engine detail — V8 reports user line 1 as line 3 — and a wrong constant would misreport *every* error. So it is measured once at module load by compiling a one-line script that throws and reading back the reported line:

```ts
const REPORTED_TO_USER_LINE = measureLineOffset();
// compile `throw new Error("probe")` with the same wrapper; offset = reported − 1
```

The probe in §2.1 was reported at `(line 5)`, which is the user's line 5. When no frame matches, `locateInScript` returns `undefined` and the diagnostic has no location — *much better than confidently reporting the wrong line.*

## 7. Why tempting alternatives are wrong

**Expose a G-code-emitting API.** It would give the script authority over motion and bypass linking, entry and interlock logic. It would also make the plan non-serialisable and the save format G-code.

**Rely on TypeScript for units.** Scripts are not compiled by `tsc`. Runtime boxing is the only enforcement available at that boundary.

**Paired `spindleOn()` / `spindleOff()` calls.** Every pairing API eventually meets a script that forgets the second call, or throws between them. Lexical scope makes the pairing structural.

**Call it a sandbox.** Presenting name shadowing as isolation would invite users to run untrusted scripts. The module's explicit "what it does not do" section is the correct practice and worth copying.

## 8. Applicability

The pattern fits any embedded DSL whose job is to *describe* work for a host to perform: build configurations, infrastructure declarations, report definitions, UI layout scripts, test scenario builders. The common shape is: capability object in, declarative plan out, host performs the effects. The go-go-goja ecosystem's native modules are a natural comparison target — they expose Go capabilities to a JavaScript runtime and face the same questions of ambient authority, unit checking and error mapping.

It is insufficient on its own when scripts come from parties the user does not control. Then process- or worker-level isolation with a timeout is required, and the capability API should be the *only* object crossing that boundary.

## 9. Candidate ecosystem guidance

1. Give scripts a capability object as their only interface; build it fresh per run and keep all mutable state in its closure.
2. Make the script's output a serialisable declarative plan; let the host own every effect.
3. Shadow ambient globals for fail-loud ergonomics, and document that this is not isolation.
4. Enforce units at runtime in untyped scripts: reject wrong units, warn on bare numbers, normalise alternate units at construction.
5. Prefer scope combinators to paired start/stop calls; keep the actual state transitions in the host.
6. Measure engine-dependent offsets at load time instead of hard-coding them, and omit a location rather than guess one.
7. Do not declare options such as `timeoutMs` until something enforces them.

## 10. Open questions

- Which isolation target fits the browser build best: a module worker per compile, a null-origin iframe, or QuickJS-in-WebAssembly inside a worker?
- Should the plan be validated against a schema when it crosses the worker boundary, so a compromised script cannot hand back a malformed plan?
- Should `withSpindle` capture direction as well as speed, given that `runPlan` currently hard-codes `"cw"` and defaults to 12,000 rpm when no speed is scoped?

## 11. Evidence and references

- `packages/script-host/src/sandbox.ts:40` (`DENIED_GLOBALS`), `:72` (`runScript`), `:155` (`locateInScript`), `:181` (`measureLineOffset`); `RunOptions.timeoutMs` (unused).
- `packages/script-host/src/api.ts` — `createScriptApi`, `unwrap`, `withTool`, `withSpindle`, boxed `units`.
- `packages/planner/src/run.ts:55` — spindle start/stop and tool-change interlock in `runPlan`; default `rpm(12000)` and `mode: "cw"` at line 95.
- `packages/planner/src/types.ts` — declarative, serialisable `ManufacturingPlan`.
- `original/DESIGN-02-kleisli-composition-for-machine-commands.md` §15 — monadic reading of the DSL.
- Probe compile at `f3ebac2`, recorded in §2.1.
- `grep -rn "timeoutMs\|Worker"` over `packages apps` at `f3ebac2`: declaration only.

## Wiki Links

- Research/Software Architecture Garden/dropcut-studio/claude-opus/08 - Strategies Produce Geometry, the Planner Owns the Gaps
- Research/Software Architecture Garden/go-go-goja/README
- Research/Software Architecture Garden/dropcut-studio/claude-opus/08 - Strategies Produce Geometry, the Planner Owns the Gaps

## Backlinks

- [research/software-architecture-garden/dropcut-studio/claude-opus/readme](http://parc.yolo.scapegoat.dev/note/research/software-architecture-garden/dropcut-studio/claude-opus/readme)
- [research/software-architecture-garden/dropcut-studio/claude-opus/11-candidate-ecosystem-guidelines](http://parc.yolo.scapegoat.dev/note/research/software-architecture-garden/dropcut-studio/claude-opus/11-candidate-ecosystem-guidelines)

## Sitemap

- [Home](http://parc.yolo.scapegoat.dev/)
- [Home markdown mirror](http://parc.yolo.scapegoat.dev/index.md)
- [Markdown sitemap](http://parc.yolo.scapegoat.dev/sitemap.md)
