operon-agents-core 0.1.0-alpha.5 → 0.1.0-alpha.6

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.
@@ -37,7 +37,12 @@ export class Runner {
37
37
  return this.withLease(opts, async (lease) => {
38
38
  const { session, owned } = await this.acquireSession(opts, undefined, lease);
39
39
  try {
40
- return await session.withRunLock(() => this.execute(agent, input, opts, session));
40
+ return await session.withRunLock(() => {
41
+ // Cancelled while queued behind another run: leave without touching the session —
42
+ // no reconcile, no context replay, no `agent.started` on the log.
43
+ opts?.signal?.throwIfAborted();
44
+ return this.execute(agent, input, opts, session);
45
+ });
41
46
  }
42
47
  finally {
43
48
  if (owned)
@@ -75,9 +80,18 @@ export class Runner {
75
80
  // One-shot pull sessions emit straight to `pull` (the bus IS the iterable). For a
76
81
  // shared session, subscribe `pull` to its bus so we never replace the channel (Invariant 4).
77
82
  const { session, owned } = await this.acquireSession(opts, pull, lease);
78
- const unsub = owned ? undefined : session.events.subscribe((ev) => void pull.emit(ev));
83
+ let unsub;
79
84
  try {
80
- return await session.withRunLock(() => this.execute(agent, input, opts, session));
85
+ return await session.withRunLock(() => {
86
+ // Cancelled while queued behind another run: leave without touching the session —
87
+ // no reconcile, no context replay, no `agent.started` on the log.
88
+ opts?.signal?.throwIfAborted();
89
+ // Subscribe only now, holding the lock: subscribing while queued would hand this
90
+ // stream the tail of the run ahead of it (its inputs and answers) before its own.
91
+ if (!owned)
92
+ unsub = session.events.subscribe((ev) => void pull.emit(ev));
93
+ return this.execute(agent, input, opts, session);
94
+ });
81
95
  }
82
96
  finally {
83
97
  unsub?.();
@@ -119,6 +133,7 @@ export class Runner {
119
133
  await session.reconcileSubagents();
120
134
  try {
121
135
  return await session.withRunLock(async () => {
136
+ baseOpts?.signal?.throwIfAborted();
122
137
  const store = session.store;
123
138
  if (!store)
124
139
  throw new Error("Cannot resume an interrupted run without a durable session store.");
@@ -192,9 +207,17 @@ export class Runner {
192
207
  // A one-shot pull stream IS the session's event bus (Invariant 4); it wins over the hook's.
193
208
  if (eventsOverride !== undefined)
194
209
  scope.register(T.Events, eventsOverride, { owned: false });
195
- const capabilities = (await this.config.session?.(scope, { sessionId: opts?.sessionId })) ?? [];
196
- const session = await Session.open(scope, { capabilities });
197
- return { session, owned: true };
210
+ try {
211
+ const capabilities = (await this.config.session?.(scope, { sessionId: opts?.sessionId })) ?? [];
212
+ const session = await Session.open(scope, { capabilities });
213
+ return { session, owned: true };
214
+ }
215
+ catch (error) {
216
+ // The scope is ours: a hook or open that fails must not leave it (and whatever it already
217
+ // registered — a provision, an MCP connection) hanging off the runner's scope.
218
+ await scope.close().catch(() => undefined);
219
+ throw error;
220
+ }
198
221
  }
199
222
  /** Resolve the durable conversation owner by following committed handoffs from `main`. */
200
223
  async resolveConversationHead(session, rootAgent) {
@@ -163,6 +163,8 @@ export declare class Session implements SessionPort {
163
163
  private thinkingOverride?;
164
164
  private openedCapabilities;
165
165
  private isOpen;
166
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
167
+ private closing;
166
168
  private runChain;
167
169
  private readonly pendingDiagnostics;
168
170
  private lastContextBreakdown?;
@@ -343,9 +345,11 @@ export declare class Session implements SessionPort {
343
345
  /**
344
346
  * Close the session: flush telemetry and the store, then close the scope — which disposes
345
347
  * every capability provision in reverse order (each under a deadline) and finally the
346
- * session's own infrastructure. Idempotent.
348
+ * session's own infrastructure. Every call returns the SAME promise, so a second caller
349
+ * (or the facade above) waits for the teardown instead of returning while it is still running.
347
350
  */
348
351
  close(): Promise<void>;
352
+ private runClose;
349
353
  /** Public URL for a port inside the machine, or undefined when the backend can't expose one. */
350
354
  resolveExposedPort(port: number): Promise<string | undefined>;
351
355
  }
@@ -87,6 +87,8 @@ export class Session {
87
87
  thinkingOverride;
88
88
  openedCapabilities = [];
89
89
  isOpen = false;
90
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
91
+ closing;
90
92
  runChain = Promise.resolve();
91
93
  pendingDiagnostics = [];
92
94
  // Most-recent per-turn context-window breakdown, stamped by the Runner at each turn boundary.
@@ -742,11 +744,16 @@ export class Session {
742
744
  /**
743
745
  * Close the session: flush telemetry and the store, then close the scope — which disposes
744
746
  * every capability provision in reverse order (each under a deadline) and finally the
745
- * session's own infrastructure. Idempotent.
747
+ * session's own infrastructure. Every call returns the SAME promise, so a second caller
748
+ * (or the facade above) waits for the teardown instead of returning while it is still running.
746
749
  */
747
- async close() {
748
- if (!this.isOpen)
749
- return;
750
+ close() {
751
+ if (this.closing !== undefined)
752
+ return this.closing;
753
+ this.closing = this.isOpen ? this.runClose() : Promise.resolve();
754
+ return this.closing;
755
+ }
756
+ async runClose() {
750
757
  this.isOpen = false;
751
758
  this.systemPromptContexts.clear();
752
759
  this.unsubscribeTracing?.();
@@ -1,5 +1,5 @@
1
1
  export { Scope, ServiceUnavailableError, deadHandle, isProbeProperty } from "./scope.ts";
2
- export type { RegisterOptions, CloseOptions, ServiceUnavailableReason, Below } from "./scope.ts";
2
+ export type { RegisterOptions, CloseOptions, ServiceUnavailableReason, Below, ScopeState } from "./scope.ts";
3
3
  export { token, SCOPE_ORDER, resetTokenDeclarationsForTest } from "./token.ts";
4
4
  export type { Token, ScopeKind } from "./token.ts";
5
5
  export { T } from "./tokens.ts";
@@ -50,6 +50,7 @@ export interface CloseOptions {
50
50
  /** Where a dispose failure/timeout goes. Default: the scope's `warn`. */
51
51
  readonly onDisposeError?: (name: string, error: unknown) => void;
52
52
  }
53
+ export type ScopeState = "open" | "closing" | "closed";
53
54
  export declare class Scope<K extends ScopeKind = ScopeKind> {
54
55
  readonly kind: K;
55
56
  readonly parent: Scope | undefined;
@@ -62,11 +63,16 @@ export declare class Scope<K extends ScopeKind = ScopeKind> {
62
63
  private readonly ops;
63
64
  private readonly children;
64
65
  private readonly warn;
65
- private _closed;
66
+ /** open → closing (the one `close()` in flight) → closed. Never goes back. */
67
+ private _state;
68
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
69
+ private closing;
66
70
  constructor(kind: K, parent?: Scope, options?: {
67
71
  readonly warn?: (message: string) => void;
68
72
  });
73
+ /** Not open: closing or closed. `register`/`provide`/`child` throw from here on. */
69
74
  get closed(): boolean;
75
+ get state(): ScopeState;
70
76
  /** Open a nested scope. Tiers only go down: harness → workspace | session, workspace → session. */
71
77
  child<C extends Below<K>>(kind: C): Scope<C>;
72
78
  /** Register a built instance under a token. Duplicate names fail closed — a scope that wants
@@ -116,10 +122,15 @@ export declare class Scope<K extends ScopeKind = ScopeKind> {
116
122
  unregister<T>(tok: Token<T, K>, options?: CloseOptions): Promise<void>;
117
123
  /**
118
124
  * Tear the scope down: children first (newest first), then this scope's entries in reverse
119
- * registration order. Idempotent. Afterwards `register`/`provide`/`child` throw; `get` still
120
- * reads the parent chain. Parents are never touched.
125
+ * registration order. Every call — concurrent or later — returns the SAME promise, so a parent
126
+ * closing while a child's close is still in flight waits for that close instead of skipping it
127
+ * and pulling its own resources out from under the child's disposers. Entering `closing` stops
128
+ * pending defaults from materializing (a disposer asking for one gets "missing"), so nothing
129
+ * new can appear behind the teardown's back. Afterwards `register`/`provide`/`child` throw;
130
+ * `get` still reads the parent chain. Parents are never touched.
121
131
  */
122
132
  close(options?: CloseOptions): Promise<void>;
133
+ private runClose;
123
134
  private lookup;
124
135
  private invoke;
125
136
  private enqueueOp;
@@ -60,15 +60,22 @@ export class Scope {
60
60
  ops = new Map();
61
61
  children = new Set();
62
62
  warn;
63
- _closed = false;
63
+ /** open → closing (the one `close()` in flight) → closed. Never goes back. */
64
+ _state = "open";
65
+ /** The one close in flight (or finished): every `close()` call returns THIS promise. */
66
+ closing;
64
67
  constructor(kind, parent, options = {}) {
65
68
  this.kind = kind;
66
69
  this.parent = parent;
67
70
  this.warn = options.warn ?? parent?.warn ?? ((message) => console.warn(`[scope] ${message}`));
68
71
  parent?.children.add(this);
69
72
  }
73
+ /** Not open: closing or closed. `register`/`provide`/`child` throw from here on. */
70
74
  get closed() {
71
- return this._closed;
75
+ return this._state !== "open";
76
+ }
77
+ get state() {
78
+ return this._state;
72
79
  }
73
80
  /** Open a nested scope. Tiers only go down: harness → workspace | session, workspace → session. */
74
81
  child(kind) {
@@ -222,27 +229,42 @@ export class Scope {
222
229
  }
223
230
  /**
224
231
  * Tear the scope down: children first (newest first), then this scope's entries in reverse
225
- * registration order. Idempotent. Afterwards `register`/`provide`/`child` throw; `get` still
226
- * reads the parent chain. Parents are never touched.
232
+ * registration order. Every call — concurrent or later — returns the SAME promise, so a parent
233
+ * closing while a child's close is still in flight waits for that close instead of skipping it
234
+ * and pulling its own resources out from under the child's disposers. Entering `closing` stops
235
+ * pending defaults from materializing (a disposer asking for one gets "missing"), so nothing
236
+ * new can appear behind the teardown's back. Afterwards `register`/`provide`/`child` throw;
237
+ * `get` still reads the parent chain. Parents are never touched.
227
238
  */
228
- async close(options = {}) {
229
- if (this._closed)
230
- return;
231
- this._closed = true;
232
- for (const child of [...this.children].reverse())
233
- await child.close(options);
234
- this.children.clear();
235
- for (const name of [...this.order].reverse()) {
236
- await this.unregister({ name, scope: this.kind }, options);
237
- }
239
+ close(options = {}) {
240
+ if (this.closing !== undefined)
241
+ return this.closing;
242
+ this._state = "closing";
238
243
  this.providers.clear();
239
- this.parent?.children.delete(this);
244
+ this.closing = this.runClose(options);
245
+ return this.closing;
246
+ }
247
+ async runClose(options) {
248
+ try {
249
+ for (const child of [...this.children].reverse())
250
+ await child.close(options);
251
+ this.children.clear();
252
+ for (const name of [...this.order].reverse()) {
253
+ await this.unregister({ name, scope: this.kind }, options);
254
+ }
255
+ }
256
+ finally {
257
+ this._state = "closed";
258
+ this.parent?.children.delete(this);
259
+ }
240
260
  }
241
261
  lookup(name) {
242
262
  const local = this.table.get(name);
243
263
  if (local !== undefined)
244
264
  return local;
245
- const provider = this.providers.get(name);
265
+ // Once closing, no default materializes: a disposer that first touches a lazy service
266
+ // during teardown must not create an instance the teardown snapshot will never dispose.
267
+ const provider = this._state === "open" ? this.providers.get(name) : undefined;
246
268
  if (provider !== undefined) {
247
269
  this.providers.delete(name);
248
270
  const entry = entryOf(provider.create(this), provider.options);
@@ -344,8 +366,8 @@ export class Scope {
344
366
  }
345
367
  }
346
368
  assertOpen() {
347
- if (this._closed)
348
- throw new Error(`${this.kind} scope is closed`);
369
+ if (this._state !== "open")
370
+ throw new Error(`${this.kind} scope is ${this._state}`);
349
371
  }
350
372
  assertTier(tok) {
351
373
  if (tok.scope !== this.kind) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "operon-agents-core",
3
- "version": "0.1.0-alpha.5",
3
+ "version": "0.1.0-alpha.6",
4
4
  "description": "Internal engine for operon-agents. Prefer operon-agents for application code.",
5
5
  "type": "module",
6
6
  "engines": {