operon-agents-core 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.
Files changed (63) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +1 -1
  3. package/dist/agent/runner.d.ts +21 -15
  4. package/dist/agent/runner.js +23 -26
  5. package/dist/agent/session.d.ts +67 -73
  6. package/dist/agent/session.js +170 -174
  7. package/dist/agent/workflow/tool.js +8 -21
  8. package/dist/capabilities/assembler.d.ts +6 -4
  9. package/dist/capabilities/assembler.js +10 -5
  10. package/dist/capabilities/background/index.js +33 -26
  11. package/dist/capabilities/capability-state.d.ts +5 -7
  12. package/dist/capabilities/capability-state.js +6 -4
  13. package/dist/capabilities/capability.d.ts +52 -40
  14. package/dist/capabilities/compaction/index.js +5 -4
  15. package/dist/capabilities/goal/index.d.ts +1 -0
  16. package/dist/capabilities/goal/index.js +13 -6
  17. package/dist/capabilities/index.d.ts +3 -3
  18. package/dist/capabilities/index.js +2 -2
  19. package/dist/capabilities/plan/index.js +12 -6
  20. package/dist/capabilities/skills/flow-provider.js +3 -3
  21. package/dist/capabilities/skills/index.d.ts +12 -0
  22. package/dist/capabilities/skills/index.js +38 -24
  23. package/dist/capabilities/skills/registry.d.ts +3 -4
  24. package/dist/capabilities/skills/registry.js +4 -7
  25. package/dist/capabilities/skills/service.js +1 -1
  26. package/dist/capabilities/skills/skill-tool.d.ts +2 -0
  27. package/dist/capabilities/skills/skill-tool.js +1 -1
  28. package/dist/capabilities/task/index.js +11 -5
  29. package/dist/capabilities/todo/index.js +12 -6
  30. package/dist/capabilities/tool-provider.d.ts +3 -3
  31. package/dist/capabilities/user-hooks/index.js +22 -16
  32. package/dist/capabilities/workflow/index.d.ts +4 -2
  33. package/dist/capabilities/workflow/index.js +14 -7
  34. package/dist/commands/index.js +6 -4
  35. package/dist/events/events.d.ts +2 -1
  36. package/dist/events/publisher.js +1 -1
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.js +2 -1
  39. package/dist/internal.d.ts +2 -0
  40. package/dist/internal.js +2 -0
  41. package/dist/loop/steer.d.ts +2 -0
  42. package/dist/loop/steer.js +7 -2
  43. package/dist/mcp/capability.js +22 -17
  44. package/dist/mcp/filter.d.ts +2 -2
  45. package/dist/mcp/index.d.ts +1 -1
  46. package/dist/mcp/index.js +1 -1
  47. package/dist/mcp/manager.d.ts +45 -2
  48. package/dist/mcp/manager.js +162 -11
  49. package/dist/plugins/index.js +10 -4
  50. package/dist/scope/index.d.ts +7 -0
  51. package/dist/scope/index.js +4 -0
  52. package/dist/scope/scope.d.ts +143 -0
  53. package/dist/scope/scope.js +406 -0
  54. package/dist/scope/token.d.ts +29 -0
  55. package/dist/scope/token.js +29 -0
  56. package/dist/scope/tokens.d.ts +98 -0
  57. package/dist/scope/tokens.js +63 -0
  58. package/dist/store/index.d.ts +1 -1
  59. package/dist/store/origin.d.ts +9 -0
  60. package/dist/store/store.d.ts +6 -2
  61. package/dist/testing.d.ts +62 -0
  62. package/dist/testing.js +118 -0
  63. package/package.json +1 -1
@@ -2,7 +2,8 @@ import { FileFreshnessLedger } from "../tool/file-freshness.js";
2
2
  import { PermissionManager } from "../permission/manager.js";
3
3
  import { STAGED_POLICY_SLOTS } from "../permission/policies.js";
4
4
  import { NullMachine } from "../tool/machine-null.js";
5
- import { joinAddress, ListenerSink, SessionEventPublisher, } from "../events/index.js";
5
+ import { WorkflowManager } from "./workflow/manager.js";
6
+ import { joinAddress, ListenerSink, SessionEventPublisher } from "../events/index.js";
6
7
  import { envLogger, noopLogger } from "../logging/index.js";
7
8
  import { DEFAULT_ADDRESS } from "../store/index.js";
8
9
  import { eventSinkTracingBridge } from "../tracing/index.js";
@@ -11,6 +12,8 @@ import { readLog } from "../capabilities/capability-state.js";
11
12
  import { SteerBus, steerOriginToPromptOrigin } from "../loop/steer.js";
12
13
  import {} from "./subagent.js";
13
14
  import { SystemPromptContextCache } from "./instruction-context.js";
15
+ import { Scope } from "../scope/scope.js";
16
+ import { T } from "../scope/tokens.js";
14
17
  let CLOSE_TIMEOUT_MS = 5_000;
