operon-managed-agents 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.
package/README.md CHANGED
@@ -58,10 +58,13 @@ for await (const event of stream) {
58
58
  // stream.lastEventId is the cursor to continue from elsewhere.
59
59
  ```
60
60
 
61
+ `sessions.update(id, { title })` renames a session (`PATCH /v1/sessions/{id}`); the title is the
62
+ only field a client can change after creation, and it is durable before the call resolves.
63
+
61
64
  `run()` sends one input and resolves when the turn that took **that** delivery ends — not the
62
65
  first `turn.ended` in the replay, which on a session with history belongs to an older turn.
63
66
 
64
- The server accepts an `authorize(request, { action, sessionId })` hook. Configure it for any
67
+ The server accepts an `authorize(request, { action, sessionId, origin })` hook. Configure it for any
65
68
  networked deployment; it can verify credentials and enforce per-session ownership. The
66
69
  bundled in-memory idempotency store is atomic within one process and bounded by TTL/capacity;
67
70
  distributed deployments should provide a database-backed `ManagedDeliveryIdempotencyStore`.
@@ -101,3 +104,24 @@ await client.sessions.messages.create(
101
104
  { idempotencyKey: requestId },
102
105
  );
103
106
  ```
107
+
108
+ Whose words a delivery is, the caller says. The party holding a session's credential is its
109
+ user — the way a local session's stdin is — so by default `messages.create` delivers the
110
+ caller's own words and the model sees them bare, as a prompt. A caller relaying someone else's
111
+ words declares it:
112
+
113
+ ```ts
114
+ await client.sessions.messages.create(session.id, {
115
+ input: "deploy finished: 3 warnings",
116
+ origin: "external",
117
+ source: "ci",
118
+ actor: "deploy-bot",
119
+ });
120
+ ```
121
+
122
+ The model then sees the text inside an `<external-message>` envelope stamped as not from the
123
+ user — not an approval, not an answer to anything it asked. `source`, `actor` and `metadata`
124
+ describe the relay and are refused without the declaration. Declaring `external` lowers trust,
125
+ so it needs no permission of its own; the `authorize` hook receives `origin` on
126
+ `messages.create`, and a deployment that hands a credential to something that only relays (a
127
+ webhook bridge, a teammate agent) can refuse it anything else.
@@ -1,6 +1,6 @@
1
1
  import type { AgentEvent, InterruptAnswer } from "operon-agents";
2
2
  import { type SseFrame } from "../protocol/sse.ts";
3
- import type { CancelManagedSessionResponse, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, InterruptionsResponse, ListSessionEventsOptions, ListSessionEventsResponse, ListManagedSessionsResponse, ManagedSession, ResumeManagedSessionResponse, StreamSessionEventsOptions } from "../protocol/types.ts";
3
+ import type { CancelManagedSessionResponse, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, InterruptionsResponse, ListSessionEventsOptions, ListSessionEventsResponse, ListManagedSessionsResponse, ManagedSession, ResumeManagedSessionResponse, StreamSessionEventsOptions, UpdateManagedSessionRequest } from "../protocol/types.ts";
4
4
  export interface ManagedAgentsClientOptions {
5
5
  readonly baseUrl: string;
6
6
  readonly apiKey?: string;
@@ -48,6 +48,8 @@ export declare class ManagedSessionsClient {
48
48
  create(request: CreateManagedSessionRequest): Promise<ManagedSession>;
49
49
  list(): Promise<ListManagedSessionsResponse>;
50
50
  retrieve(sessionId: string): Promise<ManagedSession>;
51
+ /** Rename a session; the new title is durable before this resolves. */
52
+ update(sessionId: string, request: UpdateManagedSessionRequest): Promise<ManagedSession>;
51
53
  messages: {
52
54
  create: (sessionId: string, request: CreateManagedMessageRequest, options?: CreateManagedMessageOptions) => Promise<DeliveryReceiptResource>;
53
55
  };
@@ -129,6 +129,10 @@ export class ManagedSessionsClient {
129
129
  retrieve(sessionId) {
130
130
  return this.root.request(`/sessions/${encodeURIComponent(sessionId)}`);
131
131
  }
132
+ /** Rename a session; the new title is durable before this resolves. */
133
+ update(sessionId, request) {
134
+ return this.root.request(`/sessions/${encodeURIComponent(sessionId)}`, { method: "PATCH", body: request });
135
+ }
132
136
  messages = {
133
137
  create: (sessionId, request, options = {}) => this.root.request(`/sessions/${encodeURIComponent(sessionId)}/messages`, {
134
138
  method: "POST",
@@ -60,14 +60,14 @@ export async function run(client, sessionId, input, options = {}) {
60
60
  continue;
61
61
  if (event.type === "turn.started") {
62
62
  currentTurn = event.turnId;
63
- if (claimNextTurn || (event.origin?.kind === "external" && event.origin.deliveryId === deliveryId)) {
63
+ if (claimNextTurn || deliveryOf(event.origin) === deliveryId) {
64
64
  ourTurn = event.turnId;
65
65
  claimNextTurn = false;
66
66
  }
67
67
  continue;
68
68
  }
69
69
  if (event.type === "message.appended") {
70
- if (ourTurn === undefined && event.origin?.kind === "external" && event.origin.deliveryId === deliveryId) {
70
+ if (ourTurn === undefined && deliveryOf(event.origin) === deliveryId) {
71
71
  // Inside a turn: a steer, and that turn is ours. Between turns: the prompt was
72
72
  // journaled ahead of its turn, so the next one to start is ours.
73
73
  if (currentTurn !== undefined)
@@ -141,4 +141,14 @@ function textOf(content) {
141
141
  .map((part) => part.text);
142
142
  return parts.length === 0 ? undefined : parts.join("");
143
143
  }
144
+ /**
145
+ * The delivery a journaled prompt — or the turn it started — came in as, on whichever origin it
146
+ * was filed under: `user` for the caller's own words, `external` for a relayed party's. Undefined
147
+ * for everything else in the user role (reminders, compaction summaries): those answer no delivery.
148
+ */
149
+ function deliveryOf(origin) {
150
+ return origin?.kind === "user" || origin?.kind === "user_follow_up" || origin?.kind === "external"
151
+ ? origin.deliveryId
152
+ : undefined;
153
+ }
144
154
  //# sourceMappingURL=run.js.map
@@ -27,13 +27,32 @@ export interface CreateManagedSessionRequest {
27
27
  readonly environment: EnvironmentRef | string;
28
28
  readonly metadata?: Readonly<Record<string, unknown>>;
29
29
  }
30
+ /** `PATCH /sessions/{id}`: rename a session. Only the title is client-writable after creation. */
31
+ export interface UpdateManagedSessionRequest {
32
+ readonly title: string;
33
+ }
30
34
  export interface ListManagedSessionsResponse {
31
35
  readonly data: readonly ManagedSession[];
32
36
  }
33
37
  export interface CreateManagedMessageRequest {
34
38
  readonly input: string;
39
+ /**
40
+ * Whose words these are.
41
+ *
42
+ * `user` (default): the caller's own. The party holding a session's credential is its user —
43
+ * the same way a local session's stdin is — so the model sees the text bare, as a prompt.
44
+ *
45
+ * `external`: another party's words the caller is relaying (a peer, a webhook, another
46
+ * agent). The model sees them inside an `<external-message>` envelope stamped as NOT from the
47
+ * user. Declaring this lowers trust, so it needs no extra permission; the server's `authorize`
48
+ * hook receives the value and can require it for a credential that only ever relays.
49
+ */
50
+ readonly origin?: "user" | "external";
51
+ /** `external` only: what relayed the words (default `"managed-api"`). */
35
52
  readonly source?: string;
53
+ /** `external` only: who said them. */
36
54
  readonly actor?: string;
55
+ /** `external` only: attributes rendered onto the envelope. */
37
56
  readonly metadata?: Readonly<Record<string, string | number | boolean | null>>;
38
57
  readonly mode?: "auto" | "steer" | "follow_up";
39
58
  }
@@ -1,10 +1,16 @@
1
1
  import { type IncomingMessage, type Server } from "node:http";
2
2
  import type { SessionService } from "./session-service.ts";
3
3
  import type { SessionWorker } from "./session-worker.ts";
4
- export type ManagedAuthorizationAction = "sessions.create" | "sessions.list" | "sessions.read" | "sessions.delete" | "messages.create" | "events.list" | "events.stream" | "sessions.cancel" | "interruptions.list" | "sessions.resume";
4
+ export type ManagedAuthorizationAction = "sessions.create" | "sessions.list" | "sessions.read" | "sessions.update" | "sessions.delete" | "messages.create" | "events.list" | "events.stream" | "sessions.cancel" | "interruptions.list" | "sessions.resume";
5
5
  export interface ManagedAuthorizationContext {
6
6
  readonly action: ManagedAuthorizationAction;
7
7
  readonly sessionId?: string;
8
+ /**
9
+ * `messages.create` only: whose words the caller says these are. `user` is the default and
10
+ * makes the caller this session's user; a deployment that hands a credential to something
11
+ * that only relays (a webhook bridge, a teammate agent) can refuse it anything but `external`.
12
+ */
13
+ readonly origin?: "user" | "external";
8
14
  }
9
15
  export type ManagedAuthorize = (request: IncomingMessage, context: ManagedAuthorizationContext) => boolean | void | Promise<boolean | void>;
10
16
  /**
@@ -54,6 +54,11 @@ export function createManagedHttpServer(options) {
54
54
  await authorize(request, "sessions.read", sessionId);
55
55
  return sendJson(response, 200, await options.service.get(sessionId));
56
56
  }
57
+ if (method === "PATCH" && parts.length === 2) {
58
+ await authorize(request, "sessions.update", sessionId);
59
+ const body = await readJson(request, maxBodyBytes);
60
+ return sendJson(response, 200, await options.service.update(sessionId, body));
61
+ }
57
62
  if (method === "DELETE" && parts.length === 2) {
58
63
  await authorize(request, "sessions.delete", sessionId);
59
64
  await options.service.delete(sessionId);
@@ -62,8 +67,10 @@ export function createManagedHttpServer(options) {
62
67
  return;
63
68
  }
64
69
  if (method === "POST" && parts[2] === "messages" && parts.length === 3) {
65
- await authorize(request, "messages.create", sessionId);
70
+ // Body before authorization: the hook is told whose words the caller claims these are.
71
+ // Reading first costs an unauthenticated caller at most `maxBodyBytes` of parsing.
66
72
  const body = await readJson(request, maxBodyBytes);
73
+ await authorize(request, "messages.create", sessionId, body.origin === "external" ? "external" : "user");
67
74
  if (typeof body.input !== "string" || !body.input.trim()) {
68
75
  return sendJson(response, 400, apiError("invalid_request", "input must not be empty"));
69
76
  }
@@ -186,10 +193,11 @@ export function createManagedHttpServer(options) {
186
193
  response.write(": connected\n\n");
187
194
  manageStream(request, response, () => controller.abort());
188
195
  }
189
- async function authorize(request, action, sessionId) {
196
+ async function authorize(request, action, sessionId, origin) {
190
197
  const allowed = await options.authorize(request, {
191
198
  action,
192
199
  ...(sessionId !== undefined ? { sessionId } : {}),
200
+ ...(origin !== undefined ? { origin } : {}),
193
201
  });
194
202
  if (allowed === false)
195
203
  throw new ManagedForbiddenError();
@@ -12,8 +12,7 @@
12
12
  * read — set by the same write that creates an item, cleared by a holder about to read — never
13
13
  * the truth of it.
14
14
  */
15
- import type { InterruptAnswer, SessionStore } from "operon-agents";
16
- import type { ExternalOriginMetadataValue } from "operon-agents";
15
+ import type { InboxOrigin, InterruptAnswer, SessionStore } from "operon-agents";
17
16
  /** Where processing stopped. Everything at or before it has been dealt with. */
18
17
  export declare const INBOX_CURSOR_KEY = "inbox:cursor";
19
18
  /**
@@ -39,13 +38,8 @@ export interface InboxInput {
39
38
  readonly kind: "input";
40
39
  readonly sequence: string;
41
40
  readonly input: string;
42
- readonly origin: {
43
- readonly kind: "external";
44
- readonly source: string;
45
- readonly deliveryId: string;
46
- readonly actor?: string;
47
- readonly metadata?: Readonly<Record<string, ExternalOriginMetadataValue>>;
48
- };
41
+ /** Whose words: the session's user (`user`) or a relayed party (`external`). */
42
+ readonly origin: InboxOrigin;
49
43
  readonly mode: "auto" | "steer" | "follow_up";
50
44
  }
51
45
  export interface InboxControl {
@@ -15,7 +15,7 @@
15
15
  * simple event-stream subscription ends up billing for compute.
16
16
  */
17
17
  import { type AgentEvent, type DeleteSessionOptions, type InterruptAnswer, type PendingRunInterrupt, type SessionRepository } from "operon-agents";
18
- import type { ControlReceiptResource, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, ManagedSession } from "../protocol/types.ts";
18
+ import type { ControlReceiptResource, CreateManagedMessageRequest, CreateManagedSessionRequest, DeliveryReceiptResource, ManagedSession, UpdateManagedSessionRequest } from "../protocol/types.ts";
19
19
  import type { SessionWork } from "./work.ts";
20
20
  import { type ManagedSessionMetadataStore } from "./metadata.ts";
21
21
  import type { ManagedEnvironmentRegistry } from "./registries.ts";
@@ -115,6 +115,13 @@ export declare class SessionService {
115
115
  */
116
116
  create(input: CreateManagedSessionRequest): Promise<ManagedSession>;
117
117
  get(id: string): Promise<ManagedSession>;
118
+ /**
119
+ * Rename a session. The title lives in the session's own `meta` state, so the write goes
120
+ * through the store — the same path `create` takes — and reaches the repository catalog via
121
+ * the store's observer before this resolves. Like `interruptions`, it opens the store beside
122
+ * whoever may be running the session: `meta` is written by nobody during a turn.
123
+ */
124
+ update(id: string, input: UpdateManagedSessionRequest): Promise<ManagedSession>;
118
125
  list(): Promise<readonly ManagedSession[]>;
119
126
  listEvents(id: string, options: ListPersistedEventsOptions): Promise<PersistedEventPage>;
120
127
  /**
@@ -130,6 +130,30 @@ export class SessionService {
130
130
  const summary = await this.summary(id);
131
131
  return this.toManagedSession(summary, metadata);
132
132
  }
133
+ /**
134
+ * Rename a session. The title lives in the session's own `meta` state, so the write goes
135
+ * through the store — the same path `create` takes — and reaches the repository catalog via
136
+ * the store's observer before this resolves. Like `interruptions`, it opens the store beside
137
+ * whoever may be running the session: `meta` is written by nobody during a turn.
138
+ */
139
+ async update(id, input) {
140
+ assertUpdateSessionRequest(input);
141
+ const metadata = await this.requireMetadata(id);
142
+ await this.summary(id);
143
+ const handle = await this.repository.open(id);
144
+ if (handle === undefined)
145
+ throw new ManagedSessionNotFoundError(id);
146
+ try {
147
+ const meta = await handle.store.getState("meta");
148
+ if (!isRecord(meta))
149
+ throw new Error(`session "${id}" has no meta state`);
150
+ await handle.store.putState("meta", { ...meta, title: input.title, updatedAt: Date.now() });
151
+ }
152
+ finally {
153
+ await handle.store.close?.();
154
+ }
155
+ return this.toManagedSession(await this.summary(id), metadata);
156
+ }
133
157
  async list() {
134
158
  const summaries = await this.repository.list(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : undefined);
135
159
  const metadataById = await this.metadata.getMany(summaries.map((summary) => summary.id));
@@ -364,15 +388,20 @@ export class SessionService {
364
388
  time: acceptedAt,
365
389
  address: "main",
366
390
  input: request.input,
367
- origin: {
368
- kind: "external",
369
- source: request.source ?? "managed-api",
370
- deliveryId,
371
- ...(request.actor !== undefined ? { actor: request.actor } : {}),
372
- ...(request.metadata !== undefined
373
- ? { metadata: request.metadata }
374
- : {}),
375
- },
391
+ // Whose words, not which transport: the caller is this session's user unless it says it is
392
+ // relaying someone else's. `mode` is the record's own field, so the origin never carries
393
+ // `user_follow_up` — the worker files a `user` delivery by mode when it dispatches.
394
+ origin: request.origin === "external"
395
+ ? {
396
+ kind: "external",
397
+ source: request.source ?? "managed-api",
398
+ deliveryId,
399
+ ...(request.actor !== undefined ? { actor: request.actor } : {}),
400
+ ...(request.metadata !== undefined
401
+ ? { metadata: request.metadata }
402
+ : {}),
403
+ }
404
+ : { kind: "user", deliveryId },
376
405
  mode,
377
406
  });
378
407
  return {
@@ -518,12 +547,25 @@ function assertCreateSessionRequest(input) {
518
547
  agentRef(input.agent);
519
548
  environmentRef(input.environment);
520
549
  }
550
+ function assertUpdateSessionRequest(input) {
551
+ if (!isRecord(input))
552
+ throw new ManagedInvalidRequestError("request body must be an object");
553
+ if (typeof input.title !== "string" || !input.title.trim()) {
554
+ throw new ManagedInvalidRequestError("title must be a non-empty string");
555
+ }
556
+ }
521
557
  function assertCreateMessageRequest(input) {
522
558
  if (!isRecord(input))
523
559
  throw new ManagedInvalidRequestError("request body must be an object");
524
560
  if (typeof input.input !== "string" || !input.input.trim()) {
525
561
  throw new ManagedInvalidRequestError("input must not be empty");
526
562
  }
563
+ if (input.origin !== undefined && input.origin !== "user" && input.origin !== "external") {
564
+ throw new ManagedInvalidRequestError("origin must be user or external");
565
+ }
566
+ if (input.origin !== "external" && (input.source !== undefined || input.actor !== undefined || input.metadata !== undefined)) {
567
+ throw new ManagedInvalidRequestError('source, actor and metadata describe a relayed delivery; set origin: "external"');
568
+ }
527
569
  if (input.source !== undefined && (typeof input.source !== "string" || !input.source.trim())) {
528
570
  throw new ManagedInvalidRequestError("source must be a non-empty string");
529
571
  }
@@ -258,9 +258,14 @@ export class SessionWorker {
258
258
  if (event.type !== "message.appended")
259
259
  return;
260
260
  const origin = event.origin;
261
- if (origin?.kind !== "external")
261
+ // A delivery is in the conversation when a message carries its id — on whichever origin
262
+ // the delivery was filed under. A locally steered `user` message has no deliveryId.
263
+ const deliveryId = origin?.kind === "external" || origin?.kind === "user" || origin?.kind === "user_follow_up"
264
+ ? origin.deliveryId
265
+ : undefined;
266
+ if (deliveryId === undefined)
262
267
  return;
263
- consumed.add(origin.deliveryId);
268
+ consumed.add(deliveryId);
264
269
  // Persist the cursor now, not when the turn ends: a holder that dies in between must not
265
270
  // leave an input that IS in the conversation looking like one that is not.
266
271
  wake.raise();
@@ -322,14 +327,16 @@ export class SessionWorker {
322
327
  outstanding.push(item);
323
328
  const id = inboxItemId(item);
324
329
  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
- });
330
+ const receipt = session.dispatchAccepted(item.input, item.origin.kind === "external"
331
+ ? {
332
+ kind: "external",
333
+ source: item.origin.source,
334
+ deliveryId: item.origin.deliveryId,
335
+ channel: item.mode === "follow_up" ? "follow_up" : "steering",
336
+ ...(item.origin.actor !== undefined ? { actor: item.origin.actor } : {}),
337
+ ...(item.origin.metadata !== undefined ? { metadata: item.origin.metadata } : {}),
338
+ }
339
+ : { kind: item.mode === "follow_up" ? "user_follow_up" : "user", deliveryId: item.origin.deliveryId });
333
340
  if (receipt.completion !== undefined) {
334
341
  // Resolved: the turn ran to some end (answered, refused by a guardrail, paused)
335
342
  // and the input is dealt with even if no message ever named it. Rejected: the
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.4",
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
+ "operon-agents": "0.1.0-alpha.4"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@earendil-works/pi-ai": "0.84.1",
50
50
  "zod": "^4.0.0",
51
- "operon-agents-core": "0.1.0-alpha.2"
51
+ "operon-agents-core": "0.1.0-alpha.4"
52
52
  },
53
53
  "scripts": {
54
54
  "clean": "rm -rf dist *.tsbuildinfo",