operon-managed-agents 0.1.0-alpha.2 → 0.1.0-alpha.21

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,5 +1,5 @@
1
1
  /**
2
- * The execution half: moves a session's inbox into its conversation, and runs it.
2
+ * The execution half: puts a session's accepted messages back on its bus, and runs it.
3
3
  *
4
4
  * A worker is not part of the API surface and does not look for work on its own terms. It
5
5
  * claims from the work table (`SessionWork`) — one row per session that has been appended to
@@ -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
- ...(environmentResolution.machine !== undefined ? { machine: environmentResolution.machine } : {}),
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); });
@@ -237,14 +274,12 @@ export class SessionWorker {
237
274
  return session;
238
275
  }
239
276
  /**
240
- * Hand inbox items to the session in log order, advancing the cursor as soon as each one is
241
- * in the conversation.
277
+ * Put inbox items back on the session's bus in log order, advancing the cursor as soon as
278
+ * each one is in the conversation.
242
279
  *
243
- * "In the conversation" is the `message.appended` that names the item's delivery — for a
244
- * steer, that is some step boundary of the running turn, which is why the cursor cannot
245
- * simply move on dispatch. For an input that STARTED a turn, the turn settling counts too:
246
- * a guardrail can refuse the input without ever journaling a message, and the input is no
247
- * less dealt with for it.
280
+ * "In the conversation" is the `message.appended` whose `origin.steerId` names the item — for
281
+ * a steer into a running turn, that is some step boundary of that turn, which is why the
282
+ * cursor cannot simply move on requeue. A resume is done when the run it continued settles.
248
283
  *
249
284
  * While a turn runs, the inbox is re-read on every wake — a nudge from this process, or a
250
285
  * heartbeat that came back `woken` — so a message steers the turn and a cancel stops it,
@@ -254,23 +289,58 @@ export class SessionWorker {
254
289
  */
