operon-agents 0.1.0-alpha.15 → 0.1.0-alpha.16

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/dist/harness.d.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { type AgentEvent, type EventPublicationMode, type TelemetryService, type AgentEventListener, type AgentInput, SessionProjection, type SessionSnapshot, type SnapshotOptions, type DirectoryEntry, type ProjectionObservation, type ProjectionListener, type ApprovalRequest, type ApprovalResponse, type Capability, type InterruptAnswer, type ChatModel, ListenerSink, type PermissionManagerOptions, type PermissionMode, type PendingRunInterrupt, type QuestionRequest, type QuestionResult, type Responder, type RunHandle, type RunResult, type SessionStore, type SessionHandle, type SessionSummary, type ListSessionsFilter, type OpenSessionOptions, type DeleteSessionOptions, type ThinkingLevel, type Tool, type SteerMessage, type SteerOptions, type SteerOrigin, type SteerReceipt, Agent, Runner, Session, McpOAuthService, SkillRegistry, type HookDef, type McpServerConfig, type McpTransportKind, type PluginManager, type ApprovalRequestOptions, type Environment, type EnvironmentFactory, type SessionRepository, type ResolvedAgentProfile, type SubagentProvider } from "operon-agents-core";
15
15
  import type { SkillsService, CompactionService, BackgroundManager, McpServersHandle, GoalStore, PlanMode, Logger, ModelRuntime, TracingProcessor } from "operon-agents-core";
16
+ import { type WorkspaceMcpPool } from "./workspace-mcp.ts";
16
17
  import { HarnessExtensionManager, ServiceRegistry, type ExtensionDefinition, type ServiceOptions } from "./extensions/index.ts";
17
18
  import { type CommandResult, type TodoItem } from "operon-agents-core";
18
19
  export type ApprovalHandler = (request: ApprovalRequest, options?: ApprovalRequestOptions) => Promise<ApprovalResponse> | ApprovalResponse;
