@sorbetai/plugins 0.0.0-stage → 0.1.0-alpha.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,1180 @@
1
- # Temporary Holding Version
1
+ # `@sorbetai/plugins`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This package is Sorbet's Plugin author SDK, Live Composition runtime and model consumer. Authors export or pass one `apply(ctx, config)` function and register only the capabilities they use. Addressable objects, Tools, Services, Context and Session behavior share the same Composition owner. The complete SDK below runs in trusted execution; [isolated processes](./EXECUTION.md#isolated-process-execution) support its serializable async subset and are the ACP CLI default.
4
+
5
+ The Host supplies stable Entry keys and configuration. Durable Authority records accepted intent and package authorization. Live Composition owns the current Effect Scope tree, Service resolution and resources. Each model request captures callbacks and borrows their owners. These are independent lifetimes: accepting Desired neither certifies resource health nor installs model declarations. [The architecture contract](./COMPOSITION.md) defines their interaction.
6
+
7
+ | Author capability | Registration | Request behavior |
8
+ | -------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
9
+ | Tool | `ctx.tools.register(tool)` | Exact leased Tool binding |
10
+ | Tool hooks | `ctx.tools.hook({ key, prepare?, feedback?, version?, before?, after? })` | Prepared input and result processing |
11
+ | Fixed Context | `ctx.context.prefix(key, content)` | Immutable Prefix definition |
12
+ | Named state | `ctx.context.state({ key?, stateName, schema, read })` | Request-bound state reader |
13
+ | Context preparation | `ctx.context.around(key, callback)` | Native Context continuation |
14
+ | History selection | `ctx.context.selectHistory(key, selector)` | Composable ordered-subset selection |
15
+ | Input transformation | `ctx.input.transform(key, callback)` | Admitted input transformation |
16
+ | Session behavior | `ctx.session.behavior(behavior)` | Journal-backed state, constraints and decisions |
17
+ | Run yield | `ctx.runYield.register(key, hook)` | Decides same-Run continuation after a committed answer; trusted programmatic registration only. |
18
+ | Session access | `ctx.session.bind(id)`, `discover()`, `create(input)` | Host-granted resource capabilities |
19
+ | Request prefix | `scope.request.current()` | Session-owned reconstruction of the last dispatched request plus the messages committed after it |
20
+ | Model call | `scope.model.complete({ purpose, context? })` | Provider evidence and usage. Returned Tool calls stay response data. |
21
+ | Model fork | `scope.model.fork?.({ purpose, responseMessageId, prompt })` | Continue from a committed answer with the source request's context and dispatch settings. |
22
+ | Session work | `scope.work.spawn(task)` | Cancellable, nonfatal work owned by Session and generation |
23
+ | Critical resource | `await ctx.acquire(open, close)` | Activation-owned readiness and cleanup |
24
+ | Native resource | `Effect.acquireRelease(open, close)` inside `apply` | The same Activation Scope owns cleanup |
25
+ | Service | `ctx.provide(Service, value)` and `{ requires, apply }` | Realm lookup and scoped consumer reconstruction |
26
+ | Addressable object | `ctx.objects.serve(type, factory)`, `ctx.objects.acquire(type, key)` | Scoped Host references with captured implementations |
27
+ | Child Plugin | `ctx.mount(key, apply, config)` | Parent-owned Scope and independently updated target |
28
+ | Background work | `ctx.supervise(task)` | Activation-owned task, excluded from readiness |
29
+
30
+ Runtime consumes request contributions through [`@sorbetai/plugins/model`](./src/model.ts). The root entry exports environment-neutral Composition authority, storage and Session capability contracts. The separate [`/node` entry](./src/node.ts) supplies atomic SQLite storage, native ESM and process loaders, Host Tool bindings, and Host directory input. Loaders enforce the Authority's current authorization when admitting managed callbacks. Plugins depends on the independent Context domain; Context and Runtime do not import the author implementation. The [source guide](./src/README.md) maps implementation ownership and dependencies.
31
+
32
+ The [first-version contract](./V1.md) defines supported deployment, execution
33
+ ownership, update/recovery behavior and acceptance boundaries. It distinguishes
34
+ the implemented SDK from the broader Proposed design and later capabilities.
35
+
36
+ ## SDK assembly
37
+
38
+ The Host opens one Platform and configures its complete programmatic target.
39
+ Services and owned resources work independently of a Sorbet Core Session or Journal.
40
+ The optional [Pi](../plugin-pi/README.md) and [DeepSeek](../plugin-deepseek/README.md)
41
+ compatibility packages are migrating to the extension-platform direction: Sorbet
42
+ owns the Run, and upstream plugins enter through capability adapters rather than
43
+ native guest harnesses. Their existing native profiles are legacy and not the
44
+ target architecture. See [ADR-0114](../../docs/adr/0114-sorbet-owns-the-run.md)
45
+ and [ADR-0115](../../docs/adr/0115-capability-extension-abi.md).
46
+
47
+ A Host may also lend the Platform to one or more Sorbet Sessions. Each Session requires a Runtime `permissions`
48
+ composition; Plugin Tools enter the same approval and write-ahead Effect boundary as
49
+ Host Tools. Close all borrowing Sessions before closing the Platform.
50
+
51
+ For automatically owned, private Session Platforms, use NodeAgent's
52
+ [`sessionPluginComposition`](../node-agent/README.md#programmatic-plugins).
53
+
54
+ ```ts
55
+ import { randomUUID } from 'node:crypto';
56
+ import { SorbetSession } from '@sorbetai/durable/pi';
57
+ import { PluginPlatform } from '@sorbetai/plugins';
58
+
59
+ const plugins = await PluginPlatform.open({
60
+ scopeId: 'workspace',
61
+ createId: randomUUID,
62
+ now: Date.now,
63
+ });
64
+ let session: SorbetSession | undefined;
65
+ try {
66
+ await plugins.configure([{ key: 'workspace', apply: applyWorkspace, config: { workspaceRoot } }]);
67
+ session = await SorbetSession.open({ ...sessionOptions, permissions, plugins });
68
+ await (await session.start({ prompt: 'Summarize the workspace manifest.' })).result();
69
+ } finally {
70
+ await session?.close();
71
+ await plugins.close();
72
+ }
73
+ ```
74
+
75
+ Supplying a Platform trusts code in that scope, including future resource changes adopted by
76
+ the Session. `SorbetSessionOptions.pluginToolNames` is an optional model-visible ceiling:
77
+ omission permits every Plugin Tool name, while `[]` permits none. Nonempty unique names
78
+ are copied when the Session opens; later request view or policy changes cannot expand the
79
+ ceiling. Adoption may change the implementation behind a permitted name, but invocation
80
+ still uses the exact leased binding and Runtime permission evidence. See the
81
+ [Runtime Session contract](../runtime/src/session/contracts.ts) and
82
+ [Session lifecycle guide](../runtime/src/session/README.md) for admission, retry and close
83
+ ordering.
84
+
85
+ ### Session capabilities
86
+
87
+ `PluginPlatformOptions.sessions(actor)` supplies a directory for one stable Entry
88
+ and Activation generation. The Host chooses the resource scope and available
89
+ ports. Plugins can discover, create and bind Sessions dynamically, including
90
+ Sessions created after Platform assembly. A Session ID supplies an address;
91
+ the Host's returned capability supplies authority. Missing discovery, creation or
92
+ binding fails without accessing a Session.
93
+
94
+ The actor's stable `entryId` is
95
+ `sorbet:plugin/<escaped scopeId>/<escaped Entry path>`. Each programmatic mount
96
+ path component is URI-escaped separately; an installed Desired Entry uses its
97
+ stable Entry ID as one component. Distinct Platform scopes and literal keys
98
+ containing `/` therefore remain distinct durable record owners.
99
+
100
+ `await ctx.session.bind(sessionId)` returns a
101
+ [`PluginSessionScope`](./src/contributions/session.ts) with a lifetime signal and
102
+ optional facts, records, model, work and control ports. Records belong to the
103
+ stable Entry; the Runtime supplies identity, ordering and commit metadata.
104
+ Consumers continue facts from durable cursors and use record revisions and
105
+ idempotency keys for concurrent or repeated computation. The model port shares
106
+ Runtime request evidence and usage accounting. Control enters the Session's
107
+ existing admission and permission boundaries. Node Hosts can assemble these
108
+ capabilities with `createNodeAgentPluginSessions` from `@sorbetai/node-agent`.
109
+
110
+ Replacement immediately rejects new calls through old directories and scopes.
111
+ Already admitted finite calls retain their existing Composition owner until they
112
+ settle. Following facts and spawned work are cancelled when the generation or
113
+ Session ends; cleanup still waits for actual settlement. Work failures are returned
114
+ as outcomes and leave the Activation available. Work closures are process-local;
115
+ consumers reconstruct them from durable records after restart. The isolate process
116
+ adapter currently exposes no Session directory; trusted in-process capability
117
+ configuration does not replace process isolation.
118
+
119
+ ## Programmatic configuration
120
+
121
+ `configure(entries)` accepts the complete target list. Each Entry is `{ key, apply, config }`; the list can contain heterogeneous configuration types. Configuration is captured as JSON before `apply`. Programmatic authors do not declare a configuration schema. Installed Packages retain their manifest JSON Schema boundary.
122
+
123
+ ```ts
124
+ import { readFile } from 'node:fs/promises';
125
+ import { join } from 'node:path';
126
+ import { PluginPlatform, type PluginApply } from '@sorbetai/plugins';
127
+ import * as s from '@earendil-works/pi-schema';
128
+
129
+ const manifest: PluginApply<{ workspaceRoot: string }> = (ctx, config) => {
130
+ ctx.tools.register({
131
+ name: 'workspace_manifest',
132
+ description: 'Read the trusted workspace package manifest.',
133
+ parameters: s.obj({}),
134
+ execute: async (_input, { signal }) => ({
135
+ content: [
136
+ {
137
+ type: 'text',
138
+ text: await readFile(join(config.workspaceRoot, 'package.json'), {
139
+ encoding: 'utf8',
140
+ signal,
141
+ }),
142
+ },
143
+ ],
144
+ details: {},
145
+ }),
146
+ });
147
+ };
148
+
149
+ await plugins.configure([{ key: 'workspace', apply: manifest, config: { workspaceRoot } }]);
150
+ ```
151
+
152
+ Reuse is determined by the stable Entry key, the original `apply` function reference, captured configuration value, declared required/provided Service keys, realm policy and resolved provider registrations. Rebuilding an equivalent list or changing only order does not restart instances. Changing one function or configuration prepares that instance and its affected Service consumers and children. Removing an Entry retires its owners after their request borrows drain. Reordering changes the next request view without restarting owners.
153
+
154
+ Object definitions may expose `{ apply }`, but the callback still receives only `ctx` and `config`; the container's receiver is not hidden configuration. A zero- or one-argument function may ignore configuration and is installed with `config: null`.
155
+
156
+ Registration methods synchronously capture metadata, schemas, and callback bindings. Duplicate local keys in one instance throw without changing its registrations. Internal identities derive from `(Entry key, domain, local key)`; authors do not construct them. Model-visible Tool and state names still use their domain collision rules.
157
+
158
+ For programmatic Entries and Context Packages, registration remains open after readiness. Each call returns a `PluginRegistration` with an idempotent `dispose()` that withdraws that exact registration. A withdrawn local key may be reused; disposing an old handle cannot remove its replacement. Registration changes notify Live Composition. A synchronous lease read can checkpoint contribution-only changes; while Service or child reconstruction is pending, it reads the preceding stable snapshot. A new lease materializes the latest stable model view. With the default strict policy, invalid combinations such as duplicate Tool names reject new acquisition while existing leases remain usable. Hosts may select Tool-local isolation through the [Composition contract](./COMPOSITION.md#host-bound-client-control); withdrawing a conflict restores those Tools for future requests. Scope cleanup revokes registrations, and post-cancellation registration fails.
159
+
160
+ `apply` may return `Effect.Effect<void, Error, Scope.Scope>`. The Platform runs it in the existing Activation Scope and waits for it before publishing. Use `Effect.acquireRelease` for native resources; no author-owned runtime or second lifetime is needed. Programmatic definitions can declare other required services through the Service contract below; undeclared requirements are rejected by the typed SDK. Synchronous and Promise callbacks continue to use this same owner through `ctx.acquire` and `ctx.supervise`. A returned `PluginRegistration`, including a Promise result, is adopted into the same Scope and disposed with its original receiver. Cleanup adoption also covers handles returned after cancellation; `void` creates no finalizer.
161
+
162
+ ```ts
163
+ import { Effect } from 'effect';
164
+ import type { PluginApply } from '@sorbetai/plugins';
165
+
166
+ const guidance: PluginApply<null> = (ctx) =>
167
+ Effect.sync(() => {
168
+ ctx.context.prefix('guidance', 'Explain findings with evidence.');
169
+ });
170
+ ```
171
+
172
+ ### Child Plugins
173
+
174
+ Programmatic and Context Package authors can call `ctx.mount(key, apply, config)` during initialization
175
+ or later discovery. The key is local to the parent and must be unique among its
176
+ current children. Configuration is captured as lossless JSON. The returned
177
+ `PluginMount<Config>` has synchronous `update(config)`, idempotent `dispose()` and `status()`;
178
+ these change the desired child, not its already captured callbacks. Updating to an
179
+ equal configuration does not restart it. A disposed key can be reused, while the
180
+ old handle cannot update or remove the replacement.
181
+
182
+ Child preparation runs asynchronously in the same Platform command lane as Host
183
+ configuration. `configure` includes the initial subtree. Later changes schedule
184
+ reconciliation automatically; `await plugins.flush()` waits for pending child
185
+ targets and registrations to converge. It does not materialize a model view. Awaiting `ctx.mount()` does
186
+ not wait for readiness. `flush()` does not wait for old request leases to drain,
187
+ and a successful flush does not imply every child is active: inspect
188
+ `handle.status()` for that child's Pending dependencies, conflict, failure, observed Activation or removal. `platform.status().mounts` exposes the same committed observations globally. Returned values are detached; reading or changing them cannot mutate the graph.
189
+
190
+ ```ts
191
+ const parent: PluginApply<null> = (ctx) => {
192
+ const workspace = ctx.mount('workspace', manifest, { workspaceRoot: '/work/a' });
193
+ workspace.update({ workspaceRoot: '/work/b' });
194
+ };
195
+
196
+ await plugins.configure([{ key: 'parent', apply: parent, config: null }]);
197
+ ```
198
+
199
+ The changed child, its descendants and affected Service consumers are recreated;
200
+ unaffected parents and siblings remain active. Targets changed during preparation converge before installation,
201
+ so obsolete constructors do not become model-visible. A failed child constructor
202
+ is reported locally. An update may retain its previous observed child; a failed
203
+ new child contributes nothing. The same failed target is not retried automatically.
204
+ Change its configuration, replace a resolved provider registration, or dispose and
205
+ remount to attempt construction again.
206
+ Removal excludes the child subtree at reconciliation, including after a failed
207
+ update. While asynchronous preparation is in progress, requests retain the last
208
+ installed view. Overall preparation deadlines, invalid combined catalogs and
209
+ cleanup uncertainty still use the Platform failure contracts below.
210
+
211
+ Children use actual child Scopes. Parent cleanup waits for all child generations,
212
+ including superseded children whose finalizers still run after their last lease
213
+ drains. Repeated retirement joins the same cleanup Fiber; it never reruns a disposer.
214
+ Child mounts are process-local and are not written to Desired Composition;
215
+ Context Packages reconstruct their initial children by running apply again on restore; runtime discovery and private state are not durable intent. Children inherit their
216
+ current Service realm unless their definition opens a new one; a child Scope alone
217
+ does not establish a visibility boundary. See [ADR-0089](../../docs/adr/0089-parent-owned-plugin-children.md).
218
+
219
+ ### Services
220
+
221
+ A programmatic or installed Context Package definition may declare `{ requires: [Service], apply }`. Each key
222
+ must be an Effect Context key with a stable nonempty string, such as
223
+ `workspace/transport/v1`. Function and class-style keys work, including separate
224
+ imports of keys with the same string. `Scope.Scope` and `Layer.CurrentMemoMap`
225
+ are reserved for the Activation and cannot be required or provided as Plugin Services.
226
+ The typed API checks that the returned Effect requires only Scope and declared
227
+ services. The same definition works with Host `configure` and `ctx.mount`.
228
+
229
+ ```ts
230
+ import { Context, Effect } from 'effect';
231
+ import type { PluginContext } from '@sorbetai/plugins';
232
+
233
+ const Transport = Context.Service<{ describe(): string }>('workspace/transport/v1');
234
+ const consumer = {
235
+ requires: [Transport],
236
+ apply: (ctx: PluginContext) =>
237
+ Effect.gen(function* () {
238
+ const transport = yield* Transport;
239
+ ctx.context.prefix('transport', transport.describe());
240
+ }),
241
+ };
242
+ const provider = (ctx: PluginContext) => {
243
+ ctx.provide(Transport, { describe: () => 'Local workspace' });
244
+ };
245
+ await plugins.configure([
246
+ { key: 'consumer', apply: consumer, config: null },
247
+ { key: 'provider', apply: provider, config: null },
248
+ ]);
249
+ ```
250
+
251
+ Roots share the Platform realm by default; ordinary child mounts share their
252
+ parent's current realm. A definition can set `realm: 'inherit'` to open a new realm
253
+ with parent lookup, or `realm: 'isolate'` to open one without parent lookup. This
254
+ boundary applies to that mount and its descendants. The nearest realm containing
255
+ a key wins. Multiple providers in that nearest realm block resolution; they never
256
+ fall back to a parent or silently select the last provider.
257
+
258
+ To group sibling providers and consumers in an isolated space, open the realm on
259
+ their common parent. Isolating only a provider does not move its sibling consumers:
260
+
261
+ ```ts
262
+ await plugins.configure([
263
+ {
264
+ key: 'workspace',
265
+ config: null,
266
+ apply: {
267
+ requires: [],
268
+ realm: 'isolate',
269
+ apply: (ctx: PluginContext) => {
270
+ ctx.mount('consumer', consumer, null);
271
+ ctx.mount('provider', provider, null);
272
+ },
273
+ },
274
+ },
275
+ ]);
276
+ ```
277
+
278
+ The same realm policy works on definitions passed to `ctx.mount`. Realm boundaries
279
+ isolate Service lookup, not model-visible Tool/state names, permissions, JavaScript
280
+ execution or mutable values explicitly shared by the Host.
281
+
282
+ A Consumer may precede its Provider. Missing dependencies produce `pending` mounts
283
+ with `missingServices`; ambiguous required keys produce `conflictingServices`.
284
+ `status().serviceConflicts` reports every processed same-realm duplicate, even
285
+ without a Consumer: each entry identifies the key, `realmPath` (`[]` is the root)
286
+ and provider paths/activation identities. Providers remain active; consumers of
287
+ that ambiguous key wait. Diagnostics are detached snapshots.
288
+ A constructor prepared before a later conflict is discovered is cleaned up and
289
+ its contributions are excluded before request view. Trusted constructor IO cannot
290
+ be undone by this cleanup.
291
+
292
+ `ctx.provide` returns an idempotent registration handle. Providing the same key
293
+ twice within one instance throws; withdraw first to replace it. Withdrawal leaves
294
+ the resource owned by its Activation. The provider's generation and exact
295
+ registration identity are captured in each Consumer's Effect Context. Replacing
296
+ or withdrawing a provider reconstructs its dependent consumers and their actual
297
+ children; unrelated instances retain their identities. Re-registering the same
298
+ value still creates a new registration. Values captured by old closures are never
299
+ swapped behind a proxy.
300
+
301
+ Service changes schedule the existing command lane. `await plugins.flush()` waits
302
+ for processing, then `await plugins.status()` reports the processed targets. A
303
+ missing or conflicting Service withdraws dependent contributions when that view
304
+ is installed; requests during preparation can still borrow the preceding view.
305
+ Provider arrival or conflict removal wakes Pending consumers. A failed constructor
306
+ with declared dependencies is reported as `failed`; the same desired target and
307
+ provider registrations are not retried by unrelated changes or equivalent
308
+ configure calls. A changed target or binding permits another attempt. There is
309
+ no explicit retry method. Repeating dependency reconstruction is stopped with a
310
+ local `failed` diagnostic; a cold cycle in which no Provider can start still
311
+ appears as missing dependencies when its runtime `provide` outputs are undeclared.
312
+
313
+ Definitions may add `provides: [Service]` to describe expected outputs before apply
314
+ runs. This metadata supports cold-cycle diagnostics; it creates no Provider,
315
+ reserves no key and does not restrict later dynamic `provide` calls. Pending targets
316
+ report `pendingReason: 'dependency-cycle'` and a `dependencyCycle` witness when their
317
+ missing requirements form a cycle through visible declarations. Each witness step
318
+ names the mount path and Service it waits for; the last step returns to the first.
319
+ Lookup follows the nearest declared realm and never crosses an isolated boundary.
320
+ An actual Provider can break the wait and removes that diagnostic on convergence.
321
+ Cycle observations do not run constructors or cache a Failed target.
322
+
323
+ This diagnoses the declared wait graph, not arbitrary JavaScript. Outputs without
324
+ metadata and children not yet discovered beneath Pending parents cannot participate
325
+ in a cold witness. Incorrect declarations can describe an output that apply never
326
+ registers; Service availability still depends only on actual registrations.
327
+
328
+ Old leases retain their original Service values. Each lease retains the owners of
329
+ its callable Tools and callback contributions, plus their parents and resolved
330
+ Provider dependencies. A Host Tool ceiling excludes hidden Tool-only owners from
331
+ that borrow; their old generations can close while the request continues. Prefixes
332
+ are copied values and do not retain resources. Hooks, state readers, input transforms,
333
+ Context preparation, history selectors and Session behaviors remain available on
334
+ that lease and retain their owners. Provider cleanup joins every historical Consumer
335
+ generation and its finalizers; Consumer cleanup also joins its children.
336
+
337
+ Definitions default to `replacement: 'staged'`: the replacement prepares while the
338
+ old generation can still serve borrowed requests. Set `replacement: 'exclusive'`
339
+ on a resource-owning definition to require break-before-make at its mount path.
340
+ The old dependent contributions leave the new view, the target reports
341
+ `pendingReason: 'retiring'`, and construction waits for old borrows and cleanup.
342
+ `configure()` and `flush()` may return this Pending view; they do not wait for
343
+ borrowed work. Cleanup completion wakes the same reconciler. If Desired changes
344
+ while waiting, only the latest target is constructed. Exclusive constructor failure
345
+ is local `failed`; it cannot restore the already-closed resource. Cleanup failure
346
+ retains that owner and blocks its exclusive successor.
347
+
348
+ This policy applies to programmatic and installed Context Package roots and children.
349
+ It does not coordinate independent mount paths, Platforms, processes or undeclared
350
+ external locks. Package definitions export their runtime-readable declarations beside
351
+ `apply`; the loader resolves them before Service readiness under the instance Scope.
352
+ Trusted module evaluation and profile conversion may occur while apply is Pending;
353
+ exclusive resources must be acquired inside apply. See the [loading contract](./EXECUTION.md#native-module-and-author-abi). See [ADR-0092](../../docs/adr/0092-resource-borrows-and-exclusive-replacement.md)
354
+ and the [resource and execution acceptance](../../docs/exec-plans/20261011-effect-native-resources.md).
355
+
356
+ Tool registrations may capture a synchronous `prepareArguments` normalizer. The
357
+ Session invokes this trusted author code before Pi schema validation and Sorbet
358
+ permission evaluation. Purity is an author obligation, not a runtime guarantee;
359
+ protected effects belong in the permissioned executor. This callback is not covered
360
+ by the later permission decision; direct `lease.invoke()` still requires validated arguments.
361
+ Callbacks use the original registration receiver and remain bound to that request.
362
+ Package revocation gates normalization as well as execution. Optional `outputSchema`
363
+ metadata describes successful `structuredContent`; Sorbet validates the result envelope and JSON serializability, but does not enforce that output schema. `constrainedSampling` controls model generation of input arguments. These declarations reach the Pi adapter; `structuredContent` is machine-readable result data and Pi does not send it to the model. Successful or failed results may include it. `context.onUpdate` publishes detached,
364
+ validated transient results and expires when execution settles. It is not a Journal
365
+ fact or evidence of an Effect outcome.
366
+
367
+ ## Session slash command contributions
368
+
369
+ A Plugin can contribute a Session slash command by registering a Tool that accepts
370
+ `{ arguments: string }` and adding the `sorbet.dev/slash-command` metadata. The
371
+ command name is the user-facing name without `/`; it must be nonempty and contain
372
+ neither whitespace nor `/`. `description` is required and `argumentHint` is optional.
373
+ The metadata object admits only these fields.
374
+
375
+ ```ts
376
+ import type { PluginApply } from '@sorbetai/plugins';
377
+ import * as s from '@earendil-works/pi-schema';
378
+ import { decode } from '@sorbetai/schema';
379
+
380
+ const Arguments = s.obj({ arguments: s.str() });
381
+ const hello: PluginApply<null> = (ctx) => {
382
+ ctx.tools.register({
383
+ name: 'hello_command',
384
+ description: 'Greet a person.',
385
+ parameters: Arguments,
386
+ metadata: {
387
+ 'sorbet.dev/slash-command': {
388
+ name: 'hello',
389
+ description: 'Greet a person.',
390
+ argumentHint: '<name>',
391
+ },
392
+ },
393
+ execute: async (input) => {
394
+ const { arguments: name } = decode(Arguments, input);
395
+ return { content: [{ type: 'text', text: `Hello, ${name}!` }], details: null };
396
+ },
397
+ });
398
+ };
399
+ ```
400
+
401
+ A host can select `/hello` from `session.slashCommands` and dispatch it with the
402
+ raw argument string. This invokes the Tool through the Session's existing validation,
403
+ Permission and write-ahead Effect boundaries; metadata grants no permission. Tool
404
+ ceilings and Host Tool overrides affect whether a contribution is eligible. Invalid
405
+ metadata is ignored. The author must ensure the Tool accepts the argument shape;
406
+ ordinary Tool validation still applies on execution.
407
+
408
+ The directory follows committed Tool changes. Session-owned commands take priority;
409
+ conflicting Tool contributions are omitted and reported by `conflicts()`. Replacing
410
+ or withdrawing a Tool invalidates the old selection, so a host should retain and pass
411
+ its `selectionId` and refresh on rejection. This is a Tool metadata contribution, not
412
+ a general API for plugins to dynamically register arbitrary command handlers. See the
413
+ [Node Agent Session contract](../node-agent/README.md#session-slash-commands).
414
+
415
+ ## Addressable objects
416
+
417
+ Use an object factory when a capability has many instances selected by a JSON key.
418
+ `defineObject` captures the key schema, contract version (default `1`) and method
419
+ input/output schemas once at the SDK boundary. Internal catalogs and acquisitions
420
+ borrow that readonly contract; they do not reconstruct, serialize or freeze it.
421
+ Factory registration does not construct an instance or create
422
+ a child Mount.
423
+
424
+ ```ts
425
+ import { defineObject, type PluginApply } from '@sorbetai/plugins';
426
+ import { Effect } from 'effect';
427
+ import * as s from '@earendil-works/pi-schema';
428
+
429
+ const Counter = defineObject('workspace.counter', {
430
+ key: s.str(),
431
+ methods: { add: { input: s.int(), output: s.int() } },
432
+ });
433
+ const counters: PluginApply<null> = (ctx) => {
434
+ ctx.objects.serve(Counter, {
435
+ create: (_key, self) =>
436
+ Effect.gen(function* () {
437
+ const value = yield* self.state('value', {
438
+ schema: s.int(),
439
+ version: 1,
440
+ initial: 0,
441
+ });
442
+ return {
443
+ add: (amount) =>
444
+ value.update((current) => current + amount).pipe(Effect.andThen(value.get)),
445
+ };
446
+ }),
447
+ });
448
+ };
449
+ await plugins.configure([{ key: 'counters', apply: counters, config: null }]);
450
+ const result = await Effect.runPromise(
451
+ Effect.scoped(
452
+ Effect.gen(function* () {
453
+ const counter = yield* plugins.objects.acquire(Counter, 'builds');
454
+ return yield* counter.call('add', 1);
455
+ })
456
+ )
457
+ );
458
+ ```
459
+
460
+ A Plugin that publishes state for a Host to observe holds its own instance through
461
+ `ctx.objects.acquire`, which resolves the same addresses in the same namespace. Take
462
+ that reference from supervised work: acquiring during `apply` deadlocks the
463
+ Activation's own retirement. The Host reads the shared slot with `ref.states()` or
464
+ `ref.watchState(name)`.
465
+
466
+ An address consists of the Platform `scopeId`, type ID, contract version and canonical
467
+ JSON key. Reordered object properties select the same address; lossy values such as
468
+ `undefined` and non-finite numbers reject. Different keys construct independent
469
+ instances. Concurrent acquisitions of one address and factory generation share one
470
+ construction. References belong to their acquiring Effect Scope; closing one does
471
+ not invalidate other holders. Calls made through a released reference fail.
472
+
473
+ Factory Effects require only Scope. Read declared Services in the enclosing `apply`
474
+ and capture those values in the factory. Each implementation has its own Scope and
475
+ Layer cache, and borrows its Mount, parents and Service providers until admitted
476
+ calls and references release. Native resources use `Effect.acquireRelease`. After
477
+ the last holder and invocation leave, Composition retires that implementation;
478
+ reacquisition waits for its cleanup before constructing the same generation again.
479
+
480
+ New acquisitions capture the current factory. Existing references retain their
481
+ implementation through compatible replacement while the type remains available.
482
+ Withdrawing the type rejects new acquisition and calls; already admitted calls keep
483
+ their resource borrow. Root close rejects admission and cancels owned work before
484
+ closing resources. Cleanup failure or timeout retains observable residency and does
485
+ not retry a finalizer. `status().objects` reports holders, invocations and residual
486
+ resources.
487
+
488
+ Host acquisition sees factories registered in the root Realm. Child Realms remain
489
+ private; duplicate visible factories or a different schema under the same type ID
490
+ and version reject acquisition. Factory-only registration changes use contribution
491
+ snapshots without restarting Mounts. Methods validate JSON inputs and outputs and
492
+ return Effects; they are direct Host capabilities. Selected methods can become
493
+ [request-bound Tools](#discovery-and-model-projection) through the Runtime's standard
494
+ permission and Journal boundaries.
495
+
496
+ ### Stable state
497
+
498
+ `self.state(name, { schema, version, initial })` declares an instance-owned state slot
499
+ during factory creation. Compatible implementations at the same address share that
500
+ slot while either generation is held. The initial value is used only when the slot
501
+ is first created. The logical instance ID remains stable across overlapping
502
+ generations; references continue calling their captured implementation.
503
+
504
+ A successor must declare exactly the same schema and version to reuse a slot.
505
+ An incompatible successor requires an explicit migration; increasing a version
506
+ alone rejects the candidate. New slots and migrated values remain private until
507
+ successful adoption. Preparing code may read its candidate state; writes reject
508
+ until adoption, and declarations reject after creation completes.
509
+
510
+ ```ts
511
+ const count =
512
+ yield *
513
+ self.state('count', {
514
+ schema: s.obj({ value: s.int() }),
515
+ version: 2,
516
+ initial: { value: 0 },
517
+ migrate: {
518
+ from: { schema: s.int(), version: 1 },
519
+ transform: (previous) => ({ value: previous }),
520
+ },
521
+ });
522
+ ```
523
+
524
+ The previous schema and version must match exactly, and the target version must
525
+ increase. The transform must be pure and synchronous. It runs once per candidate
526
+ against the latest old value after already admitted method calls finish. New calls
527
+ and new captured method borrows from older generations reject while the transition
528
+ is pending. After call drain, older state writers also reject; asynchronous writers
529
+ revalidate before committing. The existing preparation deadline bounds this wait.
530
+
531
+ Transformation and factory preparation leave committed state unchanged. Failure or
532
+ cancellation restores old call and write admission, subject to current source
533
+ authorization. Successful adoption publishes the new schema, value and method
534
+ generation together, and advances the state revision even if its JSON value is
535
+ equal. Older method references, captured model callbacks and typed state handles
536
+ then fail as superseded. They retain cleanup ownership until their scopes release;
537
+ they cannot continue writing a detached copy of business state.
538
+
539
+ `state.set(value)` and `update(current => next)` admit and capture the next value
540
+ at the SDK write boundary. Read results and updater inputs are readonly borrows
541
+ of the owner's committed value. Callers return a new value instead of mutating
542
+ that borrow; internal handoffs do not copy or recursively freeze it. Each synchronous
543
+ update runs once under the slot's mutation lane; a failed update leaves state
544
+ unchanged. Equal values do not advance the revision.
545
+
546
+ `state.changes` is an Effect Stream of complete `{ name, version, revision, value }`
547
+ frames. A subscriber receives the latest frame and subsequent updates through a
548
+ capacity-one queue; slow readers may skip revisions. This is a current-state feed,
549
+ not a transition log. Closing the declaring generation ends its subscriptions.
550
+ State writes do not reconstruct Mounts or change model Tool bindings.
551
+ Generation finalizers may still read and update compatible state during cleanup.
552
+ An incompatible migration revokes old typed handles, including cleanup writes.
553
+ Such a cleanup failure remains visible as residual residency and retains its source;
554
+ it is never hidden, retried, or applied to the new state shape.
555
+
556
+ The stable instance owns slots independently of implementation resources. Once all
557
+ generations and admitted calls release, the instance closes its slots; a later
558
+ acquisition starts from the initial value. Slots are process-local and never replace
559
+ Session Journal facts or committed Context state.
560
+
561
+ Hosts read the same committed slots with `ref.states()`. Snapshots are sorted by
562
+ name and contain `{ name, schema, version, revision, value }`; their JSON schemas and
563
+ values are immutable. Preparing or failed candidates cannot expose provisional
564
+ slots. The read constructs no instances and grants no state mutation capability.
565
+
566
+ `ref.watchState(name)` returns an Effect Stream of these snapshots for one committed
567
+ slot. It starts with the latest revision and uses the same capacity-one feed as
568
+ `state.changes`, so slow consumers can skip intermediate revisions. Unknown slots
569
+ fail when subscribed. A held reference can observe shared state across compatible
570
+ implementation adoption while its method calls remain pinned to their original
571
+ generation. Host observation also continues across an incompatible migration;
572
+ every frame captures its own schema and version. Updates do not alter a captured
573
+ model request or enter Context by themselves.
574
+
575
+ The acquiring reference owns observation lifetime. Releasing that reference ends
576
+ its active streams even if another reference or model request retains the instance.
577
+ Root shutdown also ends streams before waiting for resource cleanup. Starting a read
578
+ or subscription after release fails; factory availability and source authorization
579
+ still gate observation. Consumers use ordinary Effect Stream cancellation and must
580
+ retain their reference for as long as they observe it.
581
+
582
+ ### Stable resources
583
+
584
+ `self.resource(name, token, { version, identity, acquire })` declares a resource
585
+ owned by the logical instance. The Effect Context token determines its TypeScript
586
+ value type; it does not resolve a Service. Acquisition runs once in a private Scope
587
+ and Layer cache before any constructor receives the value. Use
588
+ `Effect.acquireRelease` inside `acquire` to attach cleanup to that owner.
589
+
590
+ ```ts
591
+ const Connection = Context.Service<DatabaseConnection>('workspace.connection');
592
+ const acquireConnection = self.resource('connection', Connection, {
593
+ version: 1,
594
+ identity: { database: key },
595
+ acquire: Effect.acquireRelease(openDatabase(key), closeDatabase),
596
+ });
597
+ ```
598
+
599
+ Yield `acquireConnection` inside the factory's Effect generator. Here `Context`
600
+ comes from `effect`, and the application supplies the connection type and
601
+ acquisition Effects. Concurrent compatible constructors share the
602
+ acquisition and exact resource value. For an existing slot name, compatibility
603
+ requires the same token key, version, finite JSON identity and resolved Service
604
+ registrations. Changing those fields rejects the candidate before its acquisition
605
+ runs unless the declaration selects an explicit replacement policy. Staged replacement
606
+ acquires a private revision while old methods continue using their original value.
607
+ The new resource, state declarations and methods become current together after
608
+ construction succeeds. A failed or cancelled candidate cleans its provisional
609
+ revision and preserves the current one. A different name declares an independent
610
+ slot. Select `replacement: 'exclusive'` when incompatible revisions cannot coexist.
611
+ Exclusive replacement first rejects new calls on previous implementations and waits
612
+ for admitted calls. It then revokes older Ref, captured-method and producer handles,
613
+ joins outstanding state writers, closes older implementation Scopes and disposes
614
+ all older revisions of that named resource before acquiring the new one. Held Refs
615
+ and model captures do not postpone this explicit revocation. Old generation
616
+ finalizers may use their raw resource until disposal, but state writes through
617
+ revoked handles fail and remain visible as cleanup failures.
618
+
619
+ Cancelling before old owners start closing restores previous call admission. Once
620
+ teardown starts, cancellation, acquisition failure or a failed constructor cannot
621
+ restore those owners. A failed or timed-out disposer prevents acquisition of the
622
+ replacement, retains its original ownership and never runs again automatically.
623
+ The same cleanup task may finish later. After actual cleanup drains the instance,
624
+ an explicit acquisition may construct a fresh instance. Sorbet does not retry an
625
+ uncertain disposer or promise rollback of destroyed resources.
626
+
627
+ The resource independently retains the originating Mount and its Service closure,
628
+ even after that implementation generation drains. Its acquisition must not capture
629
+ handles owned by a shorter generation Scope. Reusing it also preserves its original
630
+ Package authorization: replacing the factory cannot authorize code from a revoked
631
+ origin. Finalizers still require that original authorization.
632
+
633
+ The current revision survives while any generation of its instance remains. A
634
+ staged revision closes after its using generations and admitted calls drain;
635
+ held old Refs and captured model callbacks keep their original revision. A late
636
+ older constructor cannot replace a more recently adopted resource. A failed or
637
+ cancelled candidate releases its provisional interest; another constructor may
638
+ still be using the same acquisition. When the instance drains, every resource is
639
+ offered cleanup in reverse declaration order. Failed or timed-out cleanup retains
640
+ residency and its origin borrow without replaying the disposer. Actual late success
641
+ removes that residual. `status().objects` keeps each revision's diagnostics visible
642
+ even after all implementation rows drain.
643
+
644
+ ### Discovery and model projection
645
+
646
+ `objects.catalog()` reads immutable root-visible contracts and resident addresses
647
+ without constructing instances or creating Tool declarations. Contracts describe
648
+ key and method schemas; `availability` distinguishes an available registration from
649
+ ambiguous providers. The catalog is current process metadata. An address in it does
650
+ not grant execution or certify that construction will succeed. Acquisition and
651
+ invocation check current availability and authorization separately.
652
+
653
+ The Host can select a method and register its model projection:
654
+
655
+ ```ts
656
+ import { bindObjectMethod } from '@sorbetai/plugins/model';
657
+
658
+ await Effect.runPromise(
659
+ Effect.scoped(
660
+ Effect.gen(function* () {
661
+ const counter = yield* plugins.objects.acquire(Counter, 'builds');
662
+ const tool = yield* bindObjectMethod(counter, 'add', {
663
+ name: 'add_builds',
664
+ description: 'Increment the build counter.',
665
+ });
666
+ yield* Effect.promise(() =>
667
+ plugins.configure([
668
+ { key: 'counters', apply: counters, config: null },
669
+ {
670
+ key: 'selected-counter',
671
+ apply: (ctx) => {
672
+ ctx.tools.register(tool);
673
+ },
674
+ config: null,
675
+ },
676
+ ])
677
+ );
678
+ })
679
+ )
680
+ );
681
+ ```
682
+
683
+ The projection Scope owns an independent borrow. Registration must reach the
684
+ Composition snapshot before that Scope closes, as `configure()` does here. Committed
685
+ contributions and request leases then retain their own borrows. Withdrawing the Tool
686
+ releases its contribution borrow; a captured request can finish against its original
687
+ implementation even after the creating reference and projection Scope close.
688
+ Replacement cannot retarget that request. Withdrawal of the object type, source
689
+ failure and Package revocation still gate new invocations.
690
+
691
+ Tool arguments use `{ input: ... }`, with the native method's input schema nested
692
+ under `input`. This also supports methods whose native input is a number, array or
693
+ `null`. The captured address and method appear in the Tool description and result
694
+ details; model arguments cannot change the target. `structuredContent` contains the
695
+ native result and uses its output schema. The same value is rendered as JSON text
696
+ for the model. Runtime can archive oversized text and omit its structured value;
697
+ result details retain only the fixed target. Cancellation flows through the existing
698
+ Tool invocation signal into the method Effect.
699
+
700
+ Register only selected methods. Tool Ceiling and deferred `tool_search` apply to
701
+ these ordinary Plugin Tools. Runtime performs validation, permissions and write-ahead
702
+ effect recording before dispatch. Calling `ref.call()` directly remains a Host
703
+ capability and does not admit a Runtime operation.
704
+
705
+ `platform.objectCapabilities` exposes the borrowed `ObjectCapabilitySource` port
706
+ from `@sorbetai/plugins/model`. Its scoped `bind(address, method, metadata)` resolves
707
+ the registered key contract and captures a native method without publishing a
708
+ Platform Tool. Runtime uses this port for [Agent-selected methods](../runtime/README.md#agent-selected-object-methods)
709
+ under explicit Session grants. Selection belongs to that Session, while the native
710
+ instance and source resource closure remain owned by Composition.
711
+
712
+ The [architecture decision](../../docs/adr/0099-object-aware-composition.md) defines
713
+ the ownership model. The [implementation record](../../docs/exec-plans/20261015-object-aware-composition.md)
714
+ tracks validation and delivery boundaries.
715
+
716
+ ### Remote facets
717
+
718
+ `@sorbetai/plugins/remote` exposes JSON Object contracts across a Host-owned
719
+ connection. Wire ingress decodes peer data and checks the data-only schema profile;
720
+ the typed core adopts those values directly. Transport encoding serializes at the
721
+ connection boundary rather than recapturing JSON at each internal handoff.
722
+ `ObjectFacetTransport.request` returns an already decoded `FacetReply`; custom
723
+ transports use `decodeObjectFacetReply` at peer ingress. Servers use
724
+ `decodeObjectFacetRequest` before passing requests to the typed Facet. The hello
725
+ identity includes the namespace, which the client owns for its lifetime. Typed
726
+ acquisition sends its known contract directly without a discovery RPC; the origin
727
+ still checks that contract against its current factories. Explicit catalog reads
728
+ continue to discover the current contracts and instances.
729
+ `makeObjectFacet(platform.objects, options)` borrows the origin's
730
+ existing Composition; it does not construct a second registry. By default each
731
+ connection owns its scoped handles. With `lifetime: 'resumable'`, the Host owns
732
+ the Facet Scope across connections and must close it explicitly. The Host must
733
+ bind every connection to the same authenticated principal; the peer cannot
734
+ choose its principal or placement. Facet identity changes invalidate old holds.
735
+ Discovery, acquisition, calls and observation are authorized independently;
736
+ re-holding an original handle is also authorized, and long-poll observations
737
+ recheck authority before returning a frame. Releasing an owned handle or
738
+ abandoning its acquisition reservation remains possible after permission withdrawal.
739
+
740
+ `makeRemoteObjectClient(transport)` owns the transport in its Effect Scope and
741
+ returns `objects` with the same typed acquisition/call/observation API. Its
742
+ `objectCapabilities` port can supply the Session capability explorer directly.
743
+ Acquired handles pin their original target and implementation generation. A
744
+ captured model Tool can outlive its creator Ref through its own scoped borrow;
745
+ after that binding closes it cannot be revived by another live Ref.
746
+
747
+ Node Hosts can use `serveObjectFacet(duplex, facet)` and
748
+ `objectFacetTransport(duplex)` from `@sorbetai/plugins/node`. The Duplex must
749
+ already have the authentication and encryption required by its Host. Frames use
750
+ the existing bounded isolate channel. Requests have no default execution deadline.
751
+ TCP sockets use `TCP_NODELAY` so successive request waves do not wait for delayed
752
+ acknowledgements. Frame limits apply to actual wire bytes in each direction;
753
+ incoming JSON is not reserialized to enforce an expanded representation limit.
754
+ `requestTimeoutMs` is an explicit Host policy that cancels only that request;
755
+ quiet state subscriptions do not inherit it. `concurrency` bounds in-flight data
756
+ requests through cancellable waiting, while watch and release controls can proceed.
757
+ Connected cancellation waits for origin settlement before acknowledgement. Optional
758
+ `cancellationTimeoutMs` only ends observation: the original pending request and its
759
+ permit remain owned until actual settlement or disconnection. It never closes the
760
+ connection. A lost connection cannot prove external rollback or completed cleanup.
761
+
762
+ `makeRemoteObjectClient(transport)` owns one connection and does not reconnect.
763
+ `makeResumableRemoteObjectClient({ connect })` re-establishes access to one
764
+ Host-owned resumable facet. The connector owns authentication, routing and retry
765
+ pacing. Re-holding looks up the original opaque handle and generation; it never
766
+ acquires an address against a newer factory. Existing Refs and captured model
767
+ callbacks therefore keep their original target after reconnection. State watches
768
+ resume the same held instance after their last observed revision. If that facet
769
+ or handle has closed, recovery fails rather than constructing a replacement.
770
+
771
+ A dispatched call without a terminal reply throws
772
+ `ObjectInvocationUnknownError` (`code: 'object-invocation-unknown'`), also exported
773
+ from `/model` for Runtime classification. `ObjectFacetUnavailableError` means the
774
+ transport knows dispatch did not happen. Calls are never replayed after an
775
+ uncertain reply. The client assigns acquisition identity before dispatch; a
776
+ lost acquisition reply remains Unknown while the resumable client reconciles
777
+ and releases that exact reservation. Duplicate identity joins the recorded
778
+ acquisition or reports its release; it never runs the factory again. Acquisition
779
+ and handle identities have separate indexes in the owning facet. Once release is
780
+ confirmed, the facet removes both index entries as part of that release. The request
781
+ contains the adopted acquisition identity and handle: the client has observed its
782
+ original acquisition and must never send it again. A lost release reply can retry
783
+ the same release control without repeating its constructor or disposer. A failed
784
+ constructor whose cleanup succeeds leaves only its acquisition and handle identities
785
+ until the Host closes the Facet Scope. This fence rejects delayed old-wire duplicates
786
+ without retaining its Promise, error, native Ref, Scope, contract or input payload.
787
+ Actual cleanup failure instead retains the original receipt and cached failure;
788
+ the disposer is never replayed.
789
+
790
+ Abandoning an uncertain acquisition can arrive before its original request. It
791
+ therefore leaves a thin identity fence until the Host closes the Facet Scope.
792
+ Ordinary release cannot remove this fence and admit a delayed constructor. Unknown
793
+ acquisition reconciliation releases the original reservation without replaying it.
794
+
795
+ Normal same-Scope finalization releases Refs before closing their client and waits
796
+ for real origin cleanup. Closing the client while external Ref Scopes or acquisitions
797
+ remain active instead forces local termination: it stops reconnection, aborts local
798
+ observation, closes the owned wire, then joins local work. Node closes its local
799
+ socket without waiting for a peer's writable half to end. The connector must honor
800
+ its establishment signal and settle when aborted. Failed transport cleanup retains
801
+ its original owner and cached failure without replaying its disposer.
802
+ `ObjectFacetRecoveryPendingError` preserves the facet identity and unreconciled
803
+ `acquisitionIds`; forced closure never claims their remote resources were released.
804
+ The origin's resumable Facet Scope still owns unresolved holds and must be closed
805
+ by its Host. Default connection
806
+ mode instead releases idle and provisional holds immediately on disconnect,
807
+ while already admitted origin work continues draining under its real owner.
808
+ State feeds remain transient observations, not durable execution evidence. Raw
809
+ Context Service values and stable resource objects stay inside their owning Host.
810
+
811
+ Remote key, method input/output and observed state schemas use the same
812
+ data schema profile as Worker contributions. It supports JSON primitives, objects,
813
+ arrays, unions and numeric/size constraints. Author regexes, formats, references and
814
+ custom keywords are rejected at every node before schemas reach consuming Host validators.
815
+ The profile is checked with iterative, shallow decoding, without fixed depth, node,
816
+ property or branch counts. Local native contracts retain their
817
+ full schema support. A contract that needs those features must validate them inside
818
+ its owning Host and expose a supported data contract across the connection.
819
+
820
+ ## Lifecycle and resources
821
+
822
+ Every Activation has an independent `Layer.CurrentMemoMap`, without a parent cache.
823
+ Native Effect apply therefore constructs Layers against its own resource lifetime,
824
+ even when another mount or the Host uses the same Layer object. Replacement and
825
+ Session reattachment create new caches. Sharing a Host-constructed Service remains
826
+ explicit through `ctx.provide`; an author-supplied MemoMap, shared mutable value or
827
+ Layer constructed from a preexisting object is trusted code outside this default.
828
+ Realm lookup does not partition JavaScript module caches. See
829
+ [native module ownership](./EXECUTION.md#native-module-and-author-abi).
830
+
831
+ Mounts move through Pending, Loading, Active or Failed, Retiring, and Closed.
832
+ `configure()` and `replace()` return after graph convergence; neither returns or persists a model catalog. Durable `reconcile()` observes current Desired. `flush()` waits for queued graph changes, not request drain. New model requests sample the current usable contributions.
833
+
834
+ Normal replacement stops new borrows of the old owner. Existing requests retain their captured callbacks, parents and Service dependency closure until actual settlement. Effect Scope runs eligible finalizers in LIFO order. The cleanup timeout bounds acquisition cancellation and finalizer settlement; it does not time out legitimate request borrows. Cleanup deadlines report `residualResources` and retain ownership while the same task and sequential Scope cleanup continue. Actual late success removes residual residency and unblocks exclusive replacement; the old generation remains fenced. A disposer failure retains ownership and is not retried automatically. Unrelated owners continue serving.
835
+
836
+ `ctx.supervise()` does not delay readiness. A task failure marks its Mount Failed, withdraws its capabilities and dependent consumers, and signals existing callbacks in that closure. Independent capabilities remain usable, including on an already acquired lease. Failure does not change Desired or past request evidence. There is no automatic retry of the same failed instance.
837
+
838
+ Preparation and cleanup follow their owning Effect Scopes without implicit deadlines. A Host may set `preparationTimeoutMs` to cancel an overdue candidate, or `cleanupTimeoutMs` to bound cleanup observation. Both accept positive safe integer milliseconds. A cleanup observation timeout retains the original cleanup fiber and its resources; it neither proves settlement nor retries a finalizer. Cancellation signals author code; it cannot prove external work stopped. Late Promise settlement stays observed. Native finalizers retain Effect's Scope semantics. Platform close reports unresolved cleanup and disposes the root only after successful resource release. A failed close receipt does not reopen admission. A later `close()` can join the original retirement after real settlement and finish root disposal; it never repeats completed or failed finalizers. Historical timeout diagnostics remain visible after late success.
839
+
840
+ Registration withdrawal affects future requests. Captured callbacks can still run while their resource borrow is valid; mutable business data inside author closures is not frozen. Restart runs current enabled Desired definitions again. Runtime-discovered registrations, private state and old executors are not restored from model history.
841
+
842
+ ## History selection
843
+
844
+ A request view captures history selectors in registration order. Each selector receives the complete units retained by its predecessor. Their result initializes `draft.modelView` before Host and Plugin preparation Hooks run. Hooks may inspect, replace or remove that view and add derived request material. The Runtime validates the final projection before durable adoption.
845
+
846
+ The selector receives trusted `sessionId`, `runId`, `requestScopeId`, the invocation signal, and a read-only snapshot of the effective conversation projection. Each unit is either one message without Tool calls or one assistant Tool-call message plus its complete result group. The selector must return an ordered subset of the exact unit objects it received. Clones, duplicates, stale objects, and reordering fail. The Runtime expands units to message references and validates Tool pairing, protected inputs, persistence, retries and reconstruction. Existing request leases retain their captured selector chain through replacement and withdrawal.
847
+
848
+ The optional `history.active` snapshot supplies the complete current-Run prefix,
849
+ including user inputs already consumed before its latest complete assistant boundary.
850
+ It excludes that latest exchange and any newly adopted input after it. A policy may summarize those older units
851
+ and use the supplied `reclaimBefore` reference in a preparation Hook, retaining
852
+ uncovered active references in chronological order. Ordinary selectors continue
853
+ to filter `history.units`; no active history is reclaimed merely by reading it.
854
+
855
+ A separately injected fork seed is protected and excluded from selectable units. After compaction, inherited entries that became part of the effective retained tail follow the same projection and cut rules as other effective history. Compaction exposes only its effective summary and retained tail; it never revives replaced messages. An explicit `modelView` replaces the built-in automatic compaction policy for that request. Sorbet still records token estimates, while the Provider determines actual capacity; the built-in compaction reserve does not reject a custom projection. If no history is selectable, the selectors still run but produce no model view, preserving existing automatic compaction. An identity selector therefore differs from installing no selector. Physical retries reuse captured evidence and do not rerun policy.
856
+
857
+ `selectHistory` filters complete exchanges. Use `ctx.context.around` to derive summaries or replace the resulting view from one committed read. Request sources preserve attribution without becoming new user commands. The Runtime Tape example uses this path to avoid a second read or request-keyed handoff state.
858
+
859
+ ## Tool Hooks
860
+
861
+ Register `ctx.tools.hook` for both Host and Plugin Tool calls. Supply at least one
862
+ of `prepare` and `feedback`; there is no author-owned executor continuation.
863
+
864
+ ```ts
865
+ import type { PluginApply } from '@sorbetai/plugins';
866
+
867
+ const auditFeedback: PluginApply<null> = (ctx) => {
868
+ ctx.tools.hook({
869
+ key: 'feedback',
870
+ prepare: async (input, { toolName }) => ({ input, state: toolName }),
871
+ feedback: async (result, state, { signal }) => {
872
+ signal.throwIfAborted();
873
+ result.content.push({ type: 'text', text: `Processed ${state}` });
874
+ return result;
875
+ },
876
+ });
877
+ };
878
+ ```
879
+
880
+ `prepare` receives a JSON argument draft and returns `{ input, state? }`. The
881
+ executor validates the final arguments and obtains permission before dispatch.
882
+ Return `{ block: true, reason }` to deny execution, or
883
+ `{ input, respond: { content, details, isError } }` for a replacement response that
884
+ still requires the original Tool's schema and permission checks. Neither short
885
+ circuit creates an Effect. This is trusted-code policy, not a sandbox or proof of
886
+ cache-source authorization.
887
+
888
+ `feedback` receives a detached result and that Hook's prepared state (null when
889
+ omitted). It may edit content, JSON details, structured content and isError;
890
+ execution identity, usage and termination remain domain-owned. Preparation runs
891
+ in order and feedback in reverse order. A responding Hook skips its own feedback
892
+ and subsequent Hooks; earlier Hooks may process the response. Blocked, denied,
893
+ cancelled and unknown attempts do not enter ordinary feedback processing.
894
+
895
+ `before`/`after` constrain deterministic ordering. A string refers to a local key;
896
+ `{ entry, key }` addresses a root Entry. Unknown references, duplicates and cycles
897
+ reject the request view. Session/Run or operation identity comes from the lease,
898
+ not caller-selected impersonation; metadata does not grant Session authority.
899
+
900
+ Both phases must be repeatable data processing. C persists final parameters,
901
+ Hook identities/versions and JSON state before approval or dispatch. Restart
902
+ uses the checkpoint’s reference to that saved preparation and never reruns it. Real Effect
903
+ outcomes commit before feedback, so restarting or failing feedback cannot repeat
904
+ the Tool. A phase interrupted before its own result commits may run again;
905
+ external effects require a separate authorized operation.
906
+
907
+ `version` defaults to 1. Increase it for incompatible persisted state or feedback
908
+ changes. Recovery requires the admitted chain and compatible handlers; missing
909
+ or changed versions produce explicit failure without guessing or redoing an
910
+ Effect. Live requests retain their original callbacks until they drain.
911
+
912
+ Trusted `/model` consumers use `prepareToolHooks` and `finishToolHooks` with their
913
+ own durable boundary. A/B's `runToolHooks` assembles those same phases around its
914
+ protected execution ports. `invoke` remains raw Tool dispatch and grants no
915
+ permission. Sorbet executors perform this assembly automatically. See
916
+ [ADR-0067](../../docs/adr/0067-domain-owned-hook-continuations.md) for the full
917
+ contract and the migration from `tools.around`.
918
+
919
+ ## Context state
920
+
921
+ Register state through `ctx.context.state`. Each state has an optional local key, an
922
+ XML-compatible `stateName`, a JSON `schema`, and an async
923
+ `read({ sessionId, runId, signal })`.
924
+ Return `{ present: true, value }` or `{ present: false }`. The immutable metadata comes
925
+ from lease acquisition, not caller-selected Session impersonation. It is not a Session
926
+ command capability. Authors must partition Session-specific private data by `sessionId`;
927
+ the SDK does not make shared mutable closures isolated or durable.
928
+
929
+ ```ts
930
+ import type { PluginContext } from '@sorbetai/plugins';
931
+ import * as s from '@earendil-works/pi-schema';
932
+
933
+ // The Host supplies a Session-keyed view; the contribution only reads it.
934
+ function registerProgress(ctx: PluginContext, values: ReadonlyMap<string, number>): void {
935
+ ctx.context.state({
936
+ key: 'progress',
937
+ stateName: 'workspace_progress',
938
+ schema: s.num(),
939
+ read: async ({ sessionId, signal }) => {
940
+ signal.throwIfAborted();
941
+ const value = values.get(sessionId);
942
+ return value === undefined ? { present: false } : { present: true, value };
943
+ },
944
+ });
945
+ }
946
+ ```
947
+
948
+ Each new logical request reads from the same immutable request view as its Tools and
949
+ Hooks. Readers are independent and may run concurrently; stable state-name order
950
+ controls the resulting projection, not callback completion. Duplicate names or IDs
951
+ reject request view; a Host state-name conflict fails request preparation. No priority,
952
+ scope-shadowing, cross-reader transaction, or stale-value fallback is implied.
953
+
954
+ The lease validates and copies results, retaining active readers through actual
955
+ settlement even after cancellation. Runtime connects these readers to its existing
956
+ ContextManager, which owns value revisions and restoration/transition/deletion frames.
957
+ The request base records the request view declarations; the Context snapshot records
958
+ values and source identities. Physical retries reuse captured values. Inspection/reconstruction
959
+ does not execute readers, and owner removal records a deletion without rewriting history.
960
+
961
+ This is a contribution, not an `around` Hook: no `next`, model dispatch, mutable message
962
+ array, Journal writer or new Context registry is exposed. General message transforms
963
+ and Plugin private-state persistence remain outside this slice.
964
+ See [ADR-0068](../../docs/adr/0068-leased-plugin-context-state.md).
965
+
966
+ State readers also receive optional `toolResults`: an immutable, detached
967
+ `PluginToolResultSnapshot` captured once before request preparation. Sorbet Runtime
968
+ supplies this Session's committed feedback in Journal order, including fact/Run/Tool
969
+ identities, error flags and JSON details (null when absent), under one prefix sequence/cursor. It does
970
+ not include message content or inherited fork messages. All readers share the same
971
+ prefix but cannot mutate each other's copy. Other execution consumers may omit this
972
+ capability; absence is not an empty history. Plugins requiring it must fail explicitly.
973
+
974
+ This observation has no `next`, background task, acknowledgement or write authority.
975
+ Recompute projections after reopen/replacement; physical retries reuse captured state.
976
+ Reader failure fails preparation without undoing previously committed effects. Details
977
+ are feedback, not proof of Effect success: Hooks can edit or replace them. These are
978
+ trusted Session-wide reads, not filtered by `pluginToolNames` or a per-Plugin grant.
979
+ The [workspace consumer](../tools-node/README.md#workspace-plugin) uses this contract
980
+ without private persistence. [ADR-0081](../../docs/adr/0081-committed-tool-observation.md)
981
+ owns the observation boundary and linear full-prefix replay cost.
982
+
983
+ Executing Tools can call optional `context.readToolResults()` to capture the same
984
+ feedback projection lazily. Runtime supplies it even without named-state readers;
985
+ other hosts may omit it. Repeated reads within one invocation reuse a fixed prefix.
986
+ The current unfinished Tool result is excluded, and concurrent Tools may observe
987
+ different prefixes. The handle expires when the author callback settles. Invocation
988
+ and lease settlement join started reads even if unawaited; a read failure fails an
989
+ otherwise successful invocation. The returned snapshot remains immutable data.
990
+ This is a trusted Session-wide read, not a writer or read-modify-write transaction.
991
+
992
+ ## Context preparation
993
+
994
+ Register preparation with `ctx.context.around(key, callback)`. Each local key becomes
995
+ a stable internal hook identity and uses the native Context
996
+ `around(draft, scope, next)` contract. Selected Entry order followed by declaration
997
+ order determines nesting; it is recorded in the request binding evidence. The scope
998
+ adds lease-owned `sessionId` and `runId` to Context's turn/request identities and
999
+ cancellation signal. These identities support partitioning, not command authority.
1000
+
1001
+ Plugin scope also carries optional `visibleToolNames`: a captured view of
1002
+ the effective request Tool names. Sorbet Runtime supplies it after Host ceilings
1003
+ and temporary suppression, including visible Host Tools. Absence means unavailable,
1004
+ not an empty catalog; `[]` means no Tools. Use request-retained material for adaptive
1005
+ guidance, leaving fixed Prefix definitions unchanged. This observation grants no
1006
+ Tool permission; retries reuse prepared evidence rather than rerunning the Hook.
1007
+
1008
+ The [Context domain](../context/src/README.md#preparation) owns editable sources,
1009
+ request material and declared state readings, isolated single-use `next`, absorbing
1010
+ rejection and final owner-schema validation. Plugins uses that dispatcher rather
1011
+ than defining another Hook engine. Runtime nests the leased chain inside configured
1012
+ Host preparation Hooks. Published fixed Prefix authority remains immutable.
1013
+ Host Hooks must not use Runtime's reserved bridge ID `sorbet:plugin-bindings`.
1014
+
1015
+ Replacement captures new callbacks for new leases; an in-progress request and its
1016
+ physical retries retain the old callbacks and prepared evidence. Disposal joins
1017
+ the whole preparation, including unawaited downstream work, before releasing the
1018
+ borrow. Installed package denial rejects new Hook entries but cannot stop code
1019
+ already executing. Snapshots reconstruct without running historical Hooks; source
1020
+ provenance is trusted attribution, not proof that a particular Hook produced it.
1021
+ See [ADR-0078](../../docs/adr/0078-leased-context-preparation.md).
1022
+
1023
+ ## Fixed Prefix
1024
+
1025
+ Register fixed text through the Context domain:
1026
+
1027
+ ```ts
1028
+ import type { PluginApply } from '@sorbetai/plugins';
1029
+
1030
+ const reviewer: PluginApply<null> = (ctx) => {
1031
+ ctx.context.prefix('rules', 'Explain findings with evidence.');
1032
+ };
1033
+ ```
1034
+
1035
+ Each nonempty local key generates a stable section identity and is unique within this Entry.
1036
+ Preparation captures text and sorts by ID; author mutation cannot change the captured
1037
+ definition. Changing definitions requires a new registration, adopted at the next
1038
+ logical request. Retries and rebase reuse their captured Prefix. Dynamic progress or
1039
+ Session-specific values belong in named state, not in an every-request Prefix callback.
1040
+
1041
+ Runtime projects the exact leased definitions into plugin extension sources after
1042
+ Host configured Prefix sources. Existing Host contributor placement remains unchanged.
1043
+ ContextManager owns XML escaping, rendering and revisions. Source identities
1044
+ derive from scope and internal contribution identity; Host conflicts fail before dispatch. A fork
1045
+ keeps an identical inherited source once; conflicting current and inherited definitions
1046
+ fail instead of implicitly replacing the parent snapshot. Removing a current contribution
1047
+ does not remove a fork's inherited snapshot.
1048
+
1049
+ Removal updates the next live Prefix without rewriting historical requests or emitting
1050
+ state tombstones. Request evidence validates the exact text against its request view;
1051
+ restart uses current declarations without comparing them with historical requests. The text is persisted,
1052
+ so it must not contain secrets. It grants no Tool permissions or Host authority.
1053
+
1054
+ This static contribution adds no reader, `next`, template engine, priority mechanism,
1055
+ resource dispatcher or mutable message API. See
1056
+ [ADR-0069](../../docs/adr/0069-published-plugin-prefix.md).
1057
+
1058
+ ## Input transformation
1059
+
1060
+ Register input handling with `ctx.input.transform(key, callback)`. Each callback is
1061
+ `async transform(input, { sessionId, runId, source, mode, signal })`. Handlers run in
1062
+ contribution-ID order, independently of Entry selection order. The input is a detached
1063
+ draft: a nonempty string or nonempty array of text/image blocks. Return the effective
1064
+ input; every handler result is validated and copied before the next handler sees it.
1065
+ The context's identities and source are immutable, captured from the admitted Run.
1066
+
1067
+ Sorbet Session first persists original input in `run.accepted`, then acquires its
1068
+ first request view and transforms once. `run.input.transformed` records the original
1069
+ message ID, complete request view and effective content before Context preparation or
1070
+ model dispatch. Model conversation projections use that content; the admitted-input
1071
+ view retains the original. Neither admission identity nor permissions can be rewritten.
1072
+ Physical retries, compaction, duplicate admission and historical reconstruction reuse
1073
+ the result without executing authors again. A new Run can adopt a new request view.
1074
+
1075
+ For steering and follow-up, Pi owns queue ordering and injection. Sorbet waits until
1076
+ Pi injects its custom message, appends original `run.input.accepted`, acknowledges
1077
+ admission, then transforms with the request view leased at injection. The effective
1078
+ result is persisted before updating the Sorbet-owned wrapper consumed by Pi. A
1079
+ receipt means original input was admitted, not that transformation succeeded. Inputs
1080
+ never injected remain unaccepted. `mode` is `initial`, `steer` or `followUp`; a new
1081
+ logical request may adopt a replacement, but no previous input is transformed again.
1082
+
1083
+ Thrown errors and invalid output fail the Run before model dispatch. Cancellation
1084
+ uses the existing cancelled outcome and retains abort-ignoring handlers until actual
1085
+ settlement. Missing durable transformation evidence rejects that input's first consuming model request.
1086
+ An unfinished Run after a crash is not automatically replayed to finish its transform.
1087
+
1088
+ Internal context events bypass input transformation. The contract exposes no `next`, `handled`, Session command, mutable
1089
+ history or Journal writer. Trusted callbacks can still perform ambient effects; this
1090
+ API does not separately authorize or journal them. Managed callbacks honor current Package denial. See
1091
+ [ADR-0073](../../docs/adr/0073-queued-input-transformation.md) and the
1092
+ [Session regression](../runtime/tests/session/model-session.test.ts) for the native
1093
+ `?quick` consumer, retry/reopen evidence and failure boundaries. This is not Pi's
1094
+ complete `input` compatibility contract.
1095
+
1096
+ ## Session behaviors
1097
+
1098
+ `ctx.session.behavior()` registers a schema, reducer and view projection. Runtime
1099
+ owns serialized commits and invocation-scoped command dispatch. Native Package
1100
+ replacement and restart use current Composition resources and request borrows. The
1101
+ [behavior contract](./SESSION-BEHAVIORS.md) owns lifecycle and Host semantics;
1102
+ [Plan mode](../../plugins/plan-mode/README.md) is the optional native consumer.
1103
+
1104
+ ## Request bindings and retirement
1105
+
1106
+ `platform.modelTools.acquire({ sessionId, runId, signal, deadline, toolNames? })`
1107
+ synchronously captures one request's callbacks and borrows their resource owners.
1108
+ The caller must dispose that lease after all admitted work settles. The optional Tool
1109
+ ceiling filters Tool declarations and callback bindings before capture, so inline
1110
+ Journal evidence contains only permitted Tools. It also restricts their borrows;
1111
+ other callback domains still retain their owners. Prefixes are copied data and need no resource borrow.
1112
+
1113
+ A lease has a unique `leaseId`, immutable `view` metadata and process-local Tool
1114
+ `bindingId`s. Bindings identify the Mount incarnation, registration generation and
1115
+ contribution. Replacing a callback creates a new binding; unchanged live instances
1116
+ retain their identity across unrelated registrations. Snapshot-owned indexes and captured
1117
+ declarations are reused; only the last Tool ceiling selection is cached per snapshot.
1118
+ There is no global model revision, archived
1119
+ catalog, install callback or executor lookup through history. An old binding can
1120
+ only execute through a live lease that captured it.
1121
+
1122
+ The model consumer validates duplicate names and contribution-domain constraints
1123
+ at acquisition. Strict mode rejects the request on conflicts while the Service
1124
+ graph remains active. `modelToolConflictPolicy: 'isolate'` excludes all conflicting
1125
+ Tools and serves the rest; `status().isolatedTools` reports their names. Removing a
1126
+ conflict fixes the next acquisition without a durable reconciliation command.
1127
+
1128
+ The deadline combines with caller and invocation cancellation. Disposal stops new
1129
+ calls and joins admitted callbacks, continuations and observation reads before
1130
+ releasing resource borrows. An abort-ignoring callback keeps its request open;
1131
+ close cannot pretend its resource use ended. `status().requests` reports live
1132
+ request borrows. `lease.behaviorSignal(name)` tracks that behavior registration and
1133
+ its owner, ancestors and Service dependencies for Host reviews. Unrelated graph
1134
+ or contribution changes leave the review open. Ordinary retirement does not cancel
1135
+ legal old Tool calls. See [review ordering](./SESSION-BEHAVIORS.md#ordering-permissions-and-lifetime).
1136
+
1137
+ A Tool's `context.ownTask(execute)` can transfer its captured resource borrow to
1138
+ caller-owned background work while that invocation is open and un-aborted. Current
1139
+ owner and Package checks still apply. The borrow ends only when the returned
1140
+ Promise settles, independently of normal lease disposal. The caller must own,
1141
+ cancel and join the actual task; this port does not supervise it or record an
1142
+ operation or Effect attempt.
1143
+
1144
+ ## Session evidence
1145
+
1146
+ Runtime acquires before Context preparation. Pi owns request, retry and Tool-batch
1147
+ mechanics. A logical step and its physical retries use the same lease and prepared
1148
+ input. The complete Tool batch settles before the next logical request acquires
1149
+ current capabilities. Hooks, state readers, transformations and Tool execution all
1150
+ use that request's captured callbacks.
1151
+
1152
+ The Session Journal stores inline `pluginBindings` with each request base, effective
1153
+ Tool declarations, Context evidence and explicit Host/Plugin execution origins.
1154
+ Stable declarations reuse a Session-local Base across leases. Each `model.requested`
1155
+ records its own `leaseId`; Base contents never grant execution or own a Scope.
1156
+ Permissions and `effect.requested` precede dispatch; terminal facts record the
1157
+ actual outcome. History reconstruction reads facts without running plugin code.
1158
+ Resource failure cannot rewrite a prior request or authorize replay of an effect.
1159
+
1160
+ Journal fact schema 3, JSONL frame 4 and Plugin SQLite schema 3 deliberately reject
1161
+ old formats while preserving the original files. The [Authority storage contract](./COMPOSITION.md#storage-uncertainty-and-restart)
1162
+ defines checkpoint recovery and store replacement. No online compatibility or historical executor restoration is provided.
1163
+
1164
+ ## Verification
1165
+
1166
+ `pnpm --filter @sorbetai/plugins test` covers graph convergence, local failure,
1167
+ exclusive replacement, resource drain, durable storage and fresh-process rebuild.
1168
+ [Request borrowing](./tests/model-consumer.test.ts) verifies executor capture and
1169
+ failure closure. [Runtime Sessions](../runtime/tests/session/model-session.test.ts)
1170
+ exercise Pi retries, Tool batches, permissions and Journal evidence. The installed
1171
+ [NodeAgent](../node-agent/tests/fixtures/installed-workspace.ts) and
1172
+ [ACP](../acp/tests/fixtures/installed-composition.ts) journeys use the same protocol.
1173
+
1174
+ Measure request sampling with `pnpm --filter @sorbetai/plugins exec node --expose-gc --import tsx benchmarks/request-acquisition.ts`.
1175
+ The benchmark uses 100, 500 and 1,000 mounts, both full and single-Tool ceilings,
1176
+ and 1,000 short requests per case after warmup. Acquisition includes contribution
1177
+ collection, closure wrapping, complete View capture, validation and resource borrowing;
1178
+ release is timed separately. Each 100-request batch reports post-GC heap and RSS,
1179
+ and asserts that no request borrow remains. RSS includes allocator retention;
1180
+ post-GC heap trends are evidence to inspect, not a proof of leak freedom.