@zvada/agent-server 0.3.26 → 0.3.27

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 (124) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/client/client.js +27 -11
  4. package/dist/client/connection.js +35 -3
  5. package/dist/core/agents/claude-code/approvals.js +1 -1
  6. package/dist/core/agents/codex-app-server/plan-approval.js +1 -1
  7. package/dist/core/agents/scripted/scripted-agent.js +30 -3
  8. package/dist/core/presets.js +4 -1
  9. package/dist/core/runtime/agent-runtime.js +15 -5
  10. package/dist/core/runtime/event-processor.js +13 -8
  11. package/dist/core/runtime/origin-line.js +42 -0
  12. package/dist/core/runtime/request-broker.js +2 -1
  13. package/dist/core/runtime/steering.js +4 -3
  14. package/dist/core/runtime/turn.js +6 -4
  15. package/dist/operator/errors.js +97 -0
  16. package/dist/operator/index.js +10 -5
  17. package/dist/operator/mcp.js +7 -12
  18. package/dist/operator/operator.js +1336 -380
  19. package/dist/operator/refs.js +59 -0
  20. package/dist/operator/render.js +171 -74
  21. package/dist/operator/session-tools.js +87 -0
  22. package/dist/operator/types.js +30 -0
  23. package/dist/operator/view.js +82 -27
  24. package/dist/protocol/config.js +12 -5
  25. package/dist/protocol/conversation.js +3 -0
  26. package/dist/protocol/history.js +2 -1
  27. package/dist/protocol/index.js +1 -0
  28. package/dist/protocol/lifecycle.js +19 -0
  29. package/dist/protocol/origin.js +39 -0
  30. package/dist/protocol/reduce.js +2 -0
  31. package/dist/protocol/wire.js +17 -0
  32. package/dist/server/routes.js +15 -5
  33. package/dist/types/client/client.d.ts.map +1 -1
  34. package/dist/types/client/connection.d.ts +14 -2
  35. package/dist/types/client/connection.d.ts.map +1 -1
  36. package/dist/types/client/turns.d.ts +2 -2
  37. package/dist/types/client/turns.d.ts.map +1 -1
  38. package/dist/types/core/agents/base.d.ts +2 -0
  39. package/dist/types/core/agents/base.d.ts.map +1 -1
  40. package/dist/types/core/agents/scripted/scripted-agent.d.ts +14 -1
  41. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  42. package/dist/types/core/presets.d.ts.map +1 -1
  43. package/dist/types/core/runtime/agent-runtime.d.ts +4 -2
  44. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  45. package/dist/types/core/runtime/event-processor.d.ts +2 -2
  46. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  47. package/dist/types/core/runtime/origin-line.d.ts +15 -0
  48. package/dist/types/core/runtime/origin-line.d.ts.map +1 -0
  49. package/dist/types/core/runtime/request-broker.d.ts +1 -1
  50. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  51. package/dist/types/core/runtime/steering.d.ts +7 -4
  52. package/dist/types/core/runtime/steering.d.ts.map +1 -1
  53. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  54. package/dist/types/operator/errors.d.ts +83 -0
  55. package/dist/types/operator/errors.d.ts.map +1 -0
  56. package/dist/types/operator/index.d.ts +10 -5
  57. package/dist/types/operator/index.d.ts.map +1 -1
  58. package/dist/types/operator/mcp.d.ts +1 -1
  59. package/dist/types/operator/mcp.d.ts.map +1 -1
  60. package/dist/types/operator/operator.d.ts +15 -197
  61. package/dist/types/operator/operator.d.ts.map +1 -1
  62. package/dist/types/operator/refs.d.ts +25 -0
  63. package/dist/types/operator/refs.d.ts.map +1 -0
  64. package/dist/types/operator/render.d.ts +59 -19
  65. package/dist/types/operator/render.d.ts.map +1 -1
  66. package/dist/types/operator/session-tools.d.ts +61 -0
  67. package/dist/types/operator/session-tools.d.ts.map +1 -0
  68. package/dist/types/operator/types.d.ts +441 -0
  69. package/dist/types/operator/types.d.ts.map +1 -0
  70. package/dist/types/operator/view.d.ts +19 -29
  71. package/dist/types/operator/view.d.ts.map +1 -1
  72. package/dist/types/protocol/config.d.ts +20 -5
  73. package/dist/types/protocol/config.d.ts.map +1 -1
  74. package/dist/types/protocol/conversation.d.ts +44 -3
  75. package/dist/types/protocol/conversation.d.ts.map +1 -1
  76. package/dist/types/protocol/history.d.ts +1 -1
  77. package/dist/types/protocol/history.d.ts.map +1 -1
  78. package/dist/types/protocol/index.d.ts +1 -0
  79. package/dist/types/protocol/index.d.ts.map +1 -1
  80. package/dist/types/protocol/lifecycle.d.ts +40 -2
  81. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  82. package/dist/types/protocol/origin.d.ts +49 -0
  83. package/dist/types/protocol/origin.d.ts.map +1 -0
  84. package/dist/types/protocol/reduce.d.ts.map +1 -1
  85. package/dist/types/protocol/wire-api.d.ts +39 -1
  86. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  87. package/dist/types/protocol/wire.d.ts +65 -2
  88. package/dist/types/protocol/wire.d.ts.map +1 -1
  89. package/dist/types/server/routes.d.ts.map +1 -1
  90. package/docs/consuming.md +56 -121
  91. package/docs/sync-history.md +2 -1
  92. package/package.json +1 -1
  93. package/src/client/client.ts +36 -9
  94. package/src/client/connection.ts +31 -1
  95. package/src/client/turns.ts +2 -1
  96. package/src/core/agents/base.ts +2 -0
  97. package/src/core/agents/claude-code/approvals.ts +2 -2
  98. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  99. package/src/core/agents/scripted/scripted-agent.ts +42 -3
  100. package/src/core/presets.ts +4 -1
  101. package/src/core/runtime/agent-runtime.ts +31 -7
  102. package/src/core/runtime/event-processor.ts +13 -6
  103. package/src/core/runtime/origin-line.ts +43 -0
  104. package/src/core/runtime/request-broker.ts +2 -0
  105. package/src/core/runtime/steering.ts +8 -4
  106. package/src/core/runtime/turn.ts +11 -4
  107. package/src/operator/errors.ts +218 -0
  108. package/src/operator/index.ts +18 -23
  109. package/src/operator/mcp.ts +7 -16
  110. package/src/operator/operator.ts +1583 -613
  111. package/src/operator/refs.ts +75 -0
  112. package/src/operator/render.ts +208 -98
  113. package/src/operator/session-tools.ts +126 -0
  114. package/src/operator/types.ts +505 -0
  115. package/src/operator/view.ts +93 -42
  116. package/src/protocol/config.ts +14 -6
  117. package/src/protocol/conversation.ts +3 -0
  118. package/src/protocol/history.ts +2 -1
  119. package/src/protocol/index.ts +1 -0
  120. package/src/protocol/lifecycle.ts +21 -0
  121. package/src/protocol/origin.ts +47 -0
  122. package/src/protocol/reduce.ts +4 -0
  123. package/src/protocol/wire.ts +18 -0
  124. package/src/server/routes.ts +16 -5