@@ -60,6 +61,19 @@ export interface DefaultCapabilitiesOptions {
60
61
  * session's wins for this session only. Built, connected and shut down with the session.
61
62
  */
62
63
  readonly sessionMcpServers?: Record<string, McpServerConfig>;
64
+ /**
65
+ * Share MCP connections per DIRECTORY instead of building them per session: every server this
66
+ * bundle would otherwise connect for the session — `mcpServers`, the plugins', and `servers`
67
+ * here (the directory's own, e.g. its `mcp.json`) — is borrowed from `pool` under `workDir`, so
68
+ * the sessions open in one directory run one set. `sessionMcpServers` stay the session's own,
69
+ * layered over it. Ignored when `shared.mcpServers` is set (a process-wide set already covers
70
+ * every directory) and for a session on its own environment. See {@link WorkspaceMcpPool}.
71
+ */
72
+ readonly workspaceMcp?: {
73
+ readonly pool: WorkspaceMcpPool;
74
+ readonly workDir: string;
75
+ readonly servers?: Record<string, McpServerConfig>;
76
+ };
63
77
  /**
64
78
  * Installed-plugin manager. When set, the framework self-drives the plugin's contributions into
65
79
  * this capability set: its skills (merged into the skills capability), its MCP servers (merged
package/dist/harness.js CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { readLog, SessionProjection, ListenerSink, agentEventFromRecord, newAgentEventId, Agent, buildAgentFromProfile, INTERRUPTION_STATE_KEY, flattenPendingInterrupts, parseInterruptionState, Runner, Session, emptyUsage, isGuardrailTripwireError, askUserQuestionTool, backgroundCapability, compactionCapability, filesystemTools, goalCapability, LocalEnvironment, McpOAuthService, MemorySessionRepository, SessionRepositoryNotFoundError, planCapability, skillsCapability, SkillRegistry, mcpServersCapability, pluginsCapability, userHooksCapability, taskCapability, workflowCapability, DEFAULT_AGENT_PROFILES, DEFAULT_AGENT_PROFILE_NAME, DEFAULT_SUBAGENT_NAMES, profileSubagentProvider, DEFAULT_ADDRESS, envLogger, noopLogger, } from "operon-agents-core";
15
15
  import { mkdirSync } from "node:fs";
16
+ import { workspaceMcpCapability } from "./workspace-mcp.js";
16
17
  import { join } from "node:path";
17
18
  import { extensionCapability, extensionRuntimeOf, extensionsCapability, HarnessExtensionManager, ServiceRegistry, stageDefinition } from "./extensions/index.js";
18
19
  import { createExtensionCommandRegistry } from "operon-agents-core";
@@ -70,14 +71,26 @@ export function defaultCapabilities(options = {}) {
70
71
  ...(oauthService !== undefined ? { oauthService } : {}),
71
72
  ...(options.allowedMcpTransports !== undefined ? { allowedTransports: options.allowedMcpTransports } : {}),
72
73
  };
73
- // With process-shared connections, the capability is a VIEW over them and `configs` is this
74
- // session's overlay. Without, everything this session sees is its own — session servers last,
75
- // so the same name still resolves to the session's.
76
- const mcpConfigs = sharedServers !== undefined
77
- ? sessionMcp
78
- : { ...(options.mcpServers ?? {}), ...(manager?.mcpServerConfigs() ?? {}), ...sessionMcp };
79
- if (sharedServers !== undefined || Object.keys(mcpConfigs).length > 0) {
80
- capabilities.push(mcpServersCapability(mcpConfigs, { ...mcpOptions, ...(sharedServers !== undefined ? { sharedServers } : {}) }));
74
+ // Everything this session would connect that is not private to it: the directory's servers
75
+ // last, so they win over a same-named plugin server the way they did as a session overlay.
76
+ const shareable = {
77
+ ...(options.mcpServers ?? {}),
78
+ ...(manager?.mcpServerConfigs() ?? {}),
79
+ ...(options.workspaceMcp?.servers ?? {}),
80
+ };
81
+ const pooled = sharedServers === undefined && options.ownEnvironment !== true ? options.workspaceMcp : undefined;
82
+ if (pooled !== undefined && Object.keys(shareable).length > 0) {
83
+ // Borrowed per directory: the capability views the pool's set, `sessionMcp` is its overlay.
84
+ capabilities.push(workspaceMcpCapability({ pool: pooled.pool, workDir: pooled.workDir, servers: shareable, overlay: sessionMcp, overlayOptions: mcpOptions }));
85
+ }
86
+ else {
87
+ // With process-shared connections, the capability is a VIEW over them and `configs` is this
88
+ // session's overlay. Without, everything this session sees is its own — session servers last,
89
+ // so the same name still resolves to the session's.
90
+ const mcpConfigs = sharedServers !== undefined ? sessionMcp : { ...shareable, ...sessionMcp };
91
+ if (sharedServers !== undefined || Object.keys(mcpConfigs).length > 0) {
92
+ capabilities.push(mcpServersCapability(mcpConfigs, { ...mcpOptions, ...(sharedServers !== undefined ? { sharedServers } : {}) }));
93
+ }
81
94
  }
82
95
  // Plugins: load the manager + render the plugin's session-start skill from the shared registry
83
96
  // (skills opens before this, so by injection time the registry holds the plugin skills).
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@ export * from "./extensions/index.ts";
16
16
  export * from "./cron/index.ts";
17
17
  export * from "./providers.ts";
18
18
  export * from "./local.ts";
19
+ export * from "./workspace-mcp.ts";
19
20
  export * from "operon-agents-core";
20
21
  export * as llm from "operon-agents-core/llm";
21
22
  export * as mcp from "operon-agents-core/mcp";
package/dist/index.js CHANGED
@@ -20,6 +20,8 @@ export * from "./cron/index.js";
20
20
  export * from "./providers.js";
21
21
  // Deployment composition roots: local vs server injection presets (Invariant 7 — no engine "mode").
22
22
  export * from "./local.js";
23
+ // Per-directory MCP sharing for hosts that open many sessions in one folder (a desktop app).
24
+ export * from "./workspace-mcp.js";
23
25
  // The curated core engine, re-exported for convenience; `operon-agents/core` is the dedicated
24
26
  // primitives entrypoint.
25
27
  export * from "operon-agents-core";
@@ -0,0 +1,62 @@
1
+ import { type Capability, type McpServerConfig, type McpServersCapabilityOptions, type McpServersHandle } from "operon-agents-core";
2
+ /** How long a directory's connections outlive its last session by default: five minutes. */
3
+ export declare const DEFAULT_WORKSPACE_MCP_IDLE_MS: number;
4
+ export interface WorkspaceMcpPoolOptions extends Omit<McpServersCapabilityOptions, "sharedServers"> {
5
+ /**
6
+ * How long a directory's connections stay up after the last session using them closes, in ms.
7
+ * A session opened there within the window reuses them. `0` closes them at once. Defaults to
8
+ * {@link DEFAULT_WORKSPACE_MCP_IDLE_MS}.
9
+ */
10
+ readonly idleMs?: number;
11
+ }
12
+ /** One session's hold on a directory's connections. `release` is idempotent. */
13
+ export interface WorkspaceMcpLease {
14
+ readonly servers: McpServersHandle;
15
+ release(): Promise<void>;
16
+ }
17
+ export declare class WorkspaceMcpPool {
18
+ private readonly options;
19
+ /** The generation a NEW borrow in each directory gets. */
20
+ private readonly current;
21
+ /** Every generation not yet shut down — current ones and retired ones still on loan. */
22
+ private readonly live;
23
+ private closing;
24
+ constructor(options?: WorkspaceMcpPoolOptions);
25
+ /** Directories whose connections are currently up (on loan or idling). */
26
+ get size(): number;
27
+ /**
28
+ * Borrow the connections for `workDir`, building them if this directory has none for exactly
29
+ * these `configs`. Resolves once they have connected — fault-isolated, so a server that failed
30
+ * is a status on the handle, never a rejection. Rejects for what `createMcpServers` refuses
31
+ * up front (a transport this host does not run), before anything is built.
32
+ */
33
+ acquire(workDir: string, configs: Record<string, McpServerConfig>): Promise<WorkspaceMcpLease>;
34
+ /** Shut every directory's connections down, on loan or not. Later borrows throw. Idempotent. */
35
+ close(): Promise<void>;
36
+ /** The last lease came back: close a retired generation now, a current one after the grace. */
37
+ private idle;
38
+ private shutdown;
39
+ private assertOpen;
40
+ }
41
+ export interface WorkspaceMcpCapabilityOptions {
42
+ readonly pool: WorkspaceMcpPool;
43
+ /** The session's working directory — the key the connections are shared under. */
44
+ readonly workDir: string;
45
+ /** The servers every session in `workDir` shares. */
46
+ readonly servers: Record<string, McpServerConfig>;
47
+ /** The session's own servers, layered over the shared ones (same name: the session's wins). */
48
+ readonly overlay?: Record<string, McpServerConfig>;
49
+ /**
50
+ * Options for the overlay's connections; the pooled ones were configured on the pool. Its
51
+ * `allowedTransports` is enforced on BOTH — the host's statement of what it runs does not get
52
+ * weaker because a server happens to be shared.
53
+ */
54
+ readonly overlayOptions?: Omit<McpServersCapabilityOptions, "sharedServers">;
55
+ }
56
+ /**
57
+ * The `mcp` capability over a directory's pooled connections: borrows them at `openSession`,
58
+ * gives them back at `closeSession` (session close or detach alike). In between it is exactly
59
+ * `mcpServersCapability` viewing a shared set — same tools, same `session.mcp`, same overlay.
60
+ */
61
+ export declare function workspaceMcpCapability(options: WorkspaceMcpCapabilityOptions): Capability;
62
+ //# sourceMappingURL=workspace-mcp.d.ts.map
@@ -0,0 +1,222 @@
1
+ /**
2
+ * MCP connections shared by every session opened in the same directory.
3
+ *
4
+ * A desktop host keeps one process up all day and opens many conversations in one project at
5
+ * once. Each of them used to connect the project's MCP servers again — an stdio server is a child
6
+ * process, so N chats in one folder meant N copies of every server. The pool keys one set of
7
+ * connections by the directory's real path and lends it to each session that opens there.
8
+ *
9
+ * This is deliberately NOT a lifetime tier of the engine (that was the workspace `Scope`, removed
10
+ * for the rules it cost). Core still knows two lifetimes, the process and the session; the pool
11
+ * is a host-side object the session hook hands to `defaultCapabilities`, and the MCP capability
12
+ * borrows from it at `openSession` and gives back at `closeSession`. Because the borrowing lives
13
+ * inside the capability's own open/close, a failed open undoes it like everything else the
14
+ * session opened — no hold is taken anywhere the session cannot see.
15
+ *
16
+ * Lifetime of one directory's set, a "generation":
17
+ * - built on the first borrow, connected once; concurrent borrows share that one connect;
18
+ * - kept while any session holds it, then for `idleMs` more, so closing the last chat and
19
+ * starting the next one does not respawn every server;
20
+ * - replaced, not mutated, when a borrow arrives with a different configuration (an edited
21
+ * `mcp.json`, a plugin enabled): new sessions get a new generation, the sessions already
22
+ * holding the old one keep it, and it closes when the last of them gives it back.
23
+ *
24
+ * Sharing is the point, so it is total: two sessions in one directory drive the SAME server.
25
+ * One with state of its own (a browser) is therefore shared state between them; a reconnect or an
26
+ * OAuth sign-in in one session is seen by all. A server that must be private belongs in the
27
+ * session's own `mcpServers`, which are layered over the shared set and never pooled.
28
+ */
29
+ import { realpath } from "node:fs/promises";
30
+ import { resolve } from "node:path";
31
+ import { createMcpServers, mcpServersCapability, McpTransportNotPermittedError, } from "operon-agents-core";
32
+ /** How long a directory's connections outlive its last session by default: five minutes. */
33
+ export const DEFAULT_WORKSPACE_MCP_IDLE_MS = 5 * 60_000;
34
+ export class WorkspaceMcpPool {
35
+ options;
36
+ /** The generation a NEW borrow in each directory gets. */
37
+ current = new Map();
38
+ /** Every generation not yet shut down — current ones and retired ones still on loan. */
39
+ live = new Set();
40
+ closing;
41
+ constructor(options = {}) {
42
+ this.options = options;
43
+ }
44
+ /** Directories whose connections are currently up (on loan or idling). */
45
+ get size() {
46
+ return this.current.size;
47
+ }
48
+ /**
49
+ * Borrow the connections for `workDir`, building them if this directory has none for exactly
50
+ * these `configs`. Resolves once they have connected — fault-isolated, so a server that failed
51
+ * is a status on the handle, never a rejection. Rejects for what `createMcpServers` refuses
52
+ * up front (a transport this host does not run), before anything is built.
53
+ */
54
+ async acquire(workDir, configs) {
55
+ this.assertOpen();
56
+ const key = await canonicalDir(workDir);
57
+ this.assertOpen();
58
+ const fingerprint = fingerprintOf(configs);
59
+ let generation = this.current.get(key);
60
+ if (generation !== undefined && generation.fingerprint !== fingerprint) {
61
+ this.current.delete(key);
62
+ if (generation.leases === 0)
63
+ void this.shutdown(generation);
64
+ generation = undefined;
65
+ }
66
+ if (generation === undefined) {
67
+ const { idleMs: _idleMs, ...serverOptions } = this.options;
68
+ const servers = createMcpServers(configs, serverOptions);
69
+ // Pooled connections belong to no session: their failures reach each borrower through
70
+ // `onStatusChange`, which the MCP capability subscribes to when it opens.
71
+ generation = { key, fingerprint, servers, ready: servers.connect({ sessionId: "" }), leases: 0 };
72
+ this.current.set(key, generation);
73
+ this.live.add(generation);
74
+ }
75
+ const held = generation;
76
+ held.leases += 1;
77
+ if (held.idle !== undefined) {
78
+ clearTimeout(held.idle);
79
+ held.idle = undefined;
80
+ }
81
+ let released = false;
82
+ const release = async () => {
83
+ if (released)
84
+ return;
85
+ released = true;
86
+ held.leases -= 1;
87
+ if (held.leases === 0)
88
+ await this.idle(held);
89
+ };
90
+ try {
91
+ await held.ready;
92
+ }
93
+ catch (error) {
94
+ await release();
95
+ throw error;
96
+ }
97
+ return { servers: held.servers, release };
98
+ }
99
+ /** Shut every directory's connections down, on loan or not. Later borrows throw. Idempotent. */
100
+ close() {
101
+ this.closing ??= (async () => {
102
+ this.current.clear();
103
+ await Promise.allSettled([...this.live].map((generation) => this.shutdown(generation)));
104
+ })();
105
+ return this.closing;
106
+ }
107
+ /** The last lease came back: close a retired generation now, a current one after the grace. */
108
+ async idle(generation) {
109
+ const idleMs = this.options.idleMs ?? DEFAULT_WORKSPACE_MCP_IDLE_MS;
110
+ if (this.current.get(generation.key) !== generation || idleMs <= 0) {
111
+ if (this.current.get(generation.key) === generation)
112
+ this.current.delete(generation.key);
113
+ await this.shutdown(generation);
114
+ return;
115
+ }
116
+ generation.idle = setTimeout(() => {
117
+ generation.idle = undefined;
118
+ if (generation.leases !== 0 || this.current.get(generation.key) !== generation)
119
+ return;
120
+ this.current.delete(generation.key);
121
+ void this.shutdown(generation);
122
+ }, idleMs);
123
+ // An idling set must not be what keeps the process alive.
124
+ generation.idle.unref?.();
125
+ }
126
+ shutdown(generation) {
127
+ if (generation.idle !== undefined) {
128
+ clearTimeout(generation.idle);
129
+ generation.idle = undefined;
130
+ }
131
+ this.live.delete(generation);
132
+ generation.closed ??= generation.ready.catch(() => undefined).then(() => generation.servers.shutdown());
133
+ return generation.closed;
134
+ }
135
+ assertOpen() {
136
+ if (this.closing !== undefined)
137
+ throw new Error("WorkspaceMcpPool is closed");
138
+ }
139
+ }
140
+ /**
141
+ * The `mcp` capability over a directory's pooled connections: borrows them at `openSession`,
142
+ * gives them back at `closeSession` (session close or detach alike). In between it is exactly
143
+ * `mcpServersCapability` viewing a shared set — same tools, same `session.mcp`, same overlay.
144
+ */
145
+ export function workspaceMcpCapability(options) {
146
+ const allowed = options.overlayOptions?.allowedTransports;
147
+ if (allowed !== undefined) {
148
+ for (const [name, config] of Object.entries(options.servers)) {
149
+ if (config.enabled !== false && !allowed.includes(config.transport)) {
150
+ throw new McpTransportNotPermittedError(name, config.transport, allowed);
151
+ }
152
+ }
153
+ }
154
+ let lease;
155
+ /** The borrowed set while a lease is held; the view below is empty without one. */
156
+ let bound;
157
+ const view = {
158
+ list: () => bound?.list() ?? [],
159
+ listTools: async (name) => (bound !== undefined ? bound.listTools(name) : []),
160
+ reconnect: async (name) => {
161
+ if (bound === undefined)
162
+ throw new Error(`Unknown MCP server: ${name}`);
163
+ await bound.reconnect(name);
164
+ },
165
+ onStatusChange: (listener) => bound?.onStatusChange(listener) ?? (() => { }),
166
+ toolProviders: () => bound?.toolProviders() ?? [],
167
+ // The pool connects and shuts down; a viewer does neither.
168
+ connect: async () => { },
169
+ shutdown: async () => { },
170
+ };
171
+ const inner = mcpServersCapability(options.overlay ?? {}, { ...(options.overlayOptions ?? {}), sharedServers: view });
172
+ const giveBack = async () => {
173
+ const held = lease;
174
+ lease = undefined;
175
+ bound = undefined;
176
+ await held?.release();
177
+ };
178
+ return {
179
+ name: inner.name,
180
+ contract: inner.contract,
181
+ ...(inner.toolProviders !== undefined ? { toolProviders: inner.toolProviders } : {}),
182
+ get service() {
183
+ return inner.service;
184
+ },
185
+ openSession: async (ctx) => {
186
+ lease = await options.pool.acquire(options.workDir, options.servers);
187
+ bound = lease.servers;
188
+ try {
189
+ await inner.openSession?.(ctx);
190
+ }
191
+ catch (error) {
192
+ await giveBack();
193
+ throw error;
194
+ }
195
+ },
196
+ closeSession: async (reason) => {
197
+ try {
198
+ await inner.closeSession?.(reason);
199
+ }
200
+ finally {
201
+ await giveBack();
202
+ }
203
+ },
204
+ };
205
+ }
206
+ /** The directory's real path, so `./proj`, `/tmp/proj` and a symlink to it share one set. */
207
+ async function canonicalDir(workDir) {
208
+ const absolute = resolve(workDir);
209
+ try {
210
+ return await realpath(absolute);
211
+ }
212
+ catch {
213
+ return absolute;
214
+ }
215
+ }
216
+ /** Order-independent identity of a configuration: same servers, same settings, same string. */
217
+ function fingerprintOf(configs) {
218
+ return JSON.stringify(configs, (_key, value) => value !== null && typeof value === "object" && !Array.isArray(value)
219
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
220
+ : value);
221
+ }
222
+ //# sourceMappingURL=workspace-mcp.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "operon-agents",
3
- "version": "0.1.0-alpha.15",
3
+ "version": "0.1.0-alpha.16",
4
4
  "description": "Public SDK entrypoint for building agents.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -74,7 +74,7 @@
74
74
  "zod": "^4.4.3",
75
75
  "smol-toml": "^1.6.1",
76
76
  "@earendil-works/pi-ai": "0.87.1",
77
- "operon-agents-core": "0.1.0-alpha.15"
77
+ "operon-agents-core": "0.1.0-alpha.16"
78
78
  },
79
79
  "devDependencies": {
80
80
  "@earendil-works/pi-ai": "0.87.1"