@nexus-code/remote-protocol 0.0.0-stage → 0.2.0

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/src/rpc.ts ADDED
@@ -0,0 +1,962 @@
1
+ /**
2
+ * What one device asks another, sealed: JSON-RPC 2.0 requests, their
3
+ * answers, and the notifications a watch sends. The device that runs the
4
+ * sessions serves; the one that shows them asks.
5
+ *
6
+ * A session is named by the serving device's own ids: its workspace's and
7
+ * its tab's. The same folder has other ids on another device.
8
+ */
9
+ import { z } from "zod";
10
+ import {
11
+ AssistantItemSchema,
12
+ ChatPanelSchema,
13
+ ChatStatusSchema,
14
+ ViewItemSchema,
15
+ ViewTaskSchema,
16
+ ViewToolCallSchema,
17
+ } from "./view.js";
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // JSON-RPC 2.0 shapes
21
+ // ---------------------------------------------------------------------------
22
+
23
+ export const RpcIdSchema = z.union([z.number().int(), z.string()]);
24
+
25
+ export const RpcRequestSchema = z.object({
26
+ jsonrpc: z.literal("2.0"),
27
+ id: RpcIdSchema,
28
+ method: z.string(),
29
+ params: z.unknown().optional(),
30
+ });
31
+ export type RpcRequest = z.infer<typeof RpcRequestSchema>;
32
+
33
+ export const RpcErrorSchema = z.object({
34
+ code: z.number().int(),
35
+ message: z.string(),
36
+ data: z.unknown().optional(),
37
+ });
38
+ export type RpcError = z.infer<typeof RpcErrorSchema>;
39
+
40
+ // The error first: `result: z.unknown()` takes an object without one too,
41
+ // and would strip an error answer's `error`.
42
+ export const RpcResponseSchema = z.union([
43
+ z.object({ jsonrpc: z.literal("2.0"), id: RpcIdSchema, error: RpcErrorSchema }),
44
+ z.object({ jsonrpc: z.literal("2.0"), id: RpcIdSchema, result: z.unknown() }),
45
+ ]);
46
+ export type RpcResponse = z.infer<typeof RpcResponseSchema>;
47
+
48
+ export const RpcNotificationSchema = z.object({
49
+ jsonrpc: z.literal("2.0"),
50
+ method: z.string(),
51
+ params: z.unknown().optional(),
52
+ });
53
+ export type RpcNotification = z.infer<typeof RpcNotificationSchema>;
54
+
55
+ export const RpcMessageSchema = z.union([
56
+ RpcRequestSchema,
57
+ RpcResponseSchema,
58
+ RpcNotificationSchema,
59
+ ]);
60
+ export type RpcMessage = z.infer<typeof RpcMessageSchema>;
61
+
62
+ /** The error codes: JSON-RPC's own, and the protocol's from 1000. */
63
+ export const RpcErrorCode = {
64
+ ParseError: -32700,
65
+ InvalidRequest: -32600,
66
+ MethodNotFound: -32601,
67
+ InvalidParams: -32602,
68
+ InternalError: -32603,
69
+ /** No such workspace, tab or watch on the serving device. */
70
+ NotFound: 1001,
71
+ /** The serving device does not let this device do it. */
72
+ Forbidden: 1002,
73
+ /** The session cannot do it now: a chat with no request waiting, one whose program is gone. */
74
+ Unavailable: 1003,
75
+ } as const;
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // Sessions
79
+ // ---------------------------------------------------------------------------
80
+
81
+ /** A workspace of the serving device. */
82
+ export const RemoteWorkspaceSchema = z.object({
83
+ id: z.string(),
84
+ name: z.string(),
85
+ /** Its folder, on the serving device. */
86
+ path: z.string(),
87
+ /** A task: a workspace on a git worktree of the workspace `parentId`, on its own branch. */
88
+ parentId: z.string().optional(),
89
+ /** The agent manager's own workspace, where the session that directs the others runs. */
90
+ manager: z.boolean().optional(),
91
+ /**
92
+ * A task's branch and how it stands against its upstream, with how many
93
+ * files it changed and did not commit. Looked at now and then, not live.
94
+ */
95
+ git: z
96
+ .object({
97
+ branch: z.string().nullable(),
98
+ ahead: z.number().int().nonnegative(),
99
+ behind: z.number().int().nonnegative(),
100
+ uncommitted: z.number().int().nonnegative(),
101
+ })
102
+ .optional(),
103
+ });
104
+ export type RemoteWorkspace = z.infer<typeof RemoteWorkspaceSchema>;
105
+
106
+ /** Where a session stands, as the agent lists show it. */
107
+ export const SessionStateSchema = z.enum(["needs-you", "running", "new-result", "idle", "ended"]);
108
+ export type SessionState = z.infer<typeof SessionStateSchema>;
109
+
110
+ /** An agent session or terminal of the serving device. */
111
+ export const RemoteSessionSchema = z.object({
112
+ workspaceId: z.string(),
113
+ tabId: z.string(),
114
+ kind: z.enum(["claude", "codex", "terminal"]),
115
+ title: z.string(),
116
+ state: SessionStateSchema,
117
+ /** When it came to that state, in Unix milliseconds. */
118
+ since: z.number().optional(),
119
+ /** The last thing it said, a line. */
120
+ last: z.string().optional(),
121
+ /** The agent profile it runs with. */
122
+ profile: z.string().optional(),
123
+ /** What it waits on the user for, when it does. */
124
+ waiting: z
125
+ .object({
126
+ kind: z.enum(["permission", "question", "plan"]),
127
+ text: z.string(),
128
+ /** A terminal's Claude Code asking: the request terminal.answer answers. */
129
+ requestId: z.string().optional(),
130
+ })
131
+ .optional(),
132
+ });
133
+ export type RemoteSession = z.infer<typeof RemoteSessionSchema>;
134
+
135
+ const SessionsSchema = z.object({
136
+ workspaces: z.array(RemoteWorkspaceSchema),
137
+ sessions: z.array(RemoteSessionSchema),
138
+ });
139
+
140
+ /** A session of the serving device, by its ids there. */
141
+ const TabRef = { workspaceId: z.string(), tabId: z.string() };
142
+
143
+ /**
144
+ * The agent that sends a request, when an agent does (nexus chat send on
145
+ * another device): its own tab there, which the receiving chat shows as
146
+ * the reply address. The device is the frame's sender. A control method
147
+ * with `from` takes the `agents` capability, not its own, and the serving
148
+ * device may ask its user first (AGENT_CONSENT_MS) or turn it down.
149
+ */
150
+ export const AgentSenderSchema = z.object({
151
+ /** tab: a Claude or Codex tab; terminal: an agent in a terminal; manager: the agent manager. */
152
+ kind: z.enum(["tab", "terminal", "manager"]),
153
+ agent: z.string().min(1).max(40).optional(),
154
+ workspaceId: z.string(),
155
+ tabId: z.string(),
156
+ /** Its tab's title, as the receiver shows the sender. */
157
+ name: z.string().max(200).optional(),
158
+ /**
159
+ * How many messages between agents led to this one, the first being 1:
160
+ * a device refuses one past MAX_AGENT_HOPS, so agents on two devices
161
+ * cannot keep each other going without end.
162
+ */
163
+ hops: z.number().int().positive(),
164
+ });
165
+ export type AgentSender = z.infer<typeof AgentSenderSchema>;
166
+
167
+ /** The keys terminal.input presses by name, as `nexus terminal key` names them. */
168
+ export const TERMINAL_KEYS = [
169
+ "enter",
170
+ "tab",
171
+ "shift-tab",
172
+ "esc",
173
+ "space",
174
+ "backspace",
175
+ "delete",
176
+ "up",
177
+ "down",
178
+ "left",
179
+ "right",
180
+ "home",
181
+ "end",
182
+ "pageup",
183
+ "pagedown",
184
+ "ctrl-a",
185
+ "ctrl-b",
186
+ "ctrl-c",
187
+ "ctrl-d",
188
+ "ctrl-e",
189
+ "ctrl-f",
190
+ "ctrl-g",
191
+ "ctrl-h",
192
+ "ctrl-i",
193
+ "ctrl-j",
194
+ "ctrl-k",
195
+ "ctrl-l",
196
+ "ctrl-m",
197
+ "ctrl-n",
198
+ "ctrl-o",
199
+ "ctrl-p",
200
+ "ctrl-q",
201
+ "ctrl-r",
202
+ "ctrl-s",
203
+ "ctrl-t",
204
+ "ctrl-u",
205
+ "ctrl-v",
206
+ "ctrl-w",
207
+ "ctrl-x",
208
+ "ctrl-y",
209
+ "ctrl-z",
210
+ ] as const;
211
+ export const TerminalKeySchema = z.enum(TERMINAL_KEYS);
212
+ export type TerminalKey = z.infer<typeof TerminalKeySchema>;
213
+
214
+ /** Most messages between agents one chain may take; past it, `from` requests are refused. */
215
+ export const MAX_AGENT_HOPS = 8;
216
+
217
+ /**
218
+ * How long a serving device may ask its user about a request with `from`
219
+ * before it turns it down: a requester waits this long, and a little more.
220
+ */
221
+ export const AGENT_CONSENT_MS = 90_000;
222
+
223
+ /** Most requests with `from` one agent (a device's tab) may make a minute; more are Unavailable. */
224
+ export const MAX_AGENT_REQUESTS_PER_MINUTE = 20;
225
+
226
+ /** Longest a chat.wait or terminal.wait holds before it answers that the session is not done yet. */
227
+ export const MAX_WAIT_MS = 10_000;
228
+
229
+ /** Where a chat stands for one that waits on it, as `nexus chat wait` tells it. */
230
+ export const ChatWaitStateSchema = z.enum(["working", "asking", "idle", "error", "closed"]);
231
+
232
+ /** A session state change, as `nexus events` lists them. */
233
+ export const SessionEventSchema = z.object({
234
+ /** Counts the device's events from 1 since its app started. */
235
+ seq: z.number().int().positive(),
236
+ at: z.number(),
237
+ workspaceId: z.string(),
238
+ tabId: z.string(),
239
+ title: z.string(),
240
+ kind: z.enum(["terminal", "claude", "codex"]),
241
+ agent: z.string().optional(),
242
+ /** The phase it left (null: first seen) and the one it came to ("closed" when the tab went). */
243
+ from: z.string().nullable(),
244
+ to: z.string(),
245
+ message: z.string().optional(),
246
+ });
247
+ export type SessionEvent = z.infer<typeof SessionEventSchema>;
248
+
249
+ /** Most images one message takes. */
250
+ export const MAX_ATTACHMENTS = 4;
251
+
252
+ /**
253
+ * Most bytes one image chat.attach takes, before base64: its base64 and the
254
+ * request around it stay inside a frame (MAX_FRAME_BYTES, sealed).
255
+ */
256
+ export const MAX_ATTACHMENT_BYTES = 560 * 1024;
257
+
258
+ /** The image types a chat takes. */
259
+ export const ImageMediaTypeSchema = z.enum(["image/png", "image/jpeg", "image/gif", "image/webp"]);
260
+
261
+ /** What a chat runs with, and what it may be set to. */
262
+ export const ChatSettingsSchema = z.object({
263
+ agent: z.enum(["claude", "codex"]),
264
+ /** The model it runs, by the id to give back; null before the program says. */
265
+ model: z.string().nullable(),
266
+ effort: z.string().nullable(),
267
+ permissionMode: z.string(),
268
+ options: z.object({
269
+ models: z.array(z.object({ id: z.string(), label: z.string() })),
270
+ /** The effort levels its model takes; none when it takes none. */
271
+ efforts: z.array(z.string()),
272
+ /** The permission modes; `dangerous` ones ask the serving device's policy first. */
273
+ modes: z.array(
274
+ z.object({ id: z.string(), label: z.string(), dangerous: z.boolean().optional() }),
275
+ ),
276
+ }),
277
+ });
278
+ export type ChatSettings = z.infer<typeof ChatSettingsSchema>;
279
+
280
+ /**
281
+ * A slash command of a chat, for a "/" picker: the app's own (run with
282
+ * chat.command), the agent's own (sent as a message: chat.send "/name
283
+ * args"), or one that sets what chat.configure sets.
284
+ */
285
+ export const ChatCommandSchema = z.object({
286
+ name: z.string(),
287
+ description: z.string(),
288
+ /** command: chat.command; send: chat.send its text; settings: chat.configure. */
289
+ runs: z.enum(["command", "send", "settings"]),
290
+ /** With runs "settings": what it sets, so the picker for it opens. */
291
+ sets: z.enum(["model", "effort", "permissionMode"]).optional(),
292
+ /** What it takes after its name, as its help writes it ("<condition>"). */
293
+ args: z.string().optional(),
294
+ });
295
+ export type ChatCommand = z.infer<typeof ChatCommandSchema>;
296
+
297
+ /** A chat of the past that can be resumed: Claude Code's sessions, Codex's threads. */
298
+ export const PastSessionSchema = z.object({
299
+ sessionId: z.string(),
300
+ title: z.string(),
301
+ /** When it last changed, in Unix milliseconds. */
302
+ at: z.number(),
303
+ /** Its log's size in bytes, when known. */
304
+ bytes: z.number().int().nonnegative().optional(),
305
+ /** The folder it ran in. */
306
+ cwd: z.string().optional(),
307
+ profile: z.string().optional(),
308
+ });
309
+ export type PastSession = z.infer<typeof PastSessionSchema>;
310
+
311
+ /** A file's state in git: a letter as `git status --porcelain` gives it (M, A, D, R, C, U, ?). */
312
+ const GitLetter = z.string().length(1);
313
+
314
+ /** A file git sees changed, staged or not. */
315
+ export const GitFileSchema = z.object({
316
+ path: z.string(),
317
+ /** Renamed or copied from. */
318
+ oldPath: z.string().optional(),
319
+ staged: GitLetter.optional(),
320
+ unstaged: GitLetter.optional(),
321
+ });
322
+
323
+ /** A piece of a diff, as jsdiff's structuredPatch gives it: lines starting " ", "-" or "+". */
324
+ export const DiffHunkSchema = z.object({
325
+ oldStart: z.number().int().nonnegative(),
326
+ oldLines: z.number().int().nonnegative(),
327
+ newStart: z.number().int().nonnegative(),
328
+ newLines: z.number().int().nonnegative(),
329
+ lines: z.array(z.string()),
330
+ });
331
+ export type DiffHunk = z.infer<typeof DiffHunkSchema>;
332
+
333
+ /** Most entries one files.list gives. */
334
+ export const MAX_LIST_ENTRIES = 2000;
335
+
336
+ /** Most bytes of text one files.read gives. */
337
+ export const MAX_READ_BYTES = 512 * 1024;
338
+
339
+ // ---------------------------------------------------------------------------
340
+ // Chats
341
+ // ---------------------------------------------------------------------------
342
+
343
+ /** Most items one chat.read gives; earlier ones come by `before`. */
344
+ export const MAX_READ_ITEMS = 500;
345
+
346
+ /**
347
+ * A page of a chat: its status, the items from `start` (before `total`),
348
+ * and the tool calls, tasks and subagents' messages they name.
349
+ */
350
+ export const ChatPageSchema = z.object({
351
+ status: ChatStatusSchema,
352
+ start: z.number().int().nonnegative(),
353
+ total: z.number().int().nonnegative(),
354
+ items: z.array(ViewItemSchema),
355
+ tools: z.record(ViewToolCallSchema),
356
+ tasks: z.record(ViewTaskSchema),
357
+ agentItems: z.record(z.array(AssistantItemSchema)),
358
+ });
359
+ export type ChatPage = z.infer<typeof ChatPageSchema>;
360
+
361
+ /**
362
+ * What changed in a watched chat since its last update (or its watch
363
+ * began). Items are put at their index; `total` cuts the list when it got
364
+ * shorter. Tool calls, tasks and subagents' messages are put by id.
365
+ */
366
+ export const ChatUpdateSchema = z.object({
367
+ watchId: z.string(),
368
+ /** Counts the watch's updates from 1, so one lost shows. */
369
+ rev: z.number().int().positive(),
370
+ status: ChatStatusSchema.optional(),
371
+ total: z.number().int().nonnegative(),
372
+ items: z.array(z.object({ index: z.number().int().nonnegative(), item: ViewItemSchema })),
373
+ tools: z.record(ViewToolCallSchema),
374
+ tasks: z.record(ViewTaskSchema),
375
+ agentItems: z.record(z.array(AssistantItemSchema)),
376
+ /** The side panel, when it changed. */
377
+ panel: ChatPanelSchema.optional(),
378
+ });
379
+ export type ChatUpdate = z.infer<typeof ChatUpdateSchema>;
380
+
381
+ /**
382
+ * A watched terminal's text changed: the text from `start` (a UTF-16
383
+ * offset into the text as it was) is now `text`. A redraw at the bottom
384
+ * sends only the bottom; a scroll, all of it from 0. A watch with `ansi`
385
+ * counts in the text with its escapes.
386
+ */
387
+ export const TerminalUpdateSchema = z.object({
388
+ watchId: z.string(),
389
+ /** Counts the watch's updates from 1, so one lost shows. */
390
+ rev: z.number().int().positive(),
391
+ start: z.number().int().nonnegative(),
392
+ text: z.string(),
393
+ });
394
+ export type TerminalUpdate = z.infer<typeof TerminalUpdateSchema>;
395
+
396
+ /** The sessions' list as it is now, sent whenever it changes during a sessions.watch. */
397
+ export const SessionsUpdateSchema = SessionsSchema.extend({ watchId: z.string() });
398
+ export type SessionsUpdate = z.infer<typeof SessionsUpdateSchema>;
399
+
400
+ const Ok = z.object({});
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // The methods
404
+ // ---------------------------------------------------------------------------
405
+
406
+ /**
407
+ * Each method's params and result, and the capability (see ./sealed.ts)
408
+ * the serving device lists for it.
409
+ */
410
+ export const RPC_METHODS = {
411
+ "sessions.list": { capability: "sessions", params: Ok, result: SessionsSchema },
412
+ /** The list now; then a sessions.update each time it changes, until sessions.unwatch. */
413
+ "sessions.watch": {
414
+ capability: "sessions",
415
+ params: Ok,
416
+ result: SessionsSchema.extend({ watchId: z.string() }),
417
+ },
418
+ "sessions.unwatch": {
419
+ capability: "sessions",
420
+ params: z.object({ watchId: z.string() }),
421
+ result: Ok,
422
+ },
423
+ /**
424
+ * The session state changes after `since` (the first `limit`, `more` when
425
+ * some were left out), or the last `limit`; `cursor` is the latest seq. A
426
+ * `since` past it (from before the app restarted) reads from the start.
427
+ */
428
+ "events.read": {
429
+ capability: "sessions",
430
+ params: z.object({
431
+ since: z.number().int().nonnegative().optional(),
432
+ limit: z.number().int().positive().max(500).optional(),
433
+ }),
434
+ result: z.object({
435
+ events: z.array(SessionEventSchema),
436
+ cursor: z.number().int().nonnegative(),
437
+ more: z.boolean(),
438
+ }),
439
+ },
440
+ /** The agent profiles a chat can run with (accounts, config folders). */
441
+ "profiles.list": {
442
+ capability: "sessions",
443
+ params: z.object({ agent: z.enum(["claude", "codex"]).optional() }),
444
+ result: z.object({
445
+ profiles: z.array(
446
+ z.object({
447
+ id: z.string(),
448
+ name: z.string(),
449
+ agent: z.enum(["claude", "codex"]),
450
+ /** The one a workspace runs with unless told otherwise. */
451
+ isDefault: z.boolean(),
452
+ }),
453
+ ),
454
+ }),
455
+ },
456
+ /** The past chats of a workspace's folder that can be resumed, latest first. */
457
+ "history.list": {
458
+ capability: "chat.read",
459
+ params: z.object({
460
+ workspaceId: z.string(),
461
+ agent: z.enum(["claude", "codex"]),
462
+ /** Only those whose title has it. */
463
+ query: z.string().max(200).optional(),
464
+ limit: z.number().int().positive().max(200).optional(),
465
+ }),
466
+ result: z.object({ sessions: z.array(PastSessionSchema) }),
467
+ },
468
+
469
+ /** The chat's last `limit` items, or those before `before`. */
470
+ "chat.read": {
471
+ capability: "chat.read",
472
+ params: z.object({
473
+ ...TabRef,
474
+ before: z.number().int().nonnegative().optional(),
475
+ limit: z.number().int().positive().max(MAX_READ_ITEMS).optional(),
476
+ }),
477
+ result: ChatPageSchema,
478
+ },
479
+ /** The chat's last page now; then a chat.update each time it changes, until chat.unwatch. */
480
+ "chat.watch": {
481
+ capability: "chat.read",
482
+ params: z.object({
483
+ ...TabRef,
484
+ limit: z.number().int().positive().max(MAX_READ_ITEMS).optional(),
485
+ }),
486
+ result: ChatPageSchema.extend({ watchId: z.string(), panel: ChatPanelSchema.optional() }),
487
+ },
488
+ "chat.unwatch": {
489
+ capability: "chat.read",
490
+ params: z.object({ watchId: z.string() }),
491
+ result: Ok,
492
+ },
493
+ /** What the chat runs with and may be set to (model, effort, permission mode). */
494
+ "chat.settings": {
495
+ capability: "chat.read",
496
+ params: z.object(TabRef),
497
+ result: ChatSettingsSchema,
498
+ },
499
+ /** Its slash commands, the app's and the agent's, for a "/" picker. */
500
+ "chat.commands": {
501
+ capability: "chat.read",
502
+ params: z.object(TabRef),
503
+ result: z.object({ commands: z.array(ChatCommandSchema) }),
504
+ },
505
+ /** Its side panel now; a watch sends it again in chat.update as it changes. */
506
+ "chat.panel": {
507
+ capability: "chat.read",
508
+ params: z.object(TabRef),
509
+ result: ChatPanelSchema,
510
+ },
511
+ /** One tool call with as much of its result as a frame takes. */
512
+ "chat.tool": {
513
+ capability: "chat.read",
514
+ params: z.object({ ...TabRef, toolUseId: z.string() }),
515
+ result: ViewToolCallSchema,
516
+ },
517
+ /**
518
+ * Waits up to `timeoutMs` (at most MAX_WAIT_MS) for the chat to be done
519
+ * with its turn: no longer working (asking, idle, error, or closed). Ask
520
+ * again while `done` is false. `after`: a chat.send's `at`, so a message
521
+ * the chat has not shown yet counts as working.
522
+ */
523
+ "chat.wait": {
524
+ capability: "chat.read",
525
+ params: z.object({
526
+ ...TabRef,
527
+ timeoutMs: z.number().int().positive().max(MAX_WAIT_MS).optional(),
528
+ after: z.number().optional(),
529
+ }),
530
+ result: z.object({
531
+ done: z.boolean(),
532
+ state: ChatWaitStateSchema,
533
+ /** Its last answer; when asking, what it asks; on an error, what went wrong. */
534
+ message: z.string().optional(),
535
+ }),
536
+ },
537
+ /**
538
+ * An image of the chat, made small enough for a frame: a user message's
539
+ * (by its item's key and the image's index) or a tool result's.
540
+ */
541
+ "chat.image": {
542
+ capability: "chat.read",
543
+ params: z.object({
544
+ ...TabRef,
545
+ ref: z.discriminatedUnion("kind", [
546
+ z.object({
547
+ kind: z.literal("user"),
548
+ itemKey: z.string(),
549
+ index: z.number().int().nonnegative(),
550
+ }),
551
+ z.object({
552
+ kind: z.literal("tool"),
553
+ toolUseId: z.string(),
554
+ index: z.number().int().nonnegative(),
555
+ }),
556
+ ]),
557
+ }),
558
+ result: z.object({
559
+ mediaType: ImageMediaTypeSchema,
560
+ /** Base64. */
561
+ data: z.string(),
562
+ width: z.number().int().positive().optional(),
563
+ height: z.number().int().positive().optional(),
564
+ }),
565
+ },
566
+
567
+ /**
568
+ * Sends a message, as its composer does: during a turn, the turn reads it
569
+ * next. `text` may be empty only with attachments. Sent by an agent
570
+ * (`from`), the chat shows it as that agent's, not the user's.
571
+ */
572
+ "chat.send": {
573
+ capability: "chat.control",
574
+ params: z.object({
575
+ ...TabRef,
576
+ text: z.string(),
577
+ /** Images chat.attach took, at most MAX_ATTACHMENTS. */
578
+ attachments: z.array(z.string()).max(MAX_ATTACHMENTS).optional(),
579
+ from: AgentSenderSchema.optional(),
580
+ }),
581
+ /** `at`: when the serving device took it, by its clock, for chat.wait's `after`. */
582
+ result: z.object({ at: z.number().optional() }),
583
+ },
584
+ /**
585
+ * Takes an image for the next chat.send to this tab: one image a request,
586
+ * small enough for a frame. Kept 10 minutes, for this device only.
587
+ */
588
+ "chat.attach": {
589
+ capability: "chat.control",
590
+ params: z.object({
591
+ ...TabRef,
592
+ mediaType: ImageMediaTypeSchema,
593
+ /** Base64, of at most MAX_ATTACHMENT_BYTES bytes. */
594
+ data: z
595
+ .string()
596
+ .min(1)
597
+ .max(Math.ceil(MAX_ATTACHMENT_BYTES / 3) * 4),
598
+ }),
599
+ result: z.object({ attachmentId: z.string() }),
600
+ },
601
+ /** Answers the permission request `requestId`, as its card's buttons do. */
602
+ "chat.answer": {
603
+ capability: "chat.control",
604
+ params: z.object({
605
+ ...TabRef,
606
+ requestId: z.string(),
607
+ decision: z.enum(["allow", "deny"]),
608
+ /** Why, for a denial: the program reads it. */
609
+ message: z.string().optional(),
610
+ /** With allow: the input the tool runs with, as the user filled it (a question's answers). */
611
+ updatedInput: z.record(z.unknown()).optional(),
612
+ /** With deny: the turn stops too, as the card's "No, and stop" does. */
613
+ stop: z.boolean().optional(),
614
+ /** With allow: the request's suggestions to keep from now on, by index ("always allow"). */
615
+ always: z.array(z.number().int().nonnegative()).optional(),
616
+ from: AgentSenderSchema.optional(),
617
+ }),
618
+ result: Ok,
619
+ },
620
+ "chat.interrupt": {
621
+ capability: "chat.control",
622
+ params: z.object({ ...TabRef, from: AgentSenderSchema.optional() }),
623
+ result: Ok,
624
+ },
625
+ /**
626
+ * Sets any of model, effort and permission mode, as the composer's chips
627
+ * do; what it runs with after. A mode the serving device's policy does
628
+ * not allow is refused (Forbidden) with why.
629
+ */
630
+ "chat.configure": {
631
+ capability: "chat.control",
632
+ params: z.object({
633
+ ...TabRef,
634
+ model: z.string().min(1).max(100).optional(),
635
+ effort: z.string().min(1).max(100).optional(),
636
+ permissionMode: z.string().min(1).max(100).optional(),
637
+ from: AgentSenderSchema.optional(),
638
+ }),
639
+ result: ChatSettingsSchema,
640
+ },
641
+ /** Runs one of the app's slash commands (chat.commands' `command` ones), `args` after its name. */
642
+ "chat.command": {
643
+ capability: "chat.control",
644
+ params: z.object({
645
+ ...TabRef,
646
+ name: z.string().min(1).max(100),
647
+ args: z.string().max(10_000).optional(),
648
+ }),
649
+ result: z.object({
650
+ /** What it said, when it says something rather than changing the chat. */
651
+ message: z.string().optional(),
652
+ /** The tab it opened, when it opened one. */
653
+ tabId: z.string().optional(),
654
+ }),
655
+ },
656
+ /** Stops a task of the chat's (a background run, a subagent), as the side panel's button does. */
657
+ "chat.stopTask": {
658
+ capability: "chat.control",
659
+ params: z.object({ ...TabRef, taskId: z.string() }),
660
+ result: Ok,
661
+ },
662
+ "chat.rename": {
663
+ capability: "chat.control",
664
+ params: z.object({ ...TabRef, title: z.string().min(1).max(200) }),
665
+ result: z.object({ title: z.string() }),
666
+ },
667
+ /** Opens a past chat (history.list) in a new tab. */
668
+ "chat.resume": {
669
+ capability: "chat.control",
670
+ params: z.object({
671
+ workspaceId: z.string(),
672
+ agent: z.enum(["claude", "codex"]),
673
+ sessionId: z.string(),
674
+ }),
675
+ result: z.object({ tabId: z.string() }),
676
+ },
677
+ /**
678
+ * Opens a chat in one of the serving device's workspaces, sending it
679
+ * `prompt` if given. `model` and `effort` are set before the prompt goes,
680
+ * named as the agent's own menus name them ("haiku", "low"); the tab's
681
+ * profile's own otherwise.
682
+ */
683
+ "chat.new": {
684
+ capability: "chat.control",
685
+ params: z.object({
686
+ workspaceId: z.string(),
687
+ agent: z.enum(["claude", "codex"]),
688
+ prompt: z.string().optional(),
689
+ model: z.string().min(1).max(100).optional(),
690
+ effort: z.string().min(1).max(100).optional(),
691
+ permissionMode: z.string().min(1).max(100).optional(),
692
+ /** The agent profile, by id or name (profiles.list); the workspace's otherwise. */
693
+ profile: z.string().min(1).max(100).optional(),
694
+ /** A folder inside the workspace to run in; its own folder otherwise. */
695
+ folder: z.string().min(1).max(4096).optional(),
696
+ /** Sent by an agent: the chat shows the prompt as that agent's. */
697
+ from: AgentSenderSchema.optional(),
698
+ }),
699
+ result: z.object({
700
+ tabId: z.string(),
701
+ /** The tab opened, but the model or effort could not be set: the prompt was not sent. */
702
+ error: z.string().optional(),
703
+ }),
704
+ },
705
+ "chat.close": {
706
+ capability: "chat.control",
707
+ params: z.object({ ...TabRef, from: AgentSenderSchema.optional() }),
708
+ result: Ok,
709
+ },
710
+
711
+ /**
712
+ * A terminal's screen and the lines above it, as text; with `ansi`, with
713
+ * its colors and styles as SGR escapes (no other escapes).
714
+ */
715
+ "terminal.read": {
716
+ capability: "terminal.read",
717
+ params: z.object({
718
+ ...TabRef,
719
+ lines: z.number().int().positive().max(5000).optional(),
720
+ ansi: z.boolean().optional(),
721
+ }),
722
+ result: z.object({ text: z.string() }),
723
+ },
724
+ /** The terminal's text now, as terminal.read; then a terminal.update each time it changes, until terminal.unwatch. */
725
+ "terminal.watch": {
726
+ capability: "terminal.read",
727
+ params: z.object({
728
+ ...TabRef,
729
+ lines: z.number().int().positive().max(5000).optional(),
730
+ ansi: z.boolean().optional(),
731
+ }),
732
+ result: z.object({ text: z.string(), watchId: z.string() }),
733
+ },
734
+ "terminal.unwatch": {
735
+ capability: "terminal.read",
736
+ params: z.object({ watchId: z.string() }),
737
+ result: Ok,
738
+ },
739
+ /**
740
+ * Types into a terminal: `text` as pasted, then `keys` by name
741
+ * (TERMINAL_KEYS), then Enter when `enter`. Sent by an agent (`from`), the receiving device counts it
742
+ * as that agent's.
743
+ */
744
+ "terminal.input": {
745
+ capability: "terminal.control",
746
+ params: z.object({
747
+ ...TabRef,
748
+ text: z
749
+ .string()
750
+ .max(64 * 1024)
751
+ .optional(),
752
+ keys: z.array(TerminalKeySchema).max(64).optional(),
753
+ enter: z.boolean().optional(),
754
+ from: AgentSenderSchema.optional(),
755
+ }),
756
+ /** `at`: when it was typed, by the serving device's clock, for terminal.wait's `after`. */
757
+ result: z.object({ at: z.number().optional() }),
758
+ },
759
+ /**
760
+ * Waits up to `timeoutMs` (at most MAX_WAIT_MS) as `nexus terminal wait`
761
+ * does: for the terminal's agent to finish its turn, its shell to be back
762
+ * at the prompt, or quiet output; with `exit`, for its program to end;
763
+ * with `match`, for a line to match. Ask again while `done` is false.
764
+ */
765
+ "terminal.wait": {
766
+ capability: "terminal.read",
767
+ params: z.object({
768
+ ...TabRef,
769
+ timeoutMs: z.number().int().positive().max(MAX_WAIT_MS).optional(),
770
+ /** A terminal.input's `at`: a turn must have started after it. */
771
+ after: z.number().optional(),
772
+ exit: z.boolean().optional(),
773
+ match: z.string().min(1).max(1000).optional(),
774
+ /** Quiet for this long counts as idle, for a program that is no agent or shell. */
775
+ quietMs: z.number().int().positive().max(600_000).optional(),
776
+ }),
777
+ result: z.object({
778
+ done: z.boolean(),
779
+ /** idle, completed, needsInput, permissionPending, error, notStarted, notified, exited, matched, or waiting. */
780
+ state: z.string(),
781
+ message: z.string().optional(),
782
+ }),
783
+ },
784
+ /**
785
+ * Answers the permission request a terminal's Claude Code holds for the
786
+ * app (its session's `waiting.requestId`), as the agent list's buttons do.
787
+ * An answer for agents, so chat.control's: no typing goes in.
788
+ */
789
+ "terminal.answer": {
790
+ capability: "chat.control",
791
+ params: z.object({
792
+ ...TabRef,
793
+ requestId: z.string(),
794
+ decision: z.enum(["allow", "allowAlways", "deny", "denyStop"]),
795
+ from: AgentSenderSchema.optional(),
796
+ }),
797
+ result: Ok,
798
+ },
799
+ /** The shells a new terminal can run, as "New terminal with" lists them. */
800
+ "terminal.shells": {
801
+ capability: "terminal.control",
802
+ params: z.object({ workspaceId: z.string() }),
803
+ result: z.object({
804
+ shells: z.array(z.object({ id: z.string(), name: z.string(), isDefault: z.boolean() })),
805
+ }),
806
+ },
807
+ /** Opens a terminal: a shell (by its id), in a folder inside the workspace, running `command`. */
808
+ "terminal.open": {
809
+ capability: "terminal.control",
810
+ params: z.object({
811
+ workspaceId: z.string(),
812
+ shell: z.string().min(1).max(200).optional(),
813
+ folder: z.string().min(1).max(4096).optional(),
814
+ command: z.string().min(1).max(10_000).optional(),
815
+ title: z.string().min(1).max(200).optional(),
816
+ from: AgentSenderSchema.optional(),
817
+ }),
818
+ result: z.object({ tabId: z.string() }),
819
+ },
820
+ "terminal.rename": {
821
+ capability: "terminal.control",
822
+ params: z.object({ ...TabRef, title: z.string().min(1).max(200) }),
823
+ result: z.object({ title: z.string() }),
824
+ },
825
+ /** Closes a terminal; one running a program only with `force`. */
826
+ "terminal.close": {
827
+ capability: "terminal.control",
828
+ params: z.object({
829
+ ...TabRef,
830
+ force: z.boolean().optional(),
831
+ from: AgentSenderSchema.optional(),
832
+ }),
833
+ result: Ok,
834
+ },
835
+
836
+ /**
837
+ * A folder's entries, folders first. `path` is absolute or inside the
838
+ * workspace's folder ("" for it); it must be in the workspace's folders
839
+ * (its own, and those its chats were given).
840
+ */
841
+ "files.list": {
842
+ capability: "files",
843
+ params: z.object({ workspaceId: z.string(), path: z.string().max(4096) }),
844
+ result: z.object({
845
+ /** The folder, absolute. */
846
+ path: z.string(),
847
+ entries: z.array(
848
+ z.object({
849
+ name: z.string(),
850
+ kind: z.enum(["file", "dir", "link"]),
851
+ size: z.number().int().nonnegative().optional(),
852
+ }),
853
+ ),
854
+ /** More than MAX_LIST_ENTRIES: the rest left out. */
855
+ truncated: z.boolean().optional(),
856
+ }),
857
+ },
858
+ /** A file: text (its start, up to `maxBytes`), an image made small enough for a frame, or that it is binary. */
859
+ "files.read": {
860
+ capability: "files",
861
+ params: z.object({
862
+ workspaceId: z.string(),
863
+ path: z.string().min(1).max(4096),
864
+ maxBytes: z.number().int().positive().max(MAX_READ_BYTES).optional(),
865
+ }),
866
+ result: z.discriminatedUnion("kind", [
867
+ z.object({
868
+ kind: z.literal("text"),
869
+ path: z.string(),
870
+ text: z.string(),
871
+ size: z.number().int().nonnegative(),
872
+ truncated: z.boolean(),
873
+ }),
874
+ z.object({
875
+ kind: z.literal("image"),
876
+ path: z.string(),
877
+ mediaType: ImageMediaTypeSchema,
878
+ data: z.string(),
879
+ size: z.number().int().nonnegative(),
880
+ }),
881
+ z.object({
882
+ kind: z.literal("binary"),
883
+ path: z.string(),
884
+ size: z.number().int().nonnegative(),
885
+ }),
886
+ ]),
887
+ },
888
+
889
+ /** The workspace's branch, how it stands against its upstream, and its changed files. */
890
+ "git.status": {
891
+ capability: "git",
892
+ params: z.object({ workspaceId: z.string() }),
893
+ result: z.object({
894
+ /** null when no branch is checked out. */
895
+ branch: z.string().nullable(),
896
+ upstream: z.string().optional(),
897
+ ahead: z.number().int().nonnegative(),
898
+ behind: z.number().int().nonnegative(),
899
+ files: z.array(GitFileSchema),
900
+ /** More files than a frame takes: the rest left out. */
901
+ truncated: z.boolean().optional(),
902
+ }),
903
+ },
904
+ /** A file's changes, staged or not, in hunks as an edit's patch has them. */
905
+ "git.diff": {
906
+ capability: "git",
907
+ params: z.object({
908
+ workspaceId: z.string(),
909
+ path: z.string().min(1).max(4096),
910
+ staged: z.boolean().optional(),
911
+ }),
912
+ result: z.object({
913
+ path: z.string(),
914
+ oldPath: z.string().optional(),
915
+ binary: z.boolean().optional(),
916
+ hunks: z.array(DiffHunkSchema),
917
+ /** More than a frame takes: the hunks after left out. */
918
+ truncated: z.boolean().optional(),
919
+ }),
920
+ },
921
+ /** The branch's commits, latest first. */
922
+ "git.log": {
923
+ capability: "git",
924
+ params: z.object({
925
+ workspaceId: z.string(),
926
+ limit: z.number().int().positive().max(200).optional(),
927
+ skip: z.number().int().nonnegative().optional(),
928
+ }),
929
+ result: z.object({
930
+ commits: z.array(
931
+ z.object({
932
+ hash: z.string(),
933
+ subject: z.string(),
934
+ author: z.string(),
935
+ /** Unix milliseconds. */
936
+ at: z.number(),
937
+ refs: z.array(z.string()).optional(),
938
+ }),
939
+ ),
940
+ }),
941
+ },
942
+ } as const;
943
+
944
+ export type RpcMethod = keyof typeof RPC_METHODS;
945
+ export type RpcParams<M extends RpcMethod> = z.infer<(typeof RPC_METHODS)[M]["params"]>;
946
+ export type RpcResult<M extends RpcMethod> = z.infer<(typeof RPC_METHODS)[M]["result"]>;
947
+
948
+ /** The notifications a serving device sends, by method. */
949
+ export const RPC_NOTIFICATIONS = {
950
+ "sessions.update": SessionsUpdateSchema,
951
+ "chat.update": ChatUpdateSchema,
952
+ "terminal.update": TerminalUpdateSchema,
953
+ } as const;
954
+
955
+ export type RpcNotificationMethod = keyof typeof RPC_NOTIFICATIONS;
956
+ export type RpcNotificationParams<M extends RpcNotificationMethod> = z.infer<
957
+ (typeof RPC_NOTIFICATIONS)[M]
958
+ >;
959
+
960
+ export function isRpcMethod(method: string): method is RpcMethod {
961
+ return Object.hasOwn(RPC_METHODS, method);
962
+ }