255
290
  async processInbox(session, store, halted, wake) {
256
291
  const consumed = new Set();
292
+ const settledInBackground = new Wakeup();
257
293
  const unsubscribe = session.onEvent((event) => {
294
+ if (event.type === "background.task.terminated") {
295
+ settledInBackground.raise();
296
+ return;
297
+ }
258
298
  if (event.type !== "message.appended")
259
299
  return;
260
- const origin = event.origin;
261
- if (origin?.kind !== "external")
300
+ // A message is in the conversation when its journal record carries the steer it came in
301
+ // as — whatever kind of origin it was filed under.
302
+ const steerId = event.origin !== undefined && "steerId" in event.origin ? event.origin.steerId : undefined;
303
+ if (steerId === undefined)
262
304
  return;
263
- consumed.add(origin.deliveryId);
305
+ consumed.add(steerId);
264
306
  // Persist the cursor now, not when the turn ends: a holder that dies in between must not
265
307
  // leave an input that IS in the conversation looking like one that is not.
266
308
  wake.raise();
267
309
  });
268
310
  try {
269
311
  let cursor = await readInboxCursor(store);
270
- // Dispatched, not yet in the conversation, in log order. The cursor advances across the
312
+ // Requeued, not yet in the conversation, in log order. The cursor advances across the
271
313
  // contiguous consumed prefix, so an item can never be skipped by a later one landing first.
272
314
  const outstanding = [];
273
- let completion;
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]))) {
@@ -285,9 +355,9 @@ export class SessionWorker {
285
355
  break;
286
356
  wake.take();
287
357
  const items = [...await readInbox(store, cursor, new Set(outstanding.map((item) => item.sequence)))];
288
- // A cancel discards everything that precedes it: the turn in flight, inputs dispatched
289
- // to it but not yet taken, and inputs in this batch that never got dispatched. "Stop"
290
- // means stop, not "stop, then carry on with what was queued".
358
+ // A cancel discards everything that precedes it: the turn in flight, inputs requeued
359
+ // but not yet taken, and inputs in this batch that never got requeued. "Stop" means
360
+ // stop, not "stop, then carry on with what was queued".
291
361
  const lastCancel = findLastIndex(items, (item) => item.kind === "control" && item.command.kind === "cancel");
292
362
  if (lastCancel !== -1) {
293
363
  for (const item of outstanding)
@@ -296,20 +366,21 @@ export class SessionWorker {
296
366
  outstanding.push(item);
297
367
  consumed.add(inboxItemId(item));
298
368
  }
299
- if (completion !== undefined) {
300
- session.cancel();
301
- await completion;
302
- }
369
+ session.cancel();
370
+ await session.whenIdle();
303
371
  await advance();
304
372
  return true;
305
373
  }
306
374
  // Paused for an answer: inputs ahead of the resume that answers it are the ones the
307
375
  // paused turn already took (the service accepts no new input while interrupted), so
308
376
  // they are done, not dispatchable. Without a resume there is nothing to do but wait.
309
- if (session.status.state === "interrupted" && completion === undefined) {
377
+ if (session.status.state === "interrupted" && resuming === undefined) {
310
378
  const resumeAt = items.findIndex((item) => item.kind === "control" && item.command.kind === "resume");
311
- if (resumeAt === -1)
379
+ if (resumeAt === -1) {
380
+ if (await holdOpen())
381
+ continue;
312
382
  break;
383
+ }
313
384
  for (const item of items.slice(0, resumeAt)) {
314
385
  outstanding.push(item);
315
386
  consumed.add(inboxItemId(item));
@@ -320,42 +391,33 @@ export class SessionWorker {
320
391
  if (halted())
321
392
  break;
322
393
  outstanding.push(item);
323
- const id = inboxItemId(item);
324
394
  if (item.kind === "input") {
325
- const receipt = session.dispatchAccepted(item.input, {
326
- kind: "external",
327
- source: item.origin.source,
328
- deliveryId: item.origin.deliveryId,
329
- channel: item.mode === "follow_up" ? "follow_up" : "steering",
330
- ...(item.origin.actor !== undefined ? { actor: item.origin.actor } : {}),
331
- ...(item.origin.metadata !== undefined ? { metadata: item.origin.metadata } : {}),
332
- });
333
- if (receipt.completion !== undefined) {
334
- // Resolved: the turn ran to some end (answered, refused by a guardrail, paused)
335
- // and the input is dealt with even if no message ever named it. Rejected: the
336
- // turn failed; if the message got in, `message.appended` already said so, and if
337
- // it did not, the input is still after the cursor for the next drain.
338
- completion = receipt.completion.then(() => { consumed.add(id); }, () => undefined);
339
- }
395
+ // Its `steer.queued` record exists — that is how it got here. Back on the bus, which
396
+ // steers a running turn or wakes an idle session, exactly as a live enqueue would.
397
+ session.requeue(item.item);
340
398
  }
341
399
  else if (item.command.kind === "resume") {
342
- completion = session.resume({ ...item.command.answers }).then(() => { consumed.add(id); }, () => { consumed.add(id); });
400
+ const id = inboxItemId(item);
401
+ // Settled either way: a resume that failed is not going to succeed by being re-read.
402
+ resuming = session.resume({ ...item.command.answers }).then(() => { consumed.add(id); }, () => { consumed.add(id); });
343
403
  }
344
404
  }
345
- if (completion !== undefined) {
346
- // A turn is running. Sleep until it ends or something new arrives, whichever first.
347
- const settled = await Promise.race([
348
- completion.then(() => "done"),
349
- wake.wait().then(() => "woken"),
350
- ]);
351
- if (settled === "done")
352
- completion = undefined;
405
+ // Sleep until the session is idle or something new arrives, whichever first. `whenIdle`
406
+ // counts the run a requeue above just woke.
407
+ const settled = await Promise.race([
408
+ session.whenIdle().then(() => "idle"),
409
+ wake.wait().then(() => "woken"),
410
+ ]);
411
+ if (settled === "idle") {
412
+ await resuming;
413
+ resuming = undefined;
353
414
  }
354
415
  await advance();
355
- // Nothing running and nothing new: done. Anything still outstanding was dispatched to a
356
- // turn that ended without taking it; it is still after the cursor, and the next run —
357
- // the next append, or the next claim — dispatches it again on a fresh object.
358
- if (completion === undefined && items.length === 0)
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()))
359
421
  break;
360
422
  }
361
423
  }
@@ -11,8 +11,8 @@
11
11
  * - `claim` takes the lease on one woken (or abandoned) session. Taking it IS the claim; there
12
12
  * is no separate "dispatched" state that could disagree with "held".
13
13
  * - `renew` is the holder's heartbeat, and carries the only signal a holder gets from other
14
- * nodes: whether anything was appended since it last looked. A cancel reaches the machine
15
- * running the turn this way — no address for that machine is needed anywhere.
14
+ * nodes: whether anything was appended since it last looked. A cancel reaches the environment
15
+ * running the turn this way — no address for that environment is needed anywhere.
16
16
  *
17
17
  * A worker that dies leaves its row held past its TTL. The next `claim` takes such a row like
18
18
  * any other: an abandoned session is work, whether or not anything new was appended to it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "operon-managed-agents",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.21",
4
4
  "description": "Managed server and TypeScript client for operon-agents.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -43,12 +43,12 @@
43
43
  "README.md"
44
44
  ],
45
45
  "dependencies": {
46
- "operon-agents": "0.1.0-alpha.2"
46
+ "zod": "^4.0.0",
47
+ "operon-agents": "0.1.0-alpha.21"
47
48
  },
48
49
  "devDependencies": {
49
- "@earendil-works/pi-ai": "0.84.1",
50
- "zod": "^4.0.0",
51
- "operon-agents-core": "0.1.0-alpha.2"
50
+ "@earendil-works/pi-ai": "1.3.0",
51
+ "operon-agents-core": "0.1.0-alpha.21"
52
52
  },
53
53
  "scripts": {
54
54
  "clean": "rm -rf dist *.tsbuildinfo",