15
18
  /** store.flush persists data (vs. telemetry), so it gets a longer grace. The run journal
16
19
  * is already settled by settleRun's context.flush() before close — this is only a
@@ -30,41 +33,28 @@ export function newSessionId() {
30
33
  return `s${Date.now().toString(36)}-${sessionCounter.toString(36)}`;
31
34
  }
32
35
  /**
33
- * Thrown by `Session`'s capability-backed convenience methods when the capability they
34
- * wrap is not open on this session. Detect with `instanceof`; `capability` names the
35
- * missing one. The probe tier never throws — the getters (`session.cron`, `.goal`, …)
36
- * return `undefined` instead.
37
- */
38
- export class CapabilityMissingError extends Error {
39
- capability;
40
- constructor(capability) {
41
- super(`Session has no open "${capability}" capability.`);
42
- this.name = "CapabilityMissingError";
43
- this.capability = capability;
44
- }
45
- }
46
- /**
47
- * Capability access on a session has two tiers, one rule each:
48
- * - PROBE — the service getters (`session.cron`, `.goal`, `.plan`, `.backgroundManager`,
49
- * `.mcp`, …) return `undefined` when that capability is not open. Use these to feature-test.
50
- * - REQUIRE — the convenience wrappers (`createCronTask()`, `compact()`, `listSkills()`, …)
51
- * assume the capability and throw {@link CapabilityMissingError} when it is missing.
36
+ * Service access on a session has two tiers, one rule each:
37
+ * - PROBE — `session.get(T.X)` returns `undefined` when that service is not registered
38
+ * (the capability is not open). Use it to feature-test.
39
+ * - REQUIRE — `session.require(T.X)` and the convenience wrappers (`createCronTask()`,
40
+ * `compact()`, `listSkills()`, …) assume the service and throw `ServiceUnavailableError`
41
+ * when it is missing.
52
42
  * The only exceptions are list views documented as degrading to empty when the capability
53
43
  * is off (`listWorkflows`, `listSubagents`, `listMcpServers`) — views over durable state
54
44
  * that stay meaningful on a session opened without the capability.
45
+ *
46
+ * The session OWNS its scope: `close()` closes it, disposing every service registered there
47
+ * (capability provisions first, in reverse order, then the infrastructure).
55
48
  */
