operon-agents 0.1.0-alpha.2 → 0.1.0-alpha.4

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.
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { ServiceUnavailableError, isProbeProperty } from "./services.js";
3
- import { tagToolSource } from "operon-agents-core";
3
+ import { tagToolSource, T } from "operon-agents-core";
4
4
  /** Decision points block the loop, so they get room to do real work (network, subprocess). */
5
5
  const DECISION_TIMEOUT_MS = 30_000;
6
6
  /** Observers must not become latency: a slow one is dropped, not waited on. */
@@ -16,7 +16,7 @@ export class ExtensionRuntime {
16
16
  definitions;
17
17
  handlers = new Map();
18
18
  tools = new Map();
19
- /** Stable reference: `extensionsCapability` hands this array to the assembler, and `setup`
19
+ /** Stable reference: `extensionsCapability` hands this array to the assembler, and `session`
20
20
  * (which runs at openSession, before any run assembles) fills it in place. */
21
21
  injectors = [];
22
22
  /** Slash commands by normalized name — surfaced to the session's registry via the
@@ -28,10 +28,10 @@ export class ExtensionRuntime {
28
28
  * memoized log read — zero extra traversal) + everything recorded this session. */
29
29
  recordSnapshot;
30
30
  recordWrites = new Map();
31
- /** Per-extension teardown: setup's cleanup + every registration, undone in reverse. */
31
+ /** Per-extension teardown: session()'s cleanup + every registration, undone in reverse. */
32
32
  scopes = new Map();
33
33
  /** Extensions whose contributions are currently honored. An id leaves on detach (and on
34
- * setup failure), which turns every `actions`/`api` closure the extension still holds
34
+ * session() failure), which turns every `actions`/`api` closure the extension still holds
35
35
  * into a warn-and-noop — a detached extension must not keep steering the session. */
36
36
  live = new Set();
37
37
  /** Changes wait here until a quiet point: mid-run requests apply at the run's stop
@@ -40,6 +40,7 @@ export class ExtensionRuntime {
40
40
  /** Serializes flushes so concurrent attach/detach apply strictly in submission order. */
41
41
  flushChain = Promise.resolve();
42
42
  memoryState = new Map();
43
+ /** The session binding: its scope (machine, store, events, steer, log reader, controls) + id + signal. */
43
44
  session;
44
45
  run;
45
46
  /** The conversation shard the in-flight decision point belongs to; backs `actions.record`. */
@@ -52,7 +53,7 @@ export class ExtensionRuntime {
52
53
  /** Harness reach. Absent when the capability is built standalone (bare Runner / tests). */
53
54
  host;
54
55
  /** This session's per-session extension arguments, by extension id. A value of `false` means
55
- * "skip this extension for this session"; any other value is passed to `setup` as `params`. */
56
+ * "skip this extension for this session"; any other value is passed to `session` as `params`. */
56
57
  params;
57
58
  constructor(definitions, host, params = {}) {
58
59
  this.host = host;
@@ -124,10 +125,10 @@ export class ExtensionRuntime {
124
125
  // Hot attach / detach — host API, applied at the next quiet point
125
126
  // ==========================================================================
126
127
  /**
127
- * Add an extension to the live session. Resolves once its `setup` has run and its
128
+ * Add an extension to the live session. Resolves once its `session` has run and its
128
129
  * contributions are in place — with no run in flight that is immediately; mid-run it is
129
130
  * the current run's stop boundary, so an in-flight turn never sees its registry change.
130
- * Rejects on duplicate/empty id or when `setup` throws.
131
+ * Rejects on duplicate/empty id or when `session` throws.
131
132
  */
132
133
  attach(definition) {
133
134
  return this.submit({ kind: "attach", definition });
@@ -198,7 +199,7 @@ export class ExtensionRuntime {
198
199
  throw new Error(`duplicate extension id "${definition.id}"`);
199
200
  }
200
201
  this.definitions.push(definition);
201
- // Not open yet: `open()` will run setup with everything else.
202
+ // Not open yet: `open()` will run session() with everything else.
202
203
  if (!this.session)
203
204
  return;
204
205
  const ok = await this.setupExtension(definition);
@@ -206,7 +207,7 @@ export class ExtensionRuntime {
206
207
  const index = this.definitions.findIndex((existing) => existing.id === definition.id);
207
208
  if (index >= 0)
208
209
  this.definitions.splice(index, 1);
209
- throw new Error(`extension "${definition.id}" setup failed`);
210
+ throw new Error(`extension "${definition.id}" session() failed`);
210
211
  }
211
212
  for (const registered of [...this.handlersFor("session.start")]) {
212
213
  if (registered.extensionId !== definition.id)
@@ -242,17 +243,19 @@ export class ExtensionRuntime {
242
243
  if (this.session)
243
244
  await this.logChange("detached", id);
244
245
  }
245
- /** Runs one extension's `setup` and files its scope. Failure ⇒ skipped, contributions undone. */
246
+ /** Runs one extension's `session` and files its scope. Failure ⇒ skipped, contributions undone. */
246
247
  async setupExtension(definition) {
247
248
  const params = this.params[definition.id];
248
- // A `create`-bearing definition reaches a session only after the harness ran its `create`
249
- // and registered the result under the id. Not registered ⇒ it was handed to a session
250
- // directly instead of being registered — a programming error, so it throws rather than
251
- // being skipped.
252
- if (definition.create !== undefined && this.host?.services?.has(definition.id) !== true) {
253
- throw new Error(`extension "${definition.id}" has a create half but no service "${definition.id}" is registered — its create never ran. Register it in createHarness({ extensions }) or load it from extensionDir; a definition with create cannot be handed to a session directly`);
249
+ // A definition with a shared half reaches a session only after that half ran — the harness
250
+ // ran `harness` once, or this session's workspace ran `workspace` — and registered the result
251
+ // under the id where the session's scope chain finds it. Not registered ⇒ it was handed to a
252
+ // session directly instead of being registered — a programming error, so it throws rather
253
+ // than being skipped.
254
+ const sharedHalf = definition.harness !== undefined || definition.workspace !== undefined;
255
+ if (sharedHalf && this.host?.services?.has(definition.id) !== true) {
256
+ throw new Error(`extension "${definition.id}" has a shared half but no service "${definition.id}" is reachable from this session — its harness/workspace half never ran. Register it in createHarness({ extensions }) or load it from extensionDir; a definition with a shared half cannot be handed to a session directly`);
254
257
  }
255
- const shared = definition.create !== undefined ? this.serviceHandle(definition.id, definition.id) : undefined;
258
+ const shared = sharedHalf ? this.serviceHandle(definition.id, definition.id) : undefined;
256
259
  const registrations = [];
257
260
  this.live.add(definition.id);
258
261
  try {
@@ -264,7 +267,7 @@ export class ExtensionRuntime {
264
267
  throw new Error(`uses "${name}": no such service is registered`);
265
268
  services[name] = this.serviceHandle(definition.id, name);
266
269
  }
267
- const teardown = await definition.setup(this.apiFor(definition, registrations), { shared, params, services });
270
+ const teardown = await definition.session(this.apiFor(definition, registrations), { shared, params, services });
268
271
  this.scopes.set(definition.id, async () => {
269
272
  if (teardown)
270
273
  await teardown();
@@ -277,7 +280,7 @@ export class ExtensionRuntime {
277
280
  this.live.delete(definition.id);
278
281
  for (const dispose of [...registrations].reverse())
279
282
  dispose();
280
- await this.warn(definition.id, `setup failed; extension skipped: ${messageOf(error)}`);
283
+ await this.warn(definition.id, `session() failed; extension skipped: ${messageOf(error)}`);
281
284
  return false;
282
285
  }
283
286
  }
@@ -286,7 +289,7 @@ export class ExtensionRuntime {
286
289
  * capability timeline. Rides the `custom` record type — audit-only, ignored by reducers.
287
290
  */
288
291
  async logChange(kind, extensionId) {
289
- const store = this.session?.store;
292
+ const store = this.session?.scope.get(T.Store);
290
293
  if (!store)
291
294
  return;
292
295
  try {
@@ -634,8 +637,8 @@ export class ExtensionRuntime {
634
637
  void this.warn(definition.id, "onEvent() ignored: extension is detached.");
635
638
  return () => undefined;
636
639
  }
637
- // `setup` runs inside `open`, so the session context is already in place.
638
- const sink = this.session?.events;
640
+ // `session` runs inside `open`, so the session context is already in place.
641
+ const sink = this.session?.scope.get(T.Events);
639
642
  if (sink === undefined)
640
643
  return () => undefined;
641
644
  const dispose = sink.subscribe((event) => {
@@ -721,7 +724,7 @@ export class ExtensionRuntime {
721
724
  void this.warn(definition.id, `emitEvent("${name}") ignored: no open session.`);
722
725
  return;
723
726
  }
724
- void session.events.emit({
727
+ void session.scope.get(T.Events)?.emit({
725
728
  address: "main",
726
729
  sessionId: session.sessionId,
727
730
  type: "extension",
@@ -749,9 +752,9 @@ export class ExtensionRuntime {
749
752
  return [...snapshot, ...writes];
750
753
  },
751
754
  state: {
752
- get: (key) => this.stateFor(definition.id, this.session?.store).get(key),
753
- set: (key, value) => this.stateFor(definition.id, this.session?.store).set(key, value),
754
- delete: (key) => this.stateFor(definition.id, this.session?.store).delete(key),
755
+ get: (key) => this.stateFor(definition.id, this.session?.scope.get(T.Store)).get(key),
756
+ set: (key, value) => this.stateFor(definition.id, this.session?.scope.get(T.Store)).set(key, value),
757
+ delete: (key) => this.stateFor(definition.id, this.session?.scope.get(T.Store)).delete(key),
755
758
  },
756
759
  actions: this.actionsFor(definition.id),
757
760
  };
@@ -942,7 +945,7 @@ export class ExtensionRuntime {
942
945
  * schema untouched. `source` names the extension so a fold can attribute the message.
943
946
  */
944
947
  enqueue(extensionId, content, channel, metadata) {
945
- const bus = this.run?.steer ?? this.session?.steer;
948
+ const bus = this.session?.scope.get(T.Steer);
946
949
  if (!bus) {
947
950
  void this.warn(extensionId, `${channel === "steering" ? "steer" : "followUp"}() ignored: no steer bus.`);
948
951
  return undefined;
@@ -955,7 +958,7 @@ export class ExtensionRuntime {
955
958
  });
956
959
  }
957
960
  controls() {
958
- return this.run?.controls ?? this.session?.controls;
961
+ return this.run?.controls ?? this.session?.scope.get(T.SessionControls);
959
962
  }
960
963
  /**
961
964
  * Host-backed action wrapper. Rejects (rather than silently resolving to something fake) when
@@ -975,26 +978,28 @@ export class ExtensionRuntime {
975
978
  // ==========================================================================
976
979
  sessionContext(extensionId) {
977
980
  const session = this.requireSession();
981
+ const store = session.scope.get(T.Store);
978
982
  return {
979
983
  extensionId,
980
984
  sessionId: session.sessionId,
981
985
  signal: session.signal,
982
- machine: session.machine,
983
- store: session.store,
984
- state: this.stateFor(extensionId, session.store),
986
+ machine: session.scope.require(T.Machine),
987
+ store,
988
+ state: this.stateFor(extensionId, store),
985
989
  actions: this.actionsFor(extensionId),
986
990
  };
987
991
  }
988
992
  eventContext(extensionId, origin) {
989
993
  const session = this.requireSession();
994
+ const store = session.scope.get(T.Store);
990
995
  return {
991
996
  extensionId,
992
997
  sessionId: session.sessionId,
993
998
  address: origin.address ?? "main",
994
999
  signal: origin.signal,
995
- machine: this.run?.machine ?? session.machine,
996
- store: session.store,
997
- state: this.stateFor(extensionId, session.store),
1000
+ machine: session.scope.require(T.Machine),
1001
+ store,
1002
+ state: this.stateFor(extensionId, store),
998
1003
  actions: this.actionsFor(extensionId),
999
1004
  };
1000
1005
  }
@@ -1006,7 +1011,8 @@ export class ExtensionRuntime {
1006
1011
  if (this.recordSnapshot !== undefined)
1007
1012
  return this.recordSnapshot;
1008
1013
  const buckets = new Map();
1009
- const log = this.session?.logRecords !== undefined ? await this.session.logRecords() : [];
1014
+ const reader = this.session?.scope.get(T.SessionLog);
1015
+ const log = reader !== undefined ? await reader() : [];
1010
1016
  for (const record of log) {
1011
1017
  if (record.type !== "custom")
1012
1018
  continue;
@@ -1071,7 +1077,7 @@ export class ExtensionRuntime {
1071
1077
  return;
1072
1078
  this.reportingWarning = true;
1073
1079
  try {
1074
- await session.events.emit({
1080
+ await session.scope.get(T.Events)?.emit({
1075
1081
  type: "warning",
1076
1082
  message: `[extension ${extensionId}] ${message}`,
1077
1083
  address: "main",
@@ -1,85 +1,92 @@
1
1
  /**
2
- * Process-level service registry with handle indirection — the substrate for hot-swapping
3
- * shared instances (design: docs/architecture.md §5.5).
2
+ * Extension services, by NAME, over the {@link Scope} tree.
4
3
  *
5
- * Consumers never hold a service instance. `handle()` returns a stable Proxy that resolves
6
- * the CURRENT table entry on every method call and holds a lease for exactly that call, so
7
- * replacing a provider is a registry-local act — swap the entry, drain the old instance's
8
- * leases, dispose it — with no session participation at all. The invariant this file exists
9
- * to keep: at any moment only one generation of a service is being handed out.
4
+ * Framework objects are addressed by typed tokens (`T.Machine`, `T.Goal`, …). Extension
5
+ * services are the one place a string is the natural key: an extension is loaded by its id
6
+ * (from a file, or by value), publishes its shared half's result under that id, and other
7
+ * extensions name it in `uses`. This facade maps those ids onto tokens, so extension services
8
+ * live in the same scopes — same lease / drain / replace machinery, same teardown order — as
9
+ * everything else the harness owns (design: docs/architecture.md §5.5, §5.7).
10
+ *
11
+ * A service lives at ONE tier, decided by which shared half produced it: a `harness` half's
12
+ * result sits in the harness scope (one per process), a `workspace` half's in each workspace
13
+ * scope (one per key). The registry remembers which names are workspace-tier — the harness
14
+ * scope cannot answer that for itself — and resolves a name FROM a given scope (`hasFrom` /
15
+ * `handleFrom`), so a session reaches either tier by walking up its own chain.
10
16
  *
11
17
  * Handles expose METHODS ONLY. A method's return value must not carry the instance (no
12
18
  * `return this`, no objects closing over it) — that is the one leak the Proxy cannot stop.
13
19
  */
14
- export type ServiceUnavailableReason = "missing" | "draining";
15
- export declare class ServiceUnavailableError extends Error {
16
- readonly serviceName: string;
17
- readonly reason: ServiceUnavailableReason;
18
- constructor(serviceName: string, reason: ServiceUnavailableReason);
19
- }
20
- export interface ServiceOptions {
21
- /** Absent/false = `replace()` rejects; swapping this service means restarting the process. */
22
- readonly replaceable?: boolean;
23
- /** Called once the old instance has drained. Default: call `instance.close()` when present. */
24
- readonly dispose?: (instance: unknown) => void | Promise<void>;
25
- }
20
+ import { Scope, ServiceUnavailableError, isProbeProperty, type RegisterOptions, type Token } from "operon-agents-core";
21
+ export { ServiceUnavailableError, isProbeProperty };
22
+ export type { ServiceUnavailableReason } from "operon-agents-core";
23
+ export type ServiceOptions = Pick<RegisterOptions, "replaceable" | "dispose">;
24
+ /** The tiers an extension service can live at — the tiers a shared half can run at. */
25
+ export type ServiceTier = "harness" | "workspace";
26
26
  export declare class ServiceRegistry {
27
- private readonly table;
28
- private readonly handles;
29
- /** Per-name op chain: concurrent replace/unregister serialize instead of interleaving. */
30
- private readonly ops;
31
- private readonly warn;
32
- constructor(options?: {
27
+ readonly scope: Scope<"harness">;
28
+ /** Names published at the workspace tier (a `workspace` half's id). Declared when the
29
+ * definition is registered, so a consumer's `uses` check passes before any workspace exists. */
30
+ private readonly workspaceTier;
31
+ /** Over the given harness scope, or a fresh standalone one (tests, thin hosts) — optionally
32
+ * with its own `warn` sink. */
33
+ constructor(scopeOrOptions?: Scope<"harness"> | {
33
34
  readonly warn?: (message: string) => void;
35
+ readonly scope?: Scope<"harness">;
34
36
  });
35
- /** Register a service under a unique name. Duplicate names fail closed — an extension that
36
- * wants to take over an existing name must go through `replace`, never shadow. */
37
+ /** Which tier `name` lives at: workspace once declared so, harness otherwise. */
38
+ tierOf(name: string): ServiceTier;
39
+ /** The token a name resolves through, at its tier. */
40
+ tokenFor<T = unknown>(name: string): Token<T>;
41
+ /** Register a service under a unique name in the harness scope. Duplicate names fail closed —
42
+ * an extension that wants to take over an existing name must go through `replace`, never shadow. */
37
43
  register(name: string, instance: unknown, options?: ServiceOptions): void;
44
+ /** Registered at either tier: in the harness scope, or declared workspace-tier (present in
45
+ * every workspace once it is composed). The registration check a `uses` consumer needs. */
38
46
  has(name: string): boolean;
39
47
  /**
40
- * The stable handle for a service — safe to take before the service is registered and to
41
- * keep across replaces. Property access requires a method (a non-function property throws:
42
- * replaceable services expose methods only); availability is judged at CALL time, so a
43
- * handle taken during early setup never explodes on mere property access.
48
+ * The stable handle for a HARNESS-tier service — safe to take before the service is registered
49
+ * and to keep across replaces; see `Scope.handle`. A workspace-tier name has no single instance
50
+ * to hand out: resolve it from a workspace or session scope (`handleFrom`, or the harness's
51
+ * `workspaceService`).
44
52
  */
45
53
  handle<T = unknown>(name: string): T;
46
- /**
47
- * Swap the provider behind a name. Atomic from the consumers' side: the very next handle
48
- * call lands on `next`; calls already in flight finish on the old instance, which is
49
- * disposed once its leases drain (or after `drainTimeoutMs`, logged, default 10s).
50
- *
51
- * `force` skips the `replaceable` gate. It exists for ONE caller — `harness.replaceExtension`,
52
- * where the extension that OWNS this service is being replaced along with it, inside the
53
- * barrier's quiet moment. The gate guards the other case (a host swapping an instance under a
54
- * live owner that never agreed to it), which is why it stays closed by default.
55
- */
54
+ /** Swap the provider behind a harness-tier name; see `Scope.replace`. */
56
55
  replace(name: string, next: unknown, options?: {
57
56
  readonly drainTimeoutMs?: number;
58
57
  readonly force?: boolean;
59
58
  }): Promise<void>;
60
- /**
61
- * Remove a service entirely (extension unload). Unlike `replace`, callers see "draining"
62
- * during the drain and "missing" after — there is deliberately no replaceable gate here:
63
- * unload is the host/loader tearing an extension's service down, not swapping code under consumers.
64
- */
59
+ /** Remove a harness-tier service entirely (extension unload); see `Scope.unregister`. */
65
60
  unregister(name: string, options?: {
66
61
  readonly drainTimeoutMs?: number;
67
62
  }): Promise<void>;
68
- private invoke;
69
- private enqueueOp;
70
- private retire;
71
- private drainLeases;
72
- private disposeOf;
63
+ /** Declare `name` workspace-tier: from now on it resolves through workspace scopes and `has`
64
+ * answers true (its definition is registered; each workspace composes its own instance). */
65
+ declareWorkspace(name: string): void;
66
+ /** Forget a workspace-tier declaration (its definition unloaded, or replaced by one without a
67
+ * `workspace` half). The caller unregisters the per-workspace instances. */
68
+ undeclareWorkspace(name: string): void;
69
+ /** Register one workspace's instance of a workspace-tier service. */
70
+ registerIn(scope: Scope<"workspace">, name: string, instance: unknown, options?: ServiceOptions): void;
71
+ /** Whether `scope` holds its own instance of `name` (not an ancestor's). */
72
+ hasLocalIn(scope: Scope<"workspace">, name: string): boolean;
73
+ /** Swap one workspace's instance; see `Scope.replace`. */
74
+ replaceIn(scope: Scope<"workspace">, name: string, next: unknown, options?: {
75
+ readonly drainTimeoutMs?: number;
76
+ readonly force?: boolean;
77
+ }): Promise<void>;
78
+ /** Remove one workspace's instance; see `Scope.unregister`. */
79
+ unregisterIn(scope: Scope<"workspace">, name: string, options?: {
80
+ readonly drainTimeoutMs?: number;
81
+ }): Promise<void>;
82
+ /** Registered at `name`'s tier somewhere up `scope`'s chain, and not draining. */
83
+ hasFrom(scope: Scope, name: string): boolean;
84
+ /** The stable handle for `name` as seen from `scope`: resolution walks up the chain on every
85
+ * call, so a session's handle lands on its workspace's instance or the harness's, whichever
86
+ * tier the name lives at. */
87
+ handleFrom<T = unknown>(scope: Scope, name: string): T;
73
88
  }
74
89
  /** A handle whose every call throws "missing" — handed to detached extensions and to
75
90
  * extensions on hosts that expose no services, mirroring the actions revocation collar. */
76
91
  export declare function deadServiceHandle<T = unknown>(name: string): T;
77
- /**
78
- * Properties a proxy must NEVER intercept with a throw or a fake method — the probe surface
79
- * generic JS pokes at (await → `then`, JSON.stringify → `toJSON` via the absent-property rule,
80
- * class checks → `prototype`/`constructor`, test/inspect utilities → `_`-prefixed, serializers →
81
- * numeric indices, symbols everywhere). Cordis's reflect layer converged on this exact list
82
- * over years of proxy bugs (`isSpecialProperty`); we adopt it wholesale.
83
- */
84
- export declare function isProbeProperty(prop: string | symbol): boolean;
85
92
  //# sourceMappingURL=services.d.ts.map