operon-managed-agents 0.1.0-alpha.16 → 0.1.0-alpha.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -125,3 +125,35 @@ describe the relay and are refused without the declaration. Declaring `external`
|
|
|
125
125
|
so it needs no permission of its own; the `authorize` hook receives `origin` on
|
|
126
126
|
`messages.create`, and a deployment that hands a credential to something that only relays (a
|
|
127
127
|
webhook bridge, a teammate agent) can refuse it anything else.
|
|
128
|
+
|
|
129
|
+
A worker serves many tenants by default, and refuses what would leak between them or run outside
|
|
130
|
+
the sandbox: a session whose environment does not come from the environment registry, a harness
|
|
131
|
+
holding process-wide MCP connections or an OAuth service, MCP over stdio, and a token read from
|
|
132
|
+
the process environment. A self-hosted, one-owner deployment says so —
|
|
133
|
+
`new SessionWorker({ profile: "single-tenant", … })` — and the worker logs that it did.
|
|
134
|
+
|
|
135
|
+
What a host decides per tenant goes through the registries, which are told whose session they
|
|
136
|
+
resolve for: `resolve(ref, { sessionId, ownerKey, metadata })`. `ownerKey` is stamped by the
|
|
137
|
+
service and trustworthy; `metadata` came from the client. Per-user MCP credentials — a vault —
|
|
138
|
+
are a provider the agent registry hands out, asked on every connect:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
const agents: ManagedAgentRegistry = {
|
|
142
|
+
resolve: (_ref, { ownerKey }) => ({
|
|
143
|
+
resumeOptions: {
|
|
144
|
+
mcpServers: { linear: { transport: "http", url: "https://mcp.linear.app/mcp" } },
|
|
145
|
+
mcpCredentials: {
|
|
146
|
+
credentialsFor: async ({ url }) => {
|
|
147
|
+
const token = await vault.tokenFor(ownerKey!, url); // the host's store, refresh, lock
|
|
148
|
+
return token === undefined ? undefined : { headers: { Authorization: `Bearer ${token}` } };
|
|
149
|
+
},
|
|
150
|
+
invalidate: ({ url }) => vault.refresh(ownerKey!, url), // on a 401; the connect retries once
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
}),
|
|
154
|
+
};
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
The engine never stores, refreshes or logs a credential, and since the MCP client runs in the
|
|
158
|
+
worker, a credential never enters the sandbox. The rules and their reasons are in
|
|
159
|
+
`docs/server-profile.md`.
|
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
import type { Agent, CreateSessionOptions, Harness, Environment, EnvironmentFactory, ResumeSessionOptions } from "operon-agents";
|
|
2
2
|
import type { AgentRef, EnvironmentRef } from "../protocol/types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Which session a registry is resolving for. Handed to both registries by the service at create
|
|
5
|
+
* and by the worker on every open, so a host can choose per session — per tenant — the agent,
|
|
6
|
+
* the environment and the credentials (`resumeOptions.mcpCredentials`) it runs with.
|
|
7
|
+
*/
|
|
8
|
+
export interface ManagedSessionContext {
|
|
9
|
+
readonly sessionId: string;
|
|
10
|
+
/** Stamped by `SessionService({ ownerKey })` at create. Trusted: no client can set it. */
|
|
11
|
+
readonly ownerKey?: string;
|
|
12
|
+
/**
|
|
13
|
+
* The create request's `metadata`. Untrusted: a client wrote it. A host that acts on it (a
|
|
14
|
+
* vault id, a repository) must check it against `ownerKey`, or a client names another
|
|
15
|
+
* tenant's.
|
|
16
|
+
*/
|
|
17
|
+
readonly metadata?: Readonly<Record<string, unknown>>;
|
|
18
|
+
}
|
|
3
19
|
export interface AgentResolution<TContext = unknown> {
|
|
4
20
|
readonly agent?: Agent<TContext>;
|
|
5
21
|
readonly createOptions?: Omit<CreateSessionOptions<TContext>, "id" | "title" | "workDir" | "agent">;
|
|
6
22
|
readonly resumeOptions?: Omit<ResumeSessionOptions<TContext>, "agent">;
|
|
7
23
|
}
|
|
8
24
|
export interface ManagedAgentRegistry<TContext = unknown> {
|
|
9
|
-
resolve(ref: AgentRef): AgentResolution<TContext> | Promise<AgentResolution<TContext>>;
|
|
25
|
+
resolve(ref: AgentRef, session: ManagedSessionContext): AgentResolution<TContext> | Promise<AgentResolution<TContext>>;
|
|
10
26
|
}
|
|
11
27
|
/** Let managed sessions use the Harness's configured default Agent. */
|
|
12
28
|
export declare class DefaultAgentRegistry<TContext = unknown> implements ManagedAgentRegistry<TContext> {
|
|
@@ -21,7 +37,7 @@ export interface EnvironmentResolution {
|
|
|
21
37
|
readonly environment?: Environment | EnvironmentFactory;
|
|
22
38
|
}
|
|
23
39
|
export interface ManagedEnvironmentRegistry {
|
|
24
|
-
resolve(ref: EnvironmentRef): EnvironmentResolution | Promise<EnvironmentResolution>;
|
|
40
|
+
resolve(ref: EnvironmentRef, session: ManagedSessionContext): EnvironmentResolution | Promise<EnvironmentResolution>;
|
|
25
41
|
}
|
|
26
42
|
export declare class StaticEnvironmentRegistry implements ManagedEnvironmentRegistry {
|
|
27
43
|
private readonly environments;
|
|
@@ -82,9 +82,13 @@ export class SessionService {
|
|
|
82
82
|
async create(request) {
|
|
83
83
|
const input = parseRequest(CreateSessionRequestSchema, request);
|
|
84
84
|
const { agent, environment } = input;
|
|
85
|
-
const resolved = await this.environments.resolve(environment);
|
|
86
|
-
const now = Date.now();
|
|
87
85
|
const sessionId = input.id ?? managedSessionId();
|
|
86
|
+
const resolved = await this.environments.resolve(environment, {
|
|
87
|
+
sessionId,
|
|
88
|
+
...(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : {}),
|
|
89
|
+
...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
|
|
90
|
+
});
|
|
91
|
+
const now = Date.now();
|
|
88
92
|
// Metadata is the write-ahead identity record: after the repository commits, a crash must
|
|
89
93
|
// never leave a durable session the managed layer cannot resolve on restart.
|
|
90
94
|
const claimed = await this.metadata.create({
|
|
@@ -75,6 +75,14 @@ export interface SessionWorkerOptions<TContext = unknown> {
|
|
|
75
75
|
* to that session wakes it again. Default: `console.error`.
|
|
76
76
|
*/
|
|
77
77
|
readonly onError?: (error: unknown, sessionId: string) => void;
|
|
78
|
+
/**
|
|
79
|
+
* Who this worker's sessions belong to. `"multi-tenant"` (the default) refuses what would leak
|
|
80
|
+
* across tenants or run outside the sandbox: an environment not from the registry, a harness
|
|
81
|
+
* holding process-wide MCP connections or an OAuth service, MCP over stdio, a token read from
|
|
82
|
+
* the process environment. `"single-tenant"` lifts all of that for a self-hosted, one-owner
|
|
83
|
+
* deployment, and says so once at construction. See docs/server-profile.md.
|
|
84
|
+
*/
|
|
85
|
+
readonly profile?: "multi-tenant" | "single-tenant";
|
|
78
86
|
}
|
|
79
87
|
export declare class SessionWorker<TContext = unknown> {
|
|
80
88
|
private readonly harness;
|
|
@@ -88,6 +96,9 @@ export declare class SessionWorker<TContext = unknown> {
|
|
|
88
96
|
private readonly concurrency;
|
|
89
97
|
private readonly broadcaster;
|
|
90
98
|
private readonly onError;
|
|
99
|
+
private readonly multiTenant;
|
|
100
|
+
/** The harness check, run once and remembered — a misconfigured harness fails every open alike. */
|
|
101
|
+
private harnessChecked;
|
|
91
102
|
private readonly running;
|
|
92
103
|
/** Runs the claim loop started, counted synchronously so the cap is exact; nudges are not. */
|
|
93
104
|
private claimed;
|
|
@@ -95,6 +106,8 @@ export declare class SessionWorker<TContext = unknown> {
|
|
|
95
106
|
private stopping;
|
|
96
107
|
private interruptPause;
|
|
97
108
|
constructor(options: SessionWorkerOptions<TContext>);
|
|
109
|
+
/** Multi-tenant only: the harness must not carry what every session on the process would share. */
|
|
110
|
+
private checkHarness;
|
|
98
111
|
/** Begin claiming. Without this a worker only runs what it is nudged about in-process. */
|
|
99
112
|
start(): void;
|
|
100
113
|
/**
|
|
@@ -52,6 +52,9 @@ export class SessionWorker {
|
|
|
52
52
|
concurrency;
|
|
53
53
|
broadcaster;
|
|
54
54
|
onError;
|
|
55
|
+
multiTenant;
|
|
56
|
+
/** The harness check, run once and remembered — a misconfigured harness fails every open alike. */
|
|
57
|
+
harnessChecked;
|
|
55
58
|
running = new Map();
|
|
56
59
|
/** Runs the claim loop started, counted synchronously so the cap is exact; nudges are not. */
|
|
57
60
|
claimed = 0;
|
|
@@ -70,6 +73,17 @@ export class SessionWorker {
|
|
|
70
73
|
this.concurrency = options.concurrency ?? 16;
|
|
71
74
|
this.broadcaster = options.broadcaster;
|
|
72
75
|
this.onError = options.onError ?? ((error, sessionId) => { console.error(`session ${sessionId}:`, error); });
|
|
76
|
+
this.multiTenant = options.profile !== "single-tenant";
|
|
77
|
+
if (!this.multiTenant) {
|
|
78
|
+
console.warn("SessionWorker: single-tenant profile — sessions may share process-wide MCP connections and credentials, run MCP over stdio, and run in the worker's own environment.");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Multi-tenant only: the harness must not carry what every session on the process would share. */
|
|
82
|
+
async checkHarness() {
|
|
83
|
+
const shared = (await this.harness.processSharedParts()).filter((part) => part !== "skillRegistry");
|
|
84
|
+
if (shared.length > 0) {
|
|
85
|
+
throw new Error(`server profile: the harness shares ${shared.join(" and ")} across every session in the process, which on a multi-tenant worker is across tenants. Build them per session (resumeOptions.mcpServers / mcpCredentials), or run the worker with profile: "single-tenant".`);
|
|
86
|
+
}
|
|
73
87
|
}
|
|
74
88
|
/** Begin claiming. Without this a worker only runs what it is nudged about in-process. */
|
|
75
89
|
start() {
|
|
@@ -220,16 +234,39 @@ export class SessionWorker {
|
|
|
220
234
|
}
|
|
221
235
|
}
|
|
222
236
|
async openSession(sessionId, metadata) {
|
|
237
|
+
// The owner is the repository's record, not the managed metadata: it is what the service
|
|
238
|
+
// stamped at create, and what a registry may trust.
|
|
239
|
+
const ownerKey = (await this.repository.get(sessionId))?.ownerKey;
|
|
240
|
+
const context = {
|
|
241
|
+
sessionId,
|
|
242
|
+
...(ownerKey !== undefined ? { ownerKey } : {}),
|
|
243
|
+
...(metadata.metadata !== undefined ? { metadata: metadata.metadata } : {}),
|
|
244
|
+
};
|
|
223
245
|
const [agentResolution, environmentResolution] = await Promise.all([
|
|
224
|
-
this.agents.resolve(metadata.agent),
|
|
225
|
-
this.environments.resolve(metadata.environment),
|
|
246
|
+
this.agents.resolve(metadata.agent, context),
|
|
247
|
+
this.environments.resolve(metadata.environment, context),
|
|
226
248
|
]);
|
|
249
|
+
if (this.multiTenant) {
|
|
250
|
+
await (this.harnessChecked ??= this.checkHarness());
|
|
251
|
+
if (environmentResolution.environment === undefined) {
|
|
252
|
+
throw new Error(`server profile: environment "${metadata.environment.id}" resolved no environment for session ${sessionId}, so its tools would run in the harness's own. Return one per session from the environment registry, or run the worker with profile: "single-tenant".`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
227
255
|
const session = await this.harness.resumeSession(sessionId, {
|
|
228
256
|
...agentResolution.resumeOptions,
|
|
229
257
|
...(environmentResolution.environment !== undefined ? { environment: environmentResolution.environment } : {}),
|
|
230
258
|
...(agentResolution.agent !== undefined ? { agent: agentResolution.agent } : {}),
|
|
259
|
+
...(this.multiTenant ? { strictIsolation: true } : {}),
|
|
231
260
|
eventPublication: "committed",
|
|
232
261
|
});
|
|
262
|
+
if (this.multiTenant) {
|
|
263
|
+
// A custom `session` hook may ignore `strictIsolation`; what it connected is still visible.
|
|
264
|
+
const local = (session.mcp?.list() ?? []).filter((view) => view.transport !== "http");
|
|
265
|
+
if (local.length > 0) {
|
|
266
|
+
await session.close();
|
|
267
|
+
throw new Error(`server profile: MCP server ${local.map((view) => `"${view.name}"`).join(", ")} runs over ${local[0].transport}, a process on the worker host outside the sandbox. Serve it over http, or run the worker with profile: "single-tenant".`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
233
270
|
if (this.broadcaster !== undefined) {
|
|
234
271
|
// Not unsubscribed: the subscription dies with the session it is attached to.
|
|
235
272
|
session.onEvent((event) => { this.broadcaster?.publish(sessionId, event); });
|
|
@@ -252,7 +289,12 @@ export class SessionWorker {
|
|
|
252
289
|
*/
|
|
253
290
|
async processInbox(session, store, halted, wake) {
|
|
254
291
|
const consumed = new Set();
|
|
292
|
+
const settledInBackground = new Wakeup();
|
|
255
293
|
const unsubscribe = session.onEvent((event) => {
|
|
294
|
+
if (event.type === "background.task.terminated") {
|
|
295
|
+
settledInBackground.raise();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
256
298
|
if (event.type !== "message.appended")
|
|
257
299
|
return;
|
|
258
300
|
// A message is in the conversation when its journal record carries the steer it came in
|
|
@@ -271,6 +313,34 @@ export class SessionWorker {
|
|
|
271
313
|
// contiguous consumed prefix, so an item can never be skipped by a later one landing first.
|
|
272
314
|
const outstanding = [];
|
|
273
315
|
let resuming;
|
|
316
|
+
// A background task lives in THIS object: closing it orphans the task, and whoever opens the
|
|
317
|
+
// session next reconciles the orphan to `lost` while it may still be running here. So while
|
|
318
|
+
// one is live the session stays open and the lease stays held — until it settles (its
|
|
319
|
+
// notification wakes a run like any input) or something new arrives. True: go around.
|
|
320
|
+
//
|
|
321
|
+
// A settle that lands just as the last run ends has already queued its notification, and
|
|
322
|
+
// the idle wake starts a run for it a microtask later. Closing then would abort that run,
|
|
323
|
+
// so a run in flight — or one a tick away — is also a reason to go around.
|
|
324
|
+
// Read through a call: `status` is a live getter, and a narrowed property would not see the
|
|
325
|
+
// run the tick below starts.
|
|
326
|
+
const state = () => session.status.state;
|
|
327
|
+
const busy = async () => {
|
|
328
|
+
if (state() === "running")
|
|
329
|
+
return true;
|
|
330
|
+
if (state() !== "idle" || !session.status.hasQueuedMessages)
|
|
331
|
+
return false;
|
|
332
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
333
|
+
return state() === "running";
|
|
334
|
+
};
|
|
335
|
+
const holdOpen = async () => {
|
|
336
|
+
settledInBackground.take();
|
|
337
|
+
if (await busy())
|
|
338
|
+
return !halted();
|
|
339
|
+
if ((session.background?.list(true).length ?? 0) === 0)
|
|
340
|
+
return false;
|
|
341
|
+
await Promise.race([settledInBackground.wait(), wake.wait()]);
|
|
342
|
+
return !halted();
|
|
343
|
+
};
|
|
274
344
|
const advance = async () => {
|
|
275
345
|
let moved = false;
|
|
276
346
|
while (outstanding.length > 0 && consumed.has(inboxItemId(outstanding[0]))) {
|
|
@@ -306,8 +376,11 @@ export class SessionWorker {
|
|
|
306
376
|
// they are done, not dispatchable. Without a resume there is nothing to do but wait.
|
|
307
377
|
if (session.status.state === "interrupted" && resuming === undefined) {
|
|
308
378
|
const resumeAt = items.findIndex((item) => item.kind === "control" && item.command.kind === "resume");
|
|
309
|
-
if (resumeAt === -1)
|
|
379
|
+
if (resumeAt === -1) {
|
|
380
|
+
if (await holdOpen())
|
|
381
|
+
continue;
|
|
310
382
|
break;
|
|
383
|
+
}
|
|
311
384
|
for (const item of items.slice(0, resumeAt)) {
|
|
312
385
|
outstanding.push(item);
|
|
313
386
|
consumed.add(inboxItemId(item));
|
|
@@ -340,10 +413,11 @@ export class SessionWorker {
|
|
|
340
413
|
resuming = undefined;
|
|
341
414
|
}
|
|
342
415
|
await advance();
|
|
343
|
-
// Idle and nothing new: done
|
|
344
|
-
// ended without taking it; it is still after
|
|
345
|
-
// append, or the next claim — requeues it again
|
|
346
|
-
|
|
416
|
+
// Idle and nothing new: done, unless a background task still needs this object. Anything
|
|
417
|
+
// still outstanding was requeued to a run that ended without taking it; it is still after
|
|
418
|
+
// the cursor, and the next run — the next append, or the next claim — requeues it again
|
|
419
|
+
// on a fresh object.
|
|
420
|
+
if (settled === "idle" && items.length === 0 && !(await holdOpen()))
|
|
347
421
|
break;
|
|
348
422
|
}
|
|
349
423
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "operon-managed-agents",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.18",
|
|
4
4
|
"description": "Managed server and TypeScript client for operon-agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -44,11 +44,11 @@
|
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"zod": "^4.0.0",
|
|
47
|
-
"operon-agents": "0.1.0-alpha.
|
|
47
|
+
"operon-agents": "0.1.0-alpha.18"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@earendil-works/pi-ai": "
|
|
51
|
-
"operon-agents-core": "0.1.0-alpha.
|
|
50
|
+
"@earendil-works/pi-ai": "1.3.0",
|
|
51
|
+
"operon-agents-core": "0.1.0-alpha.18"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"clean": "rm -rf dist *.tsbuildinfo",
|