56
49
  export class Session {
57
50
  id;
51
+ /** The session-tier scope: every session-lived object, registered by the opener or by `open`. */
52
+ scope;
58
53
  machine;
59
54
  store;
60
55
  events;
61
56
  eventPublisher;
62
57
  responder;
63
- permissionOptions;
64
- /** Session-lived permission manager: one policy chain + approval memory +
65
- * mode for the whole session. Constructed in `openCapabilities` (needs capability policy
66
- * slots and the replayed log); runs reference it instead of building their own. */
67
- _permission;
68
58
  steer;
69
59
  signal;
70
60
  /** Upstream of `signal`. Fires only via `abort()`; a host signal aborts independently. */
@@ -72,9 +62,7 @@ export class Session {
72
62
  logger;
73
63
  tracing;
74
64
  unsubscribeTracing;
75
- injectedBackground;
76
65
  allCapabilities;
77
- services = new Map();
78
66
  // Runtime prompt data is live-Session state, not Agent state: machine identity + cwd isolate
79
67
  // root/subagent/worktree frames, and the date stays fixed for the Session's lifetime.
80
68
  systemPromptContexts = new SystemPromptContextCache();
@@ -91,7 +79,7 @@ export class Session {
91
79
  // has not "read" what its parent read, so ledgers are never shared across addresses.
92
80
  fileLedgers = new Map();
93
81
  modelOverride;
94
- /** Caller-supplied one-shot log for open (see SessionConfig.preloadedLog); cleared after
82
+ /** Caller-supplied one-shot log for open (see SessionOpenOptions.preloadedLog); cleared after
95
83
  * openCapabilities so the array itself is not pinned for the session's lifetime. */
96
84
  preloadedLog;
97
85
  thinkingOverride;
@@ -102,22 +90,25 @@ export class Session {
102
90
  // Most-recent per-turn context-window breakdown, stamped by the Runner at each turn boundary.
103
91
  // Undefined until the first turn assembles a request.
104
92
  lastContextBreakdown;
105
- constructor(cfg, id, eventPublisher, steer, signal, machine, ownController) {
93
+ constructor(scope, id, signal, ownController, opts) {
94
+ this.scope = scope;
106
95
  this.id = id;
107
- this.machine = machine;
96
+ this.signal = signal;
108
97
  this.ownController = ownController;
109
- this.eventPublisher = eventPublisher;
110
- this.store = eventPublisher.store;
111
- this.events = eventPublisher;
112
- this.tracing = cfg.tracing;
113
- this.unsubscribeTracing = cfg.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, cfg.tracing);
114
- this.responder = cfg.responder;
115
- this.permissionOptions = cfg.permission;
116
- this.steer = steer;
98
+ this.machine = scope.require(T.Machine);
99
+ this.eventPublisher = scope.require(T.EventPublisher);
100
+ // The publishing wrapper around `T.Store`: record-backed events surface on `events` when
101
+ // the append commits, so everything in the session writes through THIS store.
102
+ this.store = this.eventPublisher.store;
103
+ this.events = this.eventPublisher;
104
+ this.tracing = scope.get(T.Tracing);
105
+ this.unsubscribeTracing = this.tracing === undefined ? undefined : eventSinkTracingBridge(this.events, this.tracing);
106
+ this.responder = scope.get(T.Responder);
107
+ this.steer = scope.require(T.Steer);
117
108
  // Every enqueue — user steer/follow-up, cron fire, background settle — surfaces on the
118
109
  // event stream, so clients can render a pending queue and later match `origin.steerId`
119
110
  // on the consuming `message.appended` to know when the model actually saw it.
120
- steer.setEnqueueListener((item, channel) => {
111
+ this.steer.setEnqueueListener((item, channel) => {
121
112
  void this.events.emit({
122
113
  type: "steer.queued",
123
114
  steerId: item.id,
@@ -128,37 +119,62 @@ export class Session {
128
119
  sessionId: id,
129
120
  });
130
121
  });
131
- this.injectedBackground = cfg.background;
132
- this.signal = signal;
133
122
  // Env fallback (`AGENTS_LOG`) is resolved here so every entry point — direct `Session.open`,
134
- // the Runner's ephemeral session, or the harness — honors it from one place.
135
- this.logger = cfg.logger ?? envLogger() ?? noopLogger;
136
- this.allCapabilities = cfg.capabilities ?? [];
137
- this.preloadedLog = cfg.preloadedLog;
138
- }
139
- static async open(cfg) {
140
- const events = cfg.events ?? new ListenerSink();
141
- const steer = cfg.steer ?? new SteerBus();
123
+ // the Runner's ephemeral session, or the harness — honors it from one place. The harness
124
+ // tier normally provides `T.Logger`; a parentless session scope has nothing above it.
125
+ this.logger = scope.get(T.Logger) ?? envLogger() ?? noopLogger;
126
+ this.allCapabilities = opts.capabilities ?? [];
127
+ this.preloadedLog = opts.preloadedLog;
128
+ }
129
+ /**
130
+ * Open a session on a session-tier scope. The opener registers what it decides (`T.Machine`,
131
+ * `T.Store`, `T.Events`, `T.Responder`, `T.PermissionOptions`, `T.HostSignal`, `T.SessionId`, …);
132
+ * `open` provides the defaults for whatever is missing, builds the session's own objects
133
+ * (signal, event publisher, log reader, controls), runs every capability's provisions in
134
+ * order, then builds the permission manager. From here on the session owns the scope.
135
+ */
136
+ static async open(scope, opts = {}) {
137
+ if (scope.kind !== "session")
138
+ throw new Error(`Session.open needs a session scope, got a ${scope.kind} scope`);
139
+ scope.provide(T.SessionId, () => newSessionId());
140
+ const id = scope.require(T.SessionId);
142
141
  // The session owns a cancel handle of its own, downstream of whatever the host passed in:
143
142
  // `session.abort()` stops the session without taking the host's signal away from it, and a
144
143
  // host abort still propagates. `AbortSignal.any` owns the listener lifetime for us.
145
144
  const ownController = new AbortController();
146
- const signal = cfg.signal === undefined
147
- ? ownController.signal
148
- : AbortSignal.any([cfg.signal, ownController.signal]);
149
- const id = cfg.sessionId ?? newSessionId();
150
- const eventPublisher = new SessionEventPublisher(id, events, cfg.store, cfg.eventPublication ?? "immediate");
151
- const machine = await resolveMachine(cfg, { sessionId: id, signal });
152
- const session = new Session(cfg, id, eventPublisher, steer, signal, machine, ownController);
145
+ const host = scope.get(T.HostSignal);
146
+ const signal = host === undefined ? ownController.signal : AbortSignal.any([host, ownController.signal]);
147
+ scope.register(T.SessionSignal, signal);
148
+ scope.provide(T.Events, () => new ListenerSink());
149
+ scope.provide(T.Steer, () => new SteerBus());
150
+ // Machine: the opener's registration wins; else a workspace- or harness-level factory
151
+ // (resolved here because it needs the session id + signal, and `provide` is sync); else a
152
+ // NullMachine — a stateless session with no filesystem, where any file tool that slips
153
+ // through fails loudly instead of touching the host disk. The session only OPERATES the
154
+ // machine — disposal stays with whoever created it (`owned: false`).
155
+ if (!scope.hasLocal(T.Machine)) {
156
+ const factory = scope.get(T.SessionMachineFactory) ?? scope.get(T.WorkspaceMachineFactory) ?? scope.get(T.MachineFactory);
157
+ if (factory !== undefined) {
158
+ const machine = typeof factory === "function" ? await factory({ sessionId: id, signal }) : factory;
159
+ scope.register(T.Machine, machine, { owned: false });
160
+ }
161
+ }
162
+ scope.provide(T.Machine, () => new NullMachine());
163
+ scope.provide(T.EventPublisher, (s) => new SessionEventPublisher(id, s.require(T.Events), s.get(T.StoreBackend), s.get(T.SessionEventPublication) ?? s.get(T.EventPublication) ?? "immediate"));
164
+ const session = new Session(scope, id, signal, ownController, opts);
165
+ // `T.Store` is the publishing wrapper — what capabilities, the loop and the host write through.
166
+ if (session.store !== undefined)
167
+ scope.register(T.Store, session.store, { owned: false });
168
+ scope.register(T.SessionControls, session.controls());
153
169
  await session.openCapabilities();
154
170
  return session;
155
171
  }
156
172
  async openCapabilities() {
157
- // Shared restore: read the log at most once and
158
- // let every log-fold capability (goal/plan/todo) reconstruct from that one read via
159
- // `readSessionLog(ctx)`, then reuse it to pre-build the main conversation context — instead
160
- // of each capability, plus the first run's `replayContext`, re-reading the log separately.
161
- // A caller-preloaded log (SessionConfig.preloadedLog) IS that one read, done outside.
173
+ // Shared restore: read the log at most once and let every log-fold capability
174
+ // (goal/plan/todo) reconstruct from that one read via `T.SessionLog`, then reuse it to
175
+ // pre-build the main conversation context — instead of each capability, plus the first
176
+ // run's `replayContext`, re-reading the log separately. A caller-preloaded log IS that
177
+ // one read, done outside.
162
178
  let log = this.preloadedLog;
163
179
  this.preloadedLog = undefined;
164
180
  const logRecords = async () => {
@@ -166,16 +182,8 @@ export class Session {
166
182
  log = await readLog(this.store);
167
183
  return log;
168
184
  };
169
- const ctx = {
170
- sessionId: this.id,
171
- machine: this.machine,
172
- store: this.store,
173
- events: this.events,
174
- signal: this.signal,
175
- steer: this.steer,
176
- controls: this.controls(),
177
- logRecords,
178
- };
185
+ this.scope.register(T.SessionLog, logRecords);
186
+ const ctx = { scope: this.scope, sessionId: this.id, signal: this.signal };
179
187
  const opened = [];
180
188
  const seen = new Set();
181
189
  for (const cap of this.allCapabilities) {
@@ -190,26 +198,30 @@ export class Session {
190
198
  }
191
199
  seen.add(cap.name);
192
200
  try {
193
- if (cap.openSession)
194
- await cap.openSession(ctx);
201
+ for (const provision of cap.provides ?? []) {
202
+ const instance = await provision.create(ctx);
203
+ this.scope.register(provision.token, instance, provision.dispose !== undefined ? { dispose: provision.dispose } : {});
204
+ }
195
205
  }
196
206
  catch (error) {
197
- // per-run assembly too, since it isn't pushed onto `opened`.
207
+ // Fault isolation: the capability is absent for the session (its per-run assembly too,
208
+ // since it isn't pushed onto `opened`); a provision it did register stays until close.
198
209
  this.pendingDiagnostics.push({
199
210
  capability: cap.name,
200
211
  phase: "start",
201
212
  level: "error",
202
- message: `openSession failed; capability absent for the session: ${messageOf(error)}`,
213
+ message: `provision failed; capability absent for the session: ${messageOf(error)}`,
203
214
  });
204
- this.logger.log("error", `capability "${cap.name}" openSession failed`, { capability: cap.name, phase: "start", error: messageOf(error) });
215
+ this.logger.log("error", `capability "${cap.name}" provision failed`, { capability: cap.name, phase: "start", error: messageOf(error) });
205
216
  continue;
206
217
  }
207
218
  opened.push(cap);
208
- if (cap.service !== undefined)
209
- this.services.set(cap.name, cap.service);
210
219
  }
211
220
  this.openedCapabilities = opened;
212
221
  await this.buildPermissionManager(opened, logRecords);
222
+ // A session opened without the workflow capability still needs ONE manager per session (the
223
+ // resume journals of every workflow run in the session must land in the same store).
224
+ this.scope.provide(T.Workflow, () => new WorkflowManager(this.store));
213
225
  // If a capability triggered the log read, reuse those records to seed the main live
214
226
  // context so the first run appends to it instead of replaying the log a second time.
215
227
  if (log !== undefined && this.store !== undefined && this.liveContext(DEFAULT_ADDRESS) === undefined) {
@@ -225,7 +237,7 @@ export class Session {
225
237
  /**
226
238
  * Construct the session-lived PermissionManager: capability policy slots are collected from
227
239
  * the opened capabilities' static `policies` (session-tier fault isolation: a capability whose
228
- * `openSession` failed contributes nothing; a per-run `start()` failure does NOT retract its
240
+ * provision failed contributes nothing; a per-run `start()` failure does NOT retract its
229
241
  * policies — they are pure evaluators over session-lived state). Then runtime permission
230
242
  * state is folded back from the log — `permission.set_mode` (last wins) and approve-for-session
231
243
  * grants (`permission.record_approval` with scope "session").
@@ -255,84 +267,73 @@ export class Session {
255
267
  overrides.set(policy.name, policy);
256
268
  }
257
269
  }
258
- this._permission = new PermissionManager({
259
- ...this.permissionOptions,
260
- mode: this.permissionOptions?.mode,
270
+ const options = this.scope.get(T.PermissionOptions);
271
+ const permission = new PermissionManager({
272
+ ...options,
273
+ mode: options?.mode,
261
274
  // The Runner-driven path answers approvals via interrupt/resume (or the live responder
262
275
  // in onInterrupt) — never inline through the manager, so it gets no responder here.
263
276
  responder: undefined,
264
- cwd: this.permissionOptions?.cwd ?? safeCwd(this.machine),
265
- pathClass: this.permissionOptions?.pathClass ?? this.machine.pathClass(),
266
- machine: this.permissionOptions?.machine ?? this.machine,
277
+ cwd: options?.cwd ?? safeCwd(this.machine),
278
+ pathClass: options?.pathClass ?? this.machine.pathClass(),
279
+ machine: options?.machine ?? this.machine,
267
280
  policyOverrides: overrides,
268
281
  logger: this.logger,
269
282
  });
283
+ this.scope.register(T.Permission, permission);
270
284
  if (this.store === undefined)
271
285
  return;
272
286
  for (const record of await logRecords()) {
273
287
  if (record.type === "permission.set_mode") {
274
- this._permission.setMode(record.mode);
288
+ permission.setMode(record.mode);
275
289
  }
276
290
  else if (record.type === "permission.record_approval" &&
277
291
  record.decision === "approved" &&
278
292
  record.scope === "session" &&
279
293
  record.approvalRule !== undefined) {
280
- this._permission.applyApproval(record.approvalRule, { decision: "approved", scope: "session" });
294
+ permission.applyApproval(record.approvalRule, { decision: "approved", scope: "session" });
281
295
  }
282
296
  }
283
297
  }
284
298
  /** The session-lived permission manager (policy chain + mode + approval memory). */
285
299
  get permission() {
286
- return this._permission;
300
+ return this.scope.require(T.Permission);
287
301
  }
288
302
  get capabilities() {
289
303
  return this.openedCapabilities;
290
304
  }
291
- service(name) {
292
- return this.services.get(name);
305
+ /** PROBE tier: the service, or undefined when nothing registered it (see the class doc). */
306
+ get(tok) {
307
+ return this.scope.get(tok);
293
308
  }
294
- /** The REQUIRE tier (see the class doc): unwrap a probed service or throw the typed error. */
295
- requireCapability(service, name) {
296
- if (service === undefined)
297
- throw new CapabilityMissingError(name);
298
- return service;
299
- }
300
- get goal() {
301
- return this.services.get("goal");
309
+ /** REQUIRE tier: the service, or a `ServiceUnavailableError` naming what is missing. */
310
+ require(tok) {
311
+ return this.scope.require(tok);
302
312
  }
313
+ /** The workflow manager: the capability's, or the in-memory fallback `open` provides. */
303
314
  get workflow() {
304
- return this.services.get("workflow");
305
- }
306
- get skills() {
307
- return this.services.get("skills");
308
- }
309
- get plugins() {
310
- return this.services.get("plugins");
311
- }
312
- get backgroundManager() {
313
- return this.services.get("background");
315
+ return this.scope.require(T.Workflow);
314
316
  }
315
- get plan() {
316
- return this.services.get("plan");
317
+ newWorkflowJournal(runId, parentToolCallId) {
318
+ return this.workflow.newJournal(runId, parentToolCallId);
317
319
  }
318
320
  get compaction() {
319
- return this.services.get("compaction");
320
- }
321
- get mcp() {
322
- return this.services.get("mcp");
321
+ return this.scope.get(T.Compaction);
323
322
  }
323
+ /** The spawner the Agent/Workflow tools use: the background capability's manager, else the
324
+ * host-injected `T.BackgroundSpawner`. */
324
325
  get background() {
325
- return this.services.get("background") ?? this.injectedBackground;
326
+ return this.scope.get(T.Background) ?? this.scope.get(T.BackgroundSpawner);
326
327
  }
327
328
  async listBackgroundTasks(options = {}) {
328
- const background = this.requireCapability(this.backgroundManager, "background");
329
+ const background = this.require(T.Background);
329
330
  return background.list(options.activeOnly ?? false, options.limit);
330
331
  }
331
332
  /** Past BACKGROUND workflow runs (newest first), from the durable task store. A foreground
332
333
  * workflow is a plain `Workflow` tool call — its record is the conversation plus its journal
333
334
  * shard — so it is not listed here (its shard stays resumable by runId). */
334
335
  async listWorkflows() {
335
- const manager = this.backgroundManager;
336
+ const manager = this.get(T.Background);
336
337
  if (manager === undefined)
337
338
  return [];
338
339
  const runs = [];
@@ -362,7 +363,7 @@ export class Session {
362
363
  * ghosts). Foreground subagents are plain `Agent` tool calls — their record is the conversation
363
364
  * plus their own shard — so they are not listed here (their shard stays resumable by id). */
364
365
  async listSubagents() {
365
- const manager = this.backgroundManager;
366
+ const manager = this.get(T.Background);
366
367
  if (manager === undefined)
367
368
  return [];
368
369
  const records = [];
@@ -381,7 +382,7 @@ export class Session {
381
382
  * (resume any with `Agent(resume="<id>", ...)`).
382
383
  */
383
384
  async reconcileSubagents() {
384
- const manager = this.backgroundManager;
385
+ const manager = this.get(T.Background);
385
386
  if (manager === undefined || this.store === undefined)
386
387
  return [];
387
388
  const lost = [];
@@ -481,11 +482,11 @@ export class Session {
481
482
  }
482
483
  /** Resolve environment + AGENTS.md for the active runtime frame, cached for this Session. */
483
484
  resolveSystemPromptContext(machine) {
484
- return this.systemPromptContexts.resolve(machine, this.compaction?.revision ?? 0);
485
+ return this.systemPromptContexts.resolve(machine, this.get(T.Compaction)?.revision ?? 0);
485
486
  }
486
487
  /** A bounded view of the task's authoritative output, with explicit size/truncation metadata. */
487
488
  async readBackgroundTaskOutput(taskId, options = {}) {
488
- const background = this.requireCapability(this.backgroundManager, "background");
489
+ const background = this.require(T.Background);
489
490
  return background.readOutput(taskId, options.maxBytes ?? 16 * 1024);
490
491
  }
491
492
  /**
@@ -494,11 +495,11 @@ export class Session {
494
495
  * means this task keeps no byte-addressable output; use `readBackgroundTaskOutput` instead.
495
496
  */
496
497
  async readBackgroundTaskOutputDelta(taskId, options) {
497
- const background = this.requireCapability(this.backgroundManager, "background");
498
+ const background = this.require(T.Background);
498
499
  return background.readOutputDelta(taskId, options.cursor, options.maxBytes);
499
500
  }
500
501
  async stopBackgroundTask(taskId, reason) {
501
- const background = this.requireCapability(this.backgroundManager, "background");
502
+ const background = this.require(T.Background);
502
503
  return background.stop(taskId, reason);
503
504
  }
504
505
  /**
@@ -507,20 +508,28 @@ export class Session {
507
508
  * currently in its detachable window (already finished, or not a detachable tool).
508
509
  */
509
510
  detachTool(toolCallId) {
510
- const background = this.requireCapability(this.backgroundManager, "background");
511
+ const background = this.require(T.Background);
511
512
  return background.detach(toolCallId);
512
513
  }
513
514
  /** Connected MCP servers and their status. Empty when no MCP capability is open. */
514
515
  listMcpServers() {
515
- return this.mcp?.list() ?? [];
516
+ return this.get(T.Mcp)?.list() ?? [];
517
+ }
518
+ /**
519
+ * Tools one MCP server exposes — for showing a host's user what a server can do.
520
+ * Empty when the capability is off, the server is unknown, or it is not connected,
521
+ * for the same reason `listMcpServers` degrades to empty rather than throwing.
522
+ */
523
+ async listMcpTools(name) {
524
+ return (await this.get(T.Mcp)?.listTools(name)) ?? [];
516
525
  }
517
526
  /** Force-reconnect one MCP server by name. Throws if no MCP capability is open. */
518
527
  async reconnectMcpServer(name) {
519
- const mcp = this.requireCapability(this.mcp, "mcp");
528
+ const mcp = this.require(T.Mcp);
520
529
  await mcp.reconnect(name);
521
530
  }
522
531
  async createGoal(input) {
523
- const goal = this.requireCapability(this.goal, "goal");
532
+ const goal = this.require(T.Goal);
524
533
  if (input.objective.trim().length === 0)
525
534
  throw new Error("Goal objective cannot be empty.");
526
535
  if (goal.has())
@@ -538,7 +547,7 @@ export class Session {
538
547
  return snapshot;
539
548
  }
540
549
  async getGoal() {
541
- const goal = this.requireCapability(this.goal, "goal");
550
+ const goal = this.require(T.Goal);
542
551
  return goal.snapshot();
543
552
  }
544
553
  async pauseGoal(options = {}) {
@@ -548,7 +557,7 @@ export class Session {
548
557
  return this.updateExistingGoal("active", options.reason);
549
558
  }
550
559
  async cancelGoal(options = {}) {
551
- const goal = this.requireCapability(this.goal, "goal");
560
+ const goal = this.require(T.Goal);
552
561
  const previous = goal.snapshot();
553
562
  if (previous === null)
554
563
  return null;
@@ -557,13 +566,13 @@ export class Session {
557
566
  return previous;
558
567
  }
559
568
  async setGoalBudget(budget) {
560
- const goal = this.requireCapability(this.goal, "goal");
569
+ const goal = this.require(T.Goal);
561
570
  const snapshot = goal.setBudget(normalizeGoalBudget(budget));
562
571
  await this.emitControlEvent({ type: "goal.updated", snapshot });
563
572
  return snapshot;
564
573
  }
565
574
  async setPlanMode(enabled, options = {}) {
566
- const plan = this.requireCapability(this.plan, "plan");
575
+ const plan = this.require(T.Plan);
567
576
  if (enabled && !plan.isActive) {
568
577
  await plan.enter(options.createFile ?? true);
569
578
  }
@@ -575,7 +584,7 @@ export class Session {
575
584
  return snapshot;
576
585
  }
577
586
  async getPlan() {
578
- const plan = this.requireCapability(this.plan, "plan");
587
+ const plan = this.require(T.Plan);
579
588
  return plan.data();
580
589
  }
581
590
  async clearPlan() {
@@ -606,19 +615,19 @@ export class Session {
606
615
  this.ownController.abort(abortReason(reason ?? "session aborted"));
607
616
  }
608
617
  async compact(options = {}) {
609
- const compaction = this.requireCapability(this.compaction, "compaction");
618
+ const compaction = this.require(T.Compaction);
610
619
  return compaction.request(options);
611
620
  }
612
621
  async pendingCompaction() {
613
- const compaction = this.requireCapability(this.compaction, "compaction");
622
+ const compaction = this.require(T.Compaction);
614
623
  return compaction.pending();
615
624
  }
616
625
  async cancelCompaction() {
617
- const compaction = this.requireCapability(this.compaction, "compaction");
626
+ const compaction = this.require(T.Compaction);
618
627
  return compaction.cancel();
619
628
  }
620
629
  async updateExistingGoal(status, reason) {
621
- const goal = this.requireCapability(this.goal, "goal");
630
+ const goal = this.require(T.Goal);
622
631
  if (goal.snapshot() === null)
623
632
  return null;
624
633
  const snapshot = goal.update({ status, reason });
@@ -629,24 +638,24 @@ export class Session {
629
638
  await this.events.emit({ ...body, address: "main", sessionId: this.id });
630
639
  }
631
640
  async listSkills() {
632
- const skills = this.requireCapability(this.skills, "skills");
641
+ const skills = this.require(T.Skills);
633
642
  return skills.listSkills();
634
643
  }
635
644
  async activateSkill(nameOrRequest, args) {
636
- const skills = this.requireCapability(this.skills, "skills");
645
+ const skills = this.require(T.Skills);
637
646
  const request = typeof nameOrRequest === "string" ? { name: nameOrRequest, ...(args !== undefined ? { args } : {}) } : nameOrRequest;
638
647
  return skills.activateSkill(request);
639
648
  }
640
649
  async listPlugins() {
641
- const plugins = this.requireCapability(this.plugins, "plugins");
650
+ const plugins = this.require(T.Plugins);
642
651
  return plugins.summaries();
643
652
  }
644
653
  async getPluginInfo(id) {
645
- const plugins = this.requireCapability(this.plugins, "plugins");
654
+ const plugins = this.require(T.Plugins);
646
655
  return plugins.info(id);
647
656
  }
648
657
  async installPlugin(source) {
649
- const plugins = this.requireCapability(this.plugins, "plugins");
658
+ const plugins = this.require(T.Plugins);
650
659
  const record = await plugins.install(source);
651
660
  const summary = plugins.summaries().find((plugin) => plugin.id === record.id);
652
661
  if (summary === undefined)
@@ -654,19 +663,19 @@ export class Session {
654
663
  return summary;
655
664
  }
656
665
  async setPluginEnabled(id, enabled) {
657
- const plugins = this.requireCapability(this.plugins, "plugins");
666
+ const plugins = this.require(T.Plugins);
658
667
  await plugins.setEnabled(id, enabled);
659
668
  }
660
669
  async setPluginMcpServerEnabled(id, server, enabled) {
661
- const plugins = this.requireCapability(this.plugins, "plugins");
670
+ const plugins = this.require(T.Plugins);
662
671
  await plugins.setMcpServerEnabled(id, server, enabled);
663
672
  }
664
673
  async removePlugin(id) {
665
- const plugins = this.requireCapability(this.plugins, "plugins");
674
+ const plugins = this.require(T.Plugins);
666
675
  await plugins.remove(id);
667
676
  }
668
677
  async reloadPlugins() {
669
- const plugins = this.requireCapability(this.plugins, "plugins");
678
+ const plugins = this.require(T.Plugins);
670
679
  return plugins.reload();
671
680
  }
672
681
  setModel(model) {
@@ -685,7 +694,7 @@ export class Session {
685
694
  * rejection is pre-handled internally, so ignoring it never trips unhandledRejection).
686
695
  */
687
696
  setPermissionMode(mode) {
688
- this._permission.setMode(mode);
697
+ this.permission.setMode(mode);
689
698
  if (this.store === undefined)
690
699
  return Promise.resolve();
691
700
  const persisted = this.store.appendRecord({ type: "permission.set_mode", mode, address: DEFAULT_ADDRESS });
@@ -701,7 +710,7 @@ export class Session {
701
710
  return this.thinkingOverride;
702
711
  }
703
712
  get permissionModeSetting() {
704
- return this._permission.mode;
713
+ return this.permission.mode;
705
714
  }
706
715
  drainDiagnostics() {
707
716
  return this.pendingDiagnostics.splice(0, this.pendingDiagnostics.length);
@@ -721,28 +730,17 @@ export class Session {
721
730
  flushEvents() {
722
731
  return this.eventPublisher.flush();
723
732
  }
733
+ /**
734
+ * Close the session: flush telemetry and the store, then close the scope — which disposes
735
+ * every capability provision in reverse order (each under a deadline) and finally the
736
+ * session's own infrastructure. Idempotent.
737
+ */
724
738
  async close() {
725
739
  if (!this.isOpen)
726
740
  return;
727
741
  this.isOpen = false;
728
742
  this.systemPromptContexts.clear();
729
743
  this.unsubscribeTracing?.();
730
- for (const cap of [...this.openedCapabilities].reverse()) {
731
- if (!cap.closeSession)
732
- continue;
733
- try {
734
- await withTimeout(Promise.resolve(cap.closeSession()), CLOSE_TIMEOUT_MS);
735
- }
736
- catch (error) {
737
- this.pendingDiagnostics.push({
738
- capability: cap.name,
739
- phase: "stop",
740
- level: "warn",
741
- message: `closeSession failed/timed out: ${messageOf(error)}`,
742
- });
743
- this.logger.log("warn", `capability "${cap.name}" closeSession failed/timed out`, { capability: cap.name, phase: "stop", error: messageOf(error) });
744
- }
745
- }
746
744
  this.openedCapabilities = [];
747
745
  try {
748
746
  await withTimeout(Promise.resolve(this.tracing?.forceFlush()), CLOSE_TIMEOUT_MS);
@@ -769,9 +767,15 @@ export class Session {
769
767
  });
770
768
  this.logger.log("warn", "store flush failed/timed out", { capability: "store", phase: "stop", error: messageOf(error) });
771
769
  }
772
- // The machine is deliberately NOT closed here: its lifetime belongs to whoever created
773
- // it (see `MachineFactory`). A sandbox usually outlives any one session, so closing it
774
- // on session.close would pull the workspace out from under the user's other sessions.
770
+ // Provisions (MCP connections, the background manager's subscription, …) go down in
771
+ // reverse registration order, each dispose under CLOSE_TIMEOUT_MS. The machine is NOT
772
+ // closed here unless this session registered it as owned: its lifetime belongs to whoever
773
+ // created it (see `MachineFactory`) — a sandbox usually outlives any one session, so
774
+ // closing it on session.close would pull the workspace out from under other sessions.
775
+ await this.scope.close({ disposeTimeoutMs: CLOSE_TIMEOUT_MS, onDisposeError: (name, error) => {
776
+ this.pendingDiagnostics.push({ capability: name, phase: "stop", level: "warn", message: `dispose failed/timed out: ${messageOf(error)}` });
777
+ this.logger.log("warn", `service "${name}" dispose failed/timed out`, { capability: name, phase: "stop", error: messageOf(error) });
778
+ } });
775
779
  }
776
780
  /** Public URL for a port inside the machine, or undefined when the backend can't expose one. */
777
781
  async resolveExposedPort(port) {
@@ -802,14 +806,6 @@ function positiveInt(name, value) {
802
806
  throw new Error(`Goal budget ${name} must be a positive integer.`);
803
807
  return value;
804
808
  }
805
- async function resolveMachine(cfg, ctx) {
806
- // No machine configured → stateless session with no filesystem. A NullMachine
807
- // answers metadata but refuses all I/O, so a stray file tool fails loudly
808
- // rather than silently touching the host disk.
809
- if (!cfg.machine)
810
- return new NullMachine();
811
- return typeof cfg.machine === "function" ? await cfg.machine(ctx) : cfg.machine;
812
- }
813
809
  function safeCwd(machine) {
814
810
  try {
815
811
  return machine.getcwd();