@@ -0,0 +1,505 @@
1
+ /**
2
+ * The operator's public types (LLP 0019): who calls, what a session is as the
3
+ * tools report it, the host the product implements, and the refusals.
4
+ * `Origin` is the protocol's (it rides `turn/start` and `turn/steer`).
5
+ */
6
+
7
+ // @ref LLP 0019#the-host — what the package owns and what stays the host's
8
+
9
+ import type { z } from "zod";
10
+ import type { ReportedPermissionMode } from "../protocol/config.ts";
11
+ import type { AgentHarness } from "../protocol/harness.ts";
12
+ import type { Origin } from "../protocol/origin.ts";
13
+ import type { ThinkingLevel } from "../protocol/thinking.ts";
14
+
15
+ import type { Answer } from "./render.ts";
16
+ import type { DecisionRequest, QuestionRequest, ViewMessage } from "./view.ts";
17
+
18
+ export type { Origin };
19
+
20
+ // ---- who is calling ---------------------------------------------------------
21
+
22
+ /**
23
+ * A session's own agent calling the tools. Filled by the engine's delivery
24
+ * of the tools to the session, never by the model.
25
+ */
26
+ export interface SessionCaller {
27
+ kind: "session";
28
+ sessionId: string;
29
+ /** The turn the call is made in: a tool call always happens inside one. */
30
+ turnId: string;
31
+ harness: AgentHarness;
32
+ /** The session's mode live at the call, not the turn's start config: `plan` may only read. */
33
+ permissionMode: ReportedPermissionMode;
34
+ /** Aborts when the agent gives the call up: a held wait answers at once. */
35
+ signal?: AbortSignal;
36
+ }
37
+
38
+ /**
39
+ * Anyone outside a session: an assistant, a paired device, the product's
40
+ * own window. `Auth` is the host's (its token, its access row): the package
41
+ * passes it through to the host and reads nothing of it.
42
+ */
43
+ export interface ExternalCaller<Auth = unknown> {
44
+ kind: "external";
45
+ /** Stable per caller; with the kind, keys repeats and rates. */
46
+ id: string;
47
+ /** Whose words its messages are: the person's own window or device, or an assistant's. */
48
+ speaksAs: "person" | "assistant";
49
+ /** How the host shows it ("ChatGPT"); an assistant's origin carries it. */
50
+ name?: string;
51
+ /** Epoch ms its connection ends: no call waits past it (less a margin). */
52
+ endsAt?: number;
53
+ /** Aborts when the caller gives the call up (its request closed): a held wait answers at once. */
54
+ signal?: AbortSignal;
55
+ auth: Auth;
56
+ }
57
+
58
+ export type Caller<Auth = unknown> = SessionCaller | ExternalCaller<Auth>;
59
+
60
+ /** `session:<id>` or `external:<id>`: every map the package keeps is keyed by it. */
61
+ export type CallerKey = `session:${string}` | `external:${string}`;
62
+
63
+ // ---- what a session is, as the tools report it --------------------------------
64
+
65
+ /**
66
+ * - `setting_up`: its workspace is being prepared; no turn can run yet.
67
+ * - `idle`: no turn runs; the last one finished (or none ran).
68
+ * - `working`: a turn runs.
69
+ * - `needs_input`: a turn waits on a question, a plan or a permission.
70
+ * - `stopped`: the last turn was cancelled, and nothing ran since.
71
+ * - `error`: the last turn failed, or the workspace could not be set up.
72
+ * - `archived`: put away; read only.
73
+ */
74
+ export type SessionStatus =
75
+ | "setting_up"
76
+ | "idle"
77
+ | "working"
78
+ | "needs_input"
79
+ | "stopped"
80
+ | "error"
81
+ | "archived";
82
+
83
+ /** `list_sessions`'s `started_by` filter, from the caller's side. */
84
+ export type StartedByFilter = "me" | "agents" | "person" | "any";
85
+
86
+ export interface ProjectRef {
87
+ id: string;
88
+ /** Unique among the caller's projects, case-insensitively. May hold `/` (`owner/name`). */
89
+ name: string;
90
+ }
91
+
92
+ export interface WorkspaceRef {
93
+ id: string;
94
+ /** Unique in its project, case-insensitively; holds neither `/` nor `:`. */
95
+ name: string;
96
+ }
97
+
98
+ /** One session as the host lists it. */
99
+ export interface Entry {
100
+ /**
101
+ * The engine's `sessionId`, minted when the session is asked for, before
102
+ * its workspace is set up: one identity for the session's whole life.
103
+ */
104
+ id: string;
105
+ project?: ProjectRef;
106
+ /** A host with no workspaces gives each session one of its own. */
107
+ workspace: WorkspaceRef;
108
+ /** Its number in its workspace, from 1, never reused. Absent: the tools print its id. */
109
+ chat?: number;
110
+ /** The chat a bare workspace name means. */
111
+ current: boolean;
112
+ status: SessionStatus;
113
+ title?: string;
114
+ harness?: AgentHarness;
115
+ model?: string;
116
+ /**
117
+ * Who started it: the start's origin, kept by the host. An external caller
118
+ * speaking as the person starts as the person, at account scope.
119
+ */
120
+ startedBy: Origin;
121
+ startedAt?: number;
122
+ lastActivityAt?: number;
123
+ /** Why `error`, when setup failed (a failed turn's error is the view's). */
124
+ error?: string;
125
+ /** A few words the host adds to the row (lines changed, a pull request). */
126
+ note?: string;
127
+ /** Paths in this session's tool lines are shown relative to this folder. */
128
+ root?: string;
129
+ }
130
+
131
+ // ---- reading a session --------------------------------------------------------
132
+
133
+ /** A place in a session's conversation, minted by the host; the package never reads it. */
134
+ export type Cursor = string & { readonly __operatorCursor: true };
135
+
136
+ export type TurnOutcome = "running" | "done" | "cancelled" | "failed";
137
+
138
+ export interface ViewTurn {
139
+ turnId: string;
140
+ outcome: TurnOutcome;
141
+ /** Who stopped it, when the host knows (`cancelled`). */
142
+ cancelledBy?: Origin;
143
+ /** Why it failed (`failed`). */
144
+ error?: string;
145
+ /** Each user message carries its own sender (`ViewMessage.origin`): a turn can mix them. */
146
+ messages: readonly ViewMessage[];
147
+ startedAt?: number;
148
+ endedAt?: number;
149
+ }
150
+
151
+ /**
152
+ * What a session waits on, with the kind the engine's broker said explicitly
153
+ * (`permission.requested`'s `purpose`): a plan only when it says `plan`. A
154
+ * model names one by the broker's own `requestId`.
155
+ */
156
+ export type Waiting =
157
+ | { kind: "question"; request: QuestionRequest }
158
+ | { kind: "plan" | "permission"; request: DecisionRequest };
159
+
160
+ /** How a turn ended, by its id, whatever page of the transcript is read. */
161
+ export interface TurnEnded {
162
+ turnId: string;
163
+ outcome: "done" | "cancelled" | "failed";
164
+ /** Who stopped it, when the host knows. */
165
+ cancelledBy?: Origin;
166
+ }
167
+
168
+ /** One turn, looked up by id. */
169
+ export type TurnFact =
170
+ | { state: "running" }
171
+ | ({ state: "ended" } & Omit<TurnEnded, "turnId">)
172
+ | { state: "unknown" };
173
+
174
+ export interface SessionView {
175
+ status: SessionStatus;
176
+ /** The running turn's id, if one runs: independent of `turns`' page. */
177
+ running?: string;
178
+ /** The last turn that ended, and how: independent of `turns`' page. */
179
+ lastEnded?: TurnEnded;
180
+ /** Oldest first; after `after`, only what followed it (a turn still running may repeat). */
181
+ turns: readonly ViewTurn[];
182
+ waiting: readonly Waiting[];
183
+ /** The host holds earlier turns than these. */
184
+ older?: boolean;
185
+ /** Where this read ended: the next read's `after`. Absent: the host has no cursors. */
186
+ cursor?: Cursor;
187
+ }
188
+
189
+ export interface ViewOptions {
190
+ /** The most recent messages wanted. A host may give more; the package cuts. */
191
+ last?: number;
192
+ /** Only what came after this place. A cursor the host cannot read is `stale_cursor`. */
193
+ after?: Cursor;
194
+ }
195
+
196
+ export interface ListFilter {
197
+ project?: ProjectRef;
198
+ workspace?: WorkspaceRef;
199
+ status?: readonly SessionStatus[];
200
+ /** Archived ones too: name resolution asks for the complete set. */
201
+ includeArchived?: boolean;
202
+ }
203
+
204
+ // ---- writing --------------------------------------------------------------------
205
+
206
+ export interface StartInput {
207
+ /** The first task's turn id, minted by the package: deliver the first message as this turn. */
208
+ turnId: string;
209
+ project: ProjectRef;
210
+ /** A new chat in this workspace; absent: a new workspace. */
211
+ workspace?: WorkspaceRef;
212
+ harness?: AgentHarness;
213
+ model?: string;
214
+ thinkingLevel?: ThinkingLevel;
215
+ title?: string;
216
+ /** The first message: the host delivers it as the session's first turn, at once or once set up. */
217
+ message: string;
218
+ origin: Origin;
219
+ }
220
+
221
+ export interface SendInput {
222
+ /** Minted by the package; a retry after no answer uses it again, and the engine converges on it. */
223
+ turnId: string;
224
+ message: string;
225
+ origin: Origin;
226
+ }
227
+
228
+ /**
229
+ * What a cancel did: the turn stopped (it has ended: a host whose stop is
230
+ * asynchronous waits for the end, briefly, before saying so), there was none,
231
+ * the stop is asked and its end not yet seen (`unconfirmed`: an archive then
232
+ * archives nothing), or (a session being set up) its first task was dropped.
233
+ */
234
+ export type CancelOutcome = "stopped" | "not_running" | "unconfirmed" | "first_task_dropped";
235
+
236
+ export type ArchiveTarget = { kind: "session"; id: string } | { kind: "workspace"; id: string };
237
+
238
+ export interface ModelEntry {
239
+ harness: AgentHarness;
240
+ id: string;
241
+ label: string;
242
+ thinkingLevels: readonly ThinkingLevel[];
243
+ defaultThinkingLevel?: ThinkingLevel;
244
+ /** The model a new session on this harness starts on. */
245
+ default?: boolean;
246
+ /** The harness a new session starts on when none is named. */
247
+ defaultHarness?: boolean;
248
+ }
249
+
250
+ // ---- refusals -------------------------------------------------------------------
251
+
252
+ /** Every refusal the tools give, and nothing else (LLP 0019, Errors). */
253
+ export const OPERATOR_ERROR_CODES = [
254
+ "invalid_input",
255
+ "not_found",
256
+ "ambiguous",
257
+ "archived",
258
+ "self",
259
+ "read_only",
260
+ "access",
261
+ "not_yours",
262
+ "has_children",
263
+ "busy",
264
+ "not_waiting",
265
+ "person_only",
266
+ "setup_failed",
267
+ "limit_depth",
268
+ "limit_sessions",
269
+ "limit_setting_up",
270
+ "limit_rate",
271
+ "limit_resources",
272
+ "stale_cursor",
273
+ "unsupported",
274
+ "failed",
275
+ ] as const;
276
+ export type OperatorErrorCode = (typeof OPERATOR_ERROR_CODES)[number];
277
+
278
+ /** A refusal as the host gives one (`authorize`, `admit`, or thrown from a method as `Refused`). */
279
+ export interface Refusal {
280
+ code: OperatorErrorCode;
281
+ /** The sessions it is about, by id (a busy member, the children not archived). */
282
+ sessions?: readonly string[];
283
+ /** The state the host saw at its commit (`busy`): the words follow it, not the preflight read. */
284
+ state?: SessionStatus;
285
+ /** The host's words, one line, trusted: said after the code's sentence. */
286
+ detail?: string;
287
+ /** Seconds after which the same call may succeed. */
288
+ retryAfter?: number;
289
+ }
290
+
291
+ // ---- rules ------------------------------------------------------------------------
292
+
293
+ /**
294
+ * What a tool does, for the rules, declared honestly: anything that changes
295
+ * something or posts outside is `write`. `read` runs in plan mode.
296
+ */
297
+ export type Effect = "read" | "write" | "destructive";
298
+
299
+ /**
300
+ * Limits, each a host may change. The defaults are LLP 0019's.
301
+ * `depth` and `sessionsPerStarter` bind session callers only. A cap across
302
+ * the host (workspaces being set up, disk, memory) is the host's, enforced
303
+ * inside its own `start`: one starter's lock cannot hold it.
304
+ */
305
+ export interface Limits {
306
+ /** A session started by a chain this long may start no more. Default 3. */
307
+ depth: number;
308
+ /** Sessions one session started that are not archived. Default 12. */
309
+ sessionsPerStarter: number;
310
+ /** Starts per caller in any 60 seconds. Default 10. */
311
+ startsPerMinute: number;
312
+ }
313
+
314
+ /** How long a held call may wait, by caller kind: a default and a cap, in seconds. */
315
+ export interface WaitCaps {
316
+ /** Default 120 and 240 (Codex cuts a tool call at 300 s unless told otherwise). */
317
+ session: { default: number; max: number };
318
+ /** Default 60 and 90; never past `endsAt` less 5 s. */
319
+ external: { default: number; max: number };
320
+ }
321
+
322
+ /** What `admit` is asked before a start: the host's resource probes. */
323
+ export interface AdmitRequest {
324
+ kind: "start";
325
+ project: ProjectRef;
326
+ /** Absent: a new workspace would be set up. */
327
+ workspace?: WorkspaceRef;
328
+ origin: Origin;
329
+ }
330
+
331
+ /**
332
+ * The facts the rules and limits rest on, authoritative, not filtered by
333
+ * what a caller may see. Required of a host that enables session callers.
334
+ */
335
+ export interface PolicyFacts {
336
+ /** The sessions this session started, not archived. */
337
+ startedBy(sessionId: string): Promise<Entry[]>;
338
+ /** Who started this session, and who started that one, nearest first. */
339
+ lineage(sessionId: string): Promise<Origin[]>;
340
+ /** Every session in the workspace with its status, archived ones excluded. */
341
+ inWorkspace(workspaceId: string): Promise<Entry[]>;
342
+ }
343
+
344
+ // ---- the host ------------------------------------------------------------------
345
+
346
+ /**
347
+ * The product, to the package. `list`, `view`, `send` and `onChange` are
348
+ * required; every other method is a capability, and a tool that needs one
349
+ * the host lacks is not listed. The host keeps its own check at each
350
+ * mutation; the package's rules are in addition.
351
+ */
352
+ export interface OperatorHost<Auth = unknown> {
353
+ /** The sessions this caller may see, filtered as asked (the package filters again). */
354
+ list(caller: Caller<Auth>, filter: ListFilter): Promise<Entry[]>;
355
+ view(caller: Caller<Auth>, sessionId: string, options: ViewOptions): Promise<SessionView>;
356
+ /**
357
+ * Start the turn `input.turnId` now, carrying `origin` to the wire. The
358
+ * same turn id again converges on the first (the engine's rule). A host
359
+ * that finds the session busy refuses `busy` (an `OperatorError`, or
360
+ * `Refused`), any other definite refusal is one of those too, and a
361
+ * failure whose outcome is unknown throws a plain error: the package tries
362
+ * again with the same turn id.
363
+ */
364
+ send(caller: Caller<Auth>, sessionId: string, input: SendInput): Promise<void>;
365
+ /** One turn by id: running, ended (how, and by whom when stopped), or unknown. */
366
+ turn(caller: Caller<Auth>, sessionId: string, turnId: string): Promise<TurnFact>;
367
+ /**
368
+ * Call `listener` with the sessions that may have changed, for as long as
369
+ * the returned function is not called. Waits rest on it.
370
+ */
371
+ onChange(listener: (sessionIds: readonly string[]) => void): () => void;
372
+
373
+ /** One entry by session id or workspace id (its current chat), archived ones included. */
374
+ entry?(caller: Caller<Auth>, id: string): Promise<Entry | undefined>;
375
+ /** Every project this caller could start in, those with no session included. */
376
+ projects?(caller: Caller<Auth>): Promise<ProjectRef[]>;
377
+ /**
378
+ * Make the session (and its workspace, when none is named) and return its
379
+ * entry at once, its session id minted now: `idle`, or `setting_up` while
380
+ * its workspace is prepared. Keep `input.origin` as its `startedBy`. The
381
+ * host OWNS delivering `input.message` as its first turn (`input.turnId`),
382
+ * at once or once set up, and reports what became of it through the
383
+ * session's status (an `error` with why when it could not be delivered).
384
+ * The package's checks are preflight; the host enforces, atomically at
385
+ * its commit, by throwing `Refused`: no start into an archived workspace
386
+ * or by an archived starter (`archived`), and its caps across starters
387
+ * (`limit_setting_up` or `limit_resources`, with `retryAfter`). Enables
388
+ * `start_session`.
389
+ */
390
+ start?(caller: Caller<Auth>, input: StartInput): Promise<Entry>;
391
+ /**
392
+ * Stop this turn, and only it; with no turn (a session being set up), drop
393
+ * the first task the host holds for it. Enables `stop_sessions` and
394
+ * `when: interrupt`.
395
+ */
396
+ cancel?(caller: Caller<Auth>, sessionId: string, turnId?: string): Promise<CancelOutcome>;
397
+ /** Answer exactly this request; `accepted: false` when it no longer waits. Enables `answer_request`. */
398
+ respond?(caller: Caller<Auth>, sessionId: string, answer: Answer): Promise<{ accepted: boolean }>;
399
+ /**
400
+ * Archive one target. The package's checks are preflight; the host
401
+ * enforces eligibility atomically at its commit, throwing `Refused` with
402
+ * the sessions concerned and the state it saw: a member being set up
403
+ * (`busy`, `state: "setting_up"`), a member still working or waiting, the
404
+ * caller's own included, since a stop must be confirmed first (`busy`; a
405
+ * member the caller did not start, `not_yours`), a member that started
406
+ * sessions not archived, lineage included (`has_children`).
407
+ * Enables `archive`.
408
+ */
409
+ archive?(caller: Caller<Auth>, target: ArchiveTarget): Promise<{ note?: string }>;
410
+ /** The models a new session can run. Enables `list_models`. */
411
+ models?(caller: Caller<Auth>): Promise<ModelEntry[]>;
412
+ /**
413
+ * Whether this outside caller may run this tool now, read from the host's
414
+ * store at the call: asked before every tool and again just before every
415
+ * write the package makes (each send, cancel, answer, start, archive). The tool's
416
+ * name lets a host allow one write tool to a low-access caller.
417
+ */
418
+ authorize?(
419
+ caller: ExternalCaller<Auth>,
420
+ call: { effect: Effect; tool: string },
421
+ ): Refusal | undefined | Promise<Refusal | undefined>;
422
+ /** Required with session callers: the facts the rules and limits rest on. */
423
+ policy?: PolicyFacts;
424
+ /** Resource probes before a start (disk, memory): a `limit_resources` refusal, or none. */
425
+ admit?(caller: Caller<Auth>, request: AdmitRequest): Promise<Refusal | undefined>;
426
+ /** One line of host facts once a turn settles ("changes: a.ts (+4 -0)"). */
427
+ outcome?(caller: Caller<Auth>, entry: Entry): Promise<string | undefined>;
428
+ /** One line `whoami` adds for this caller ("access: read"). */
429
+ describe?(caller: Caller<Auth>): Promise<string | undefined>;
430
+ }
431
+
432
+ // ---- the host's own tools ---------------------------------------------------------
433
+
434
+ /**
435
+ * A tool the host adds beside the package's. It declares only its effect;
436
+ * the package applies plan mode and `authorize` (with its name) to it and
437
+ * nothing else. It may not change sessions: that is the package's tools'.
438
+ */
439
+ export interface ExtraTool<Auth = unknown> {
440
+ name: string;
441
+ title: string;
442
+ description: string;
443
+ input: z.ZodObject;
444
+ effect: Effect;
445
+ /** It reaches past this host (sends something elsewhere): MCP's `openWorldHint`. */
446
+ openWorld?: boolean;
447
+ /** `call`: the call's deadline (epoch ms) and its caller's signal, so a long run answers in time. */
448
+ run(args: never, caller: Caller<Auth>, call: CallScope): Promise<string>;
449
+ }
450
+
451
+ /**
452
+ * A call's time, as a host's own tool sees it: the deadline the package's
453
+ * waits keep (the caller's wait, capped, never past its connection) and the
454
+ * caller's signal.
455
+ */
456
+ export interface CallScope {
457
+ deadline: number;
458
+ signal?: AbortSignal;
459
+ }
460
+
461
+ // ---- the package's side ----------------------------------------------------------
462
+
463
+ /** A tool as any transport lists it. */
464
+ export interface ToolInfo {
465
+ name: string;
466
+ title: string;
467
+ description: string;
468
+ /** JSON Schema of the arguments (an object). */
469
+ inputSchema: unknown;
470
+ readOnly: boolean;
471
+ /** It reaches past this host: MCP's `openWorldHint`. */
472
+ openWorld?: boolean;
473
+ /** It may undo or lose work: MCP's `destructiveHint`. */
474
+ destructive?: boolean;
475
+ }
476
+
477
+ /** Time, for the waits and the limits. Tests pass their own; the default is the wall clock. */
478
+ export interface OperatorClock {
479
+ now(): number;
480
+ /** Resolve after `ms`, or as soon as `signal` aborts. */
481
+ pause(ms: number, signal: AbortSignal): Promise<void>;
482
+ }
483
+
484
+ export interface OperatorOptions<Auth = unknown> {
485
+ limits?: Partial<Limits>;
486
+ waits?: Partial<WaitCaps>;
487
+ extra?: ExtraTool<Auth>[];
488
+ clock?: OperatorClock;
489
+ /**
490
+ * Shown each unexpected failure a call answers without (a `refused (failed)`,
491
+ * an outcome that could not be read), once, with the tool and the caller:
492
+ * for the host's reports. Never a refusal. It cannot change the answer,
493
+ * and a throw inside it is swallowed.
494
+ */
495
+ onError?: (error: unknown, tool: string, caller: Caller<Auth>) => void;
496
+ }
497
+
498
+ export interface Operator<Auth = unknown> {
499
+ /** The same for every caller: an assistant keeps the list it got when it connected. */
500
+ tools(): ToolInfo[];
501
+ /** Run one tool and answer in text. Refusals are `OperatorError`s. */
502
+ call(name: string, args: unknown, caller: Caller<Auth>): Promise<string>;
503
+ /** The entry a reference names (LLP 0019, References). */
504
+ find(caller: Caller<Auth>, ref: string): Promise<Entry>;
505
+ }
@@ -1,10 +1,8 @@
1
1
  /**
2
- * What an operator needs to know about one session, however its host keeps it.
3
- *
4
- * A host that holds a folded `ConversationState` gets this with `viewOf`. A host
5
- * that keeps its own rows (messages with their parts, a status column) builds
6
- * the same shape directly. Nothing here knows about projects, workspaces,
7
- * accounts or storage: those are the host's.
2
+ * What the operator needs to know about one session, however its host keeps
3
+ * it. A host that holds a folded `ConversationState` gets it with `viewOf`; a
4
+ * host that keeps its own rows builds the same shape. Nothing here knows about
5
+ * projects, workspaces, accounts or storage: those are the host's.
8
6
  */
9
7
 
10
8
  import {
@@ -15,14 +13,24 @@ import {
15
13
  pendingElicitations,
16
14
  pendingPermissions,
17
15
  } from "../protocol/conversation.ts";
16
+ import type { ReportedOrigin } from "../protocol/origin.ts";
18
17
  import type { Part, UnknownPart } from "../protocol/parts.ts";
19
- import { PLAN_OPTION_IDS } from "../protocol/plan.ts";
18
+ import type {
19
+ SessionStatus,
20
+ SessionView,
21
+ TurnFact,
22
+ TurnOutcome,
23
+ ViewTurn,
24
+ Waiting,
25
+ } from "./types.ts";
20
26
 
21
27
  export interface ViewMessage {
22
28
  role: "user" | "assistant";
23
29
  parts: readonly (Part | UnknownPart)[];
24
30
  /** A sub-agent's output: shown nested, never as the agent's reply. */
25
31
  nested?: boolean;
32
+ /** A user message's sender when it is not the person (LLP 0019). */
33
+ origin?: ReportedOrigin;
26
34
  }
27
35
 
28
36
  /** A question the agent asked, as the engine's `elicitation.requested` carries it. */
@@ -33,50 +41,93 @@ export type QuestionRequest = Pick<
33
41
  /** A decision the agent waits on (a tool's approval, or a plan), as `permission.requested` carries it. */
34
42
  export type DecisionRequest = Pick<
35
43
  ConversationPermission,
36
- "requestId" | "title" | "toolCall" | "options"
44
+ "requestId" | "title" | "toolCall" | "options" | "purpose"
37
45
  >;
38
46
 
39
- export type Waiting =
40
- | { kind: "question"; request: QuestionRequest }
41
- | { kind: "decision"; request: DecisionRequest };
42
-
43
- export interface SessionView {
44
- /** Whether a turn is running. "Waiting on a person" is `waiting`, not a status. */
45
- status: "idle" | "working" | "error";
46
- messages: readonly ViewMessage[];
47
- waiting: readonly Waiting[];
48
- error?: string;
49
- /** The host holds earlier messages than the ones given here. */
50
- older?: boolean;
47
+ // @ref LLP 0019#answer_request-write — a plan only when the engine says so; anything else is a permission
48
+ /** A decision's kind, from its `purpose`: `plan` when it says so, else a permission. */
49
+ export function waitingOf(request: DecisionRequest): Waiting {
50
+ return { kind: request.purpose === "plan" ? "plan" : "permission", request };
51
51
  }
52
52
 
53
- /** What a person would call the session's state. Waiting on them is not "finished". */
54
- export type Phase = "idle" | "working" | "needs_input" | "error";
53
+ /** Whether a status needs no more waiting: a wait returns it. */
54
+ export const settledStatus = (status: SessionStatus): boolean =>
55
+ status !== "working" && status !== "setting_up";
55
56
 
56
- export function phaseOf(view: Pick<SessionView, "status" | "waiting">): Phase {
57
- return view.waiting.length > 0 ? "needs_input" : view.status;
57
+ /**
58
+ * The view of a session whose events were folded with the engine's reducer,
59
+ * with its turn facts (`running`, `lastEnded`) from every turn, not a page.
60
+ */
61
+ export function viewOf(state: ConversationState): SessionView {
62
+ return viewWithFacts(state);
58
63
  }
59
64
 
60
- /** A plan's approval is a decision whose options include "keep planning" (`PLAN_OPTIONS`). */
61
- export function isPlan(request: DecisionRequest): boolean {
62
- return request.options.some((option) => option.optionId === PLAN_OPTION_IDS.keepPlanning);
65
+ /** One turn of a folded state, by id: the host's `turn`, for a host that folds. */
66
+ export function turnOf(state: ConversationState, turnId: string): TurnFact {
67
+ const turn = state.turns.find((t) => t.turnId === turnId);
68
+ if (!turn) return { state: "unknown" };
69
+ if (turn.status === "active") return { state: "running" };
70
+ return {
71
+ state: "ended",
72
+ outcome: turn.error ? "failed" : turn.stopReason === "cancelled" ? "cancelled" : "done",
73
+ };
63
74
  }
64
75
 
65
- /** The view of a session whose events were folded with the engine's reducer. */
66
- export function viewOf(state: ConversationState): SessionView {
67
- const last = state.turns.at(-1);
68
- const failed = last?.status === "ended" ? last.error : undefined;
76
+ function viewWithFacts(state: ConversationState): SessionView {
77
+ const messages = conversationMessages(state);
78
+ const waiting: Waiting[] = [
79
+ ...pendingElicitations(state).map((request) => ({ kind: "question" as const, request })),
80
+ ...pendingPermissions(state).map(waitingOf),
81
+ ];
82
+ const turns: ViewTurn[] = state.turns.map((turn) => {
83
+ const outcome: TurnOutcome =
84
+ turn.status === "active"
85
+ ? "running"
86
+ : turn.error
87
+ ? "failed"
88
+ : turn.stopReason === "cancelled"
89
+ ? "cancelled"
90
+ : "done";
91
+ return {
92
+ turnId: turn.turnId,
93
+ outcome,
94
+ ...(turn.error ? { error: turn.error.message } : {}),
95
+ messages: messages
96
+ .filter((message) => message.turnId === turn.turnId)
97
+ .map((message) => ({
98
+ role: message.role,
99
+ parts: message.parts,
100
+ ...(message.parentToolCallId ? { nested: true } : {}),
101
+ ...(message.origin ? { origin: message.origin } : {}),
102
+ })),
103
+ startedAt: turn.startedAt,
104
+ ...(turn.endedAt !== undefined ? { endedAt: turn.endedAt } : {}),
105
+ };
106
+ });
107
+ const last = turns.at(-1)?.outcome;
108
+ const status: SessionStatus = waiting.length
109
+ ? "needs_input"
110
+ : last === "running"
111
+ ? "working"
112
+ : last === "failed"
113
+ ? "error"
114
+ : last === "cancelled"
115
+ ? "stopped"
116
+ : "idle";
117
+ const running = turns.find((t) => t.outcome === "running")?.turnId;
118
+ const ended = [...turns].reverse().find((t) => t.outcome !== "running");
69
119
  return {
70
- status: last?.status === "active" ? "working" : failed ? "error" : "idle",
71
- messages: conversationMessages(state).map((message) => ({
72
- role: message.role,
73
- parts: message.parts,
74
- ...(message.parentToolCallId ? { nested: true } : {}),
75
- })),
76
- waiting: [
77
- ...pendingElicitations(state).map((request) => ({ kind: "question" as const, request })),
78
- ...pendingPermissions(state).map((request) => ({ kind: "decision" as const, request })),
79
- ],
80
- ...(failed ? { error: failed.message } : {}),
120
+ status,
121
+ turns,
122
+ waiting,
123
+ ...(running ? { running } : {}),
124
+ ...(ended
125
+ ? {
126
+ lastEnded: {
127
+ turnId: ended.turnId,
128
+ outcome: ended.outcome as "done" | "cancelled" | "failed",
129
+ },
130
+ }
131
+ : {}),
81
132
  };
82
133
  }