@diffexai/diffex 0.2.4 → 0.2.6

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 (81) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/AGENTS.md +0 -11
  4. package/dist/core/agent-session.d.ts +0 -1
  5. package/dist/core/agent-session.js +3 -10
  6. package/dist/core/sdk.js +1 -1
  7. package/dist/core/system-prompt-production.d.ts +7 -0
  8. package/dist/core/system-prompt-production.js +102 -0
  9. package/dist/core/system-prompt.d.ts +2 -2
  10. package/dist/core/system-prompt.js +34 -35
  11. package/dist/core/tools/subagents.js +22 -9
  12. package/dist/modes/print-mode.js +12 -14
  13. package/dist/node_modules/@diffexai/diffex-agent-core/distribution-components.json +4 -4
  14. package/dist/node_modules/@diffexai/diffex-agent-core/distribution-files.json +1 -1
  15. package/dist/node_modules/@diffexai/diffex-agent-core/package.json +1 -1
  16. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/.manifest.json +1 -1
  17. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/amazon-bedrock.json +1 -1
  18. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  19. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/fireworks.json +1 -1
  20. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/mistral.json +1 -1
  21. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/nvidia.json +1 -1
  22. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/openrouter.json +1 -1
  23. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  24. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/qwen-token-plan.json +1 -1
  25. package/dist/node_modules/@diffexai/diffex-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  26. package/dist/node_modules/@diffexai/diffex-ai/distribution-components.json +3 -3
  27. package/dist/node_modules/@diffexai/diffex-ai/distribution-files.json +11 -11
  28. package/dist/node_modules/@diffexai/diffex-ai/package.json +1 -1
  29. package/dist/node_modules/@diffexai/diffex-client/distribution-components.json +3 -3
  30. package/dist/node_modules/@diffexai/diffex-client/distribution-files.json +1 -1
  31. package/dist/node_modules/@diffexai/diffex-client/package.json +1 -1
  32. package/dist/node_modules/@diffexai/diffex-harness-state/distribution-components.json +2 -2
  33. package/dist/node_modules/@diffexai/diffex-harness-state/distribution-files.json +1 -1
  34. package/dist/node_modules/@diffexai/diffex-harness-state/package.json +1 -1
  35. package/dist/node_modules/@diffexai/diffex-protocol/distribution-components.json +2 -2
  36. package/dist/node_modules/@diffexai/diffex-protocol/distribution-files.json +1 -1
  37. package/dist/node_modules/@diffexai/diffex-protocol/package.json +1 -1
  38. package/dist/node_modules/@diffexai/diffex-telemetry/distribution-components.json +2 -2
  39. package/dist/node_modules/@diffexai/diffex-telemetry/distribution-files.json +1 -1
  40. package/dist/node_modules/@diffexai/diffex-telemetry/package.json +1 -1
  41. package/dist/node_modules/@diffexai/diffex-tui/distribution-components.json +2 -2
  42. package/dist/node_modules/@diffexai/diffex-tui/distribution-files.json +1 -1
  43. package/dist/node_modules/@diffexai/diffex-tui/package.json +1 -1
  44. package/dist/server/create-harness.js +1 -1
  45. package/distribution-components.json +11 -11
  46. package/distribution-files.json +49 -41
  47. package/npm-shrinkwrap.json +2 -2
  48. package/package.json +1 -31
  49. package/release/distribution-manifest.json +4 -4
  50. package/release/install-package-lock.json +5 -5
  51. package/release/install-package.json +2 -2
  52. package/docs/compaction.md +0 -401
  53. package/docs/containerization.md +0 -84
  54. package/docs/custom-provider.md +0 -774
  55. package/docs/environment-variables.md +0 -88
  56. package/docs/evolution.md +0 -90
  57. package/docs/extensions.md +0 -2982
  58. package/docs/images/interactive-mode.png +0 -0
  59. package/docs/images/tree-view.png +0 -0
  60. package/docs/installation.md +0 -118
  61. package/docs/json.md +0 -91
  62. package/docs/keybindings.md +0 -241
  63. package/docs/llama-cpp.md +0 -99
  64. package/docs/models.md +0 -565
  65. package/docs/packages.md +0 -232
  66. package/docs/prompt-templates.md +0 -96
  67. package/docs/providers.md +0 -317
  68. package/docs/quickstart.md +0 -161
  69. package/docs/rpc.md +0 -1647
  70. package/docs/sdk.md +0 -1332
  71. package/docs/security.md +0 -66
  72. package/docs/session-format.md +0 -438
  73. package/docs/sessions.md +0 -162
  74. package/docs/settings.md +0 -341
  75. package/docs/shell-aliases.md +0 -13
  76. package/docs/skills.md +0 -227
  77. package/docs/terminal-setup.md +0 -152
  78. package/docs/themes.md +0 -326
  79. package/docs/tmux.md +0 -63
  80. package/docs/tui.md +0 -940
  81. package/docs/usage.md +0 -434
package/docs/rpc.md DELETED
@@ -1,1647 +0,0 @@
1
- # RPC Mode
2
-
3
- RPC mode enables headless operation of the coding agent via a JSON protocol over stdin/stdout. This is useful for embedding the agent in other applications, IDEs, or custom UIs.
4
-
5
- **Note for Node.js/TypeScript users**: If you're building a Node.js application, consider using `AgentSession` directly from `@diffexai/diffex` instead of spawning a subprocess. See [`src/core/agent-session.ts`](../src/core/agent-session.ts) for the API. For a subprocess-based TypeScript client, see [`src/modes/rpc/rpc-client.ts`](../src/modes/rpc/rpc-client.ts).
6
-
7
- ## Starting RPC Mode
8
-
9
- ```bash
10
- diffex --mode rpc [options]
11
- ```
12
-
13
- Common options:
14
- - `--provider <name>`: Set the LLM provider (anthropic, openai, google, etc.)
15
- - `--model <pattern>`: Model pattern or ID (supports `provider/id` and optional `:<thinking>`)
16
- - `--name <name>` / `-n <name>`: Set the session display name at startup
17
- - `--no-session`: Disable session persistence
18
- - `--session-dir <path>`: Custom session storage directory
19
-
20
- ## Protocol Overview
21
-
22
- - **Commands**: JSON objects sent to stdin, one per line
23
- - **Responses**: JSON objects with `type: "response"` indicating command success/failure
24
- - **Events**: Agent events streamed to stdout as JSON lines
25
-
26
- All commands support an optional `id` field for request/response correlation. If provided, the corresponding response will include the same `id`. `bash_execution_update` events also include the `id` of their originating `bash` command.
27
-
28
- ### Framing
29
-
30
- RPC mode uses strict JSONL semantics with LF (`\n`) as the only record delimiter.
31
-
32
- This matters for clients:
33
- - Split records on `\n` only
34
- - Accept optional `\r\n` input by stripping a trailing `\r`
35
- - Do not use generic line readers that treat Unicode separators as newlines
36
-
37
- In particular, Node `readline` is not protocol-compliant for RPC mode because it also splits on `U+2028` and `U+2029`, which are valid inside JSON strings.
38
-
39
- ## Commands
40
-
41
- ### Prompting
42
-
43
- #### prompt
44
-
45
- Send a user prompt to the agent. The command response is emitted after the prompt is accepted, queued, or handled. Events continue streaming asynchronously after acceptance.
46
-
47
- ```json
48
- {"id": "req-1", "type": "prompt", "message": "Hello, world!"}
49
- ```
50
-
51
- With images:
52
- ```json
53
- {"type": "prompt", "message": "What's in this image?", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}
54
- ```
55
-
56
- **During streaming**: If the agent is already streaming, you must specify `streamingBehavior` to queue the message:
57
-
58
- ```json
59
- {"type": "prompt", "message": "New instruction", "streamingBehavior": "steer"}
60
- ```
61
-
62
- - `"steer"`: Queue the message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
63
- - `"followUp"`: Wait until the agent finishes. Message is delivered only when agent stops.
64
-
65
- If the agent is streaming and no `streamingBehavior` is specified, the command returns an error.
66
-
67
- **Extension commands**: If the message is an extension command (e.g., `/mycommand`), it executes immediately even during streaming. Extension commands manage their own LLM interaction via `diffex.sendMessage()`.
68
-
69
- **Input expansion**: Prompt templates (`/template`) and explicit versioned skill references are expanded before sending or queueing.
70
-
71
- Response:
72
- ```json
73
- {"id": "req-1", "type": "response", "command": "prompt", "success": true}
74
- ```
75
-
76
- `success: true` means the prompt was accepted, queued, or handled immediately. `success: false` means the prompt was rejected before acceptance. Failures after acceptance are reported through the normal event and message stream, not as a second `response` for the same request id.
77
-
78
- Acceptance is not settlement.
79
- If the parent spawns coordinated children, events continue while RPC mode waits for the frozen child batch and automatically resumes the parent with hidden results.
80
- Wait for `agent_settled`, not the `prompt` response or the first `agent_end`, before treating the prompt cycle as complete.
81
-
82
- The `images` field is optional. Each image uses `ImageContent` format: `{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}`.
83
-
84
- #### steer
85
-
86
- Queue a steering message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Prompt templates and explicit skill references are expanded. Extension commands are not allowed (use `prompt` instead).
87
-
88
- ```json
89
- {"type": "steer", "message": "Stop and do this instead"}
90
- ```
91
-
92
- With images:
93
- ```json
94
- {"type": "steer", "message": "Look at this instead", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}
95
- ```
96
-
97
- The `images` field is optional. Each image uses `ImageContent` format (same as `prompt`).
98
-
99
- Response:
100
- ```json
101
- {"type": "response", "command": "steer", "success": true}
102
- ```
103
-
104
- See [set_steering_mode](#set_steering_mode) for controlling how steering messages are processed.
105
-
106
- #### follow_up
107
-
108
- Queue a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Prompt templates and explicit skill references are expanded. Extension commands are not allowed (use `prompt` instead).
109
-
110
- ```json
111
- {"type": "follow_up", "message": "After you're done, also do this"}
112
- ```
113
-
114
- With images:
115
- ```json
116
- {"type": "follow_up", "message": "Also check this image", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}
117
- ```
118
-
119
- The `images` field is optional. Each image uses `ImageContent` format (same as `prompt`).
120
-
121
- Response:
122
- ```json
123
- {"type": "response", "command": "follow_up", "success": true}
124
- ```
125
-
126
- See [set_follow_up_mode](#set_follow_up_mode) for controlling how follow-up messages are processed.
127
-
128
- #### abort
129
-
130
- Abort the current agent operation.
131
-
132
- During a coordinated child wait, this interrupts every unfinished child in the frozen batch, emits terminal notices and a cancelled wait end event, and settles without another parent provider call.
133
-
134
- ```json
135
- {"type": "abort"}
136
- ```
137
-
138
- Response:
139
- ```json
140
- {"type": "response", "command": "abort", "success": true}
141
- ```
142
-
143
- #### new_session
144
-
145
- Start a fresh session. Can be cancelled by a `session_before_switch` extension event handler.
146
-
147
- ```json
148
- {"type": "new_session"}
149
- ```
150
-
151
- With optional parent session tracking:
152
- ```json
153
- {"type": "new_session", "parentSession": "/path/to/parent-session.jsonl"}
154
- ```
155
-
156
- Response:
157
- ```json
158
- {"type": "response", "command": "new_session", "success": true, "data": {"cancelled": false}}
159
- ```
160
-
161
- If an extension cancelled:
162
- ```json
163
- {"type": "response", "command": "new_session", "success": true, "data": {"cancelled": true}}
164
- ```
165
-
166
- ### State
167
-
168
- #### get_state
169
-
170
- Get current session state.
171
-
172
- ```json
173
- {"type": "get_state"}
174
- ```
175
-
176
- Response:
177
- ```json
178
- {
179
- "type": "response",
180
- "command": "get_state",
181
- "success": true,
182
- "data": {
183
- "model": {...},
184
- "thinkingLevel": "medium",
185
- "isStreaming": false,
186
- "isCompacting": false,
187
- "steeringMode": "all",
188
- "followUpMode": "one-at-a-time",
189
- "sessionFile": "/path/to/session.jsonl",
190
- "sessionId": "abc123",
191
- "sessionName": "my-feature-work",
192
- "autoCompactionEnabled": true,
193
- "messageCount": 5,
194
- "pendingMessageCount": 0
195
- }
196
- }
197
- ```
198
-
199
- The `model` field is a full [Model](#model) object or `null`. The `sessionName` field is the display name set via `set_session_name`, or omitted if not set.
200
-
201
- #### get_messages
202
-
203
- Get all messages in the conversation.
204
-
205
- ```json
206
- {"type": "get_messages"}
207
- ```
208
-
209
- Response:
210
- ```json
211
- {
212
- "type": "response",
213
- "command": "get_messages",
214
- "success": true,
215
- "data": {"messages": [...]}
216
- }
217
- ```
218
-
219
- Messages are `AgentMessage` objects (see [Message Types](#message-types)).
220
-
221
- ### Model
222
-
223
- #### set_model
224
-
225
- Switch to a specific model.
226
-
227
- ```json
228
- {"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4-20250514"}
229
- ```
230
-
231
- Response contains the full [Model](#model) object:
232
- ```json
233
- {
234
- "type": "response",
235
- "command": "set_model",
236
- "success": true,
237
- "data": {...}
238
- }
239
- ```
240
-
241
- #### cycle_model
242
-
243
- Cycle to the next available model. Returns `null` data if only one model available.
244
-
245
- ```json
246
- {"type": "cycle_model"}
247
- ```
248
-
249
- Response:
250
- ```json
251
- {
252
- "type": "response",
253
- "command": "cycle_model",
254
- "success": true,
255
- "data": {
256
- "model": {...},
257
- "thinkingLevel": "medium",
258
- "isScoped": false
259
- }
260
- }
261
- ```
262
-
263
- The `model` field is a full [Model](#model) object.
264
-
265
- #### get_available_models
266
-
267
- List all configured models.
268
-
269
- ```json
270
- {"type": "get_available_models"}
271
- ```
272
-
273
- Response contains an array of full [Model](#model) objects:
274
- ```json
275
- {
276
- "type": "response",
277
- "command": "get_available_models",
278
- "success": true,
279
- "data": {
280
- "models": [...]
281
- }
282
- }
283
- ```
284
-
285
- ### Thinking
286
-
287
- #### set_thinking_level
288
-
289
- Set the reasoning/thinking level for models that support it.
290
-
291
- ```json
292
- {"type": "set_thinking_level", "level": "high"}
293
- ```
294
-
295
- Levels: `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"`
296
-
297
- `"xhigh"` and `"max"` are exposed only when supported by the selected model. Some models, including GPT-5.6, expose both.
298
-
299
- Response:
300
- ```json
301
- {"type": "response", "command": "set_thinking_level", "success": true}
302
- ```
303
-
304
- #### cycle_thinking_level
305
-
306
- Cycle through available thinking levels. Returns `null` data if model doesn't support thinking.
307
-
308
- ```json
309
- {"type": "cycle_thinking_level"}
310
- ```
311
-
312
- Response:
313
- ```json
314
- {
315
- "type": "response",
316
- "command": "cycle_thinking_level",
317
- "success": true,
318
- "data": {"level": "high"}
319
- }
320
- ```
321
-
322
- #### get_available_thinking_levels
323
-
324
- List the thinking levels supported by the current model. Returns `["off"]` for a model without reasoning support.
325
-
326
- ```json
327
- {"type": "get_available_thinking_levels"}
328
- ```
329
-
330
- Response:
331
- ```json
332
- {
333
- "type": "response",
334
- "command": "get_available_thinking_levels",
335
- "success": true,
336
- "data": {
337
- "levels": ["off", "minimal", "low", "medium", "high"]
338
- }
339
- }
340
- ```
341
-
342
- ### Queue Modes
343
-
344
- #### set_steering_mode
345
-
346
- Control how steering messages (from `steer`) are delivered.
347
-
348
- ```json
349
- {"type": "set_steering_mode", "mode": "one-at-a-time"}
350
- ```
351
-
352
- Modes:
353
- - `"all"`: Deliver all steering messages after the current assistant turn finishes executing its tool calls
354
- - `"one-at-a-time"`: Deliver one steering message per completed assistant turn (default)
355
-
356
- Response:
357
- ```json
358
- {"type": "response", "command": "set_steering_mode", "success": true}
359
- ```
360
-
361
- #### set_follow_up_mode
362
-
363
- Control how follow-up messages (from `follow_up`) are delivered.
364
-
365
- ```json
366
- {"type": "set_follow_up_mode", "mode": "one-at-a-time"}
367
- ```
368
-
369
- Modes:
370
- - `"all"`: Deliver all follow-up messages when agent finishes
371
- - `"one-at-a-time"`: Deliver one follow-up message per agent completion (default)
372
-
373
- Response:
374
- ```json
375
- {"type": "response", "command": "set_follow_up_mode", "success": true}
376
- ```
377
-
378
- ### Compaction
379
-
380
- #### compact
381
-
382
- Manually compact conversation context to reduce token usage.
383
-
384
- ```json
385
- {"type": "compact"}
386
- ```
387
-
388
- With custom instructions:
389
- ```json
390
- {"type": "compact", "customInstructions": "Focus on code changes"}
391
- ```
392
-
393
- Response:
394
- ```json
395
- {
396
- "type": "response",
397
- "command": "compact",
398
- "success": true,
399
- "data": {
400
- "summary": "Summary of conversation...",
401
- "firstKeptEntryId": "abc123",
402
- "tokensBefore": 150000,
403
- "estimatedTokensAfter": 32000,
404
- "usage": {
405
- "input": 32000,
406
- "output": 1200,
407
- "cacheRead": 0,
408
- "cacheWrite": 0,
409
- "totalTokens": 33200,
410
- "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}
411
- },
412
- "details": {}
413
- }
414
- }
415
- ```
416
-
417
- `estimatedTokensAfter` is a heuristic estimate over the rebuilt message context immediately after compaction, not a provider-exact token count. `usage` reports the LLM call or calls that generated the summary and may be omitted by custom compaction handlers.
418
-
419
- #### set_auto_compaction
420
-
421
- Enable or disable automatic compaction when context is nearly full.
422
-
423
- ```json
424
- {"type": "set_auto_compaction", "enabled": true}
425
- ```
426
-
427
- Response:
428
- ```json
429
- {"type": "response", "command": "set_auto_compaction", "success": true}
430
- ```
431
-
432
- ### Retry
433
-
434
- #### set_auto_retry
435
-
436
- Enable or disable automatic retry on transient errors (overloaded, rate limit, 5xx).
437
-
438
- ```json
439
- {"type": "set_auto_retry", "enabled": true}
440
- ```
441
-
442
- Response:
443
- ```json
444
- {"type": "response", "command": "set_auto_retry", "success": true}
445
- ```
446
-
447
- #### abort_retry
448
-
449
- Abort an in-progress retry (cancel the delay and stop retrying).
450
-
451
- ```json
452
- {"type": "abort_retry"}
453
- ```
454
-
455
- Response:
456
- ```json
457
- {"type": "response", "command": "abort_retry", "success": true}
458
- ```
459
-
460
- ### Bash
461
-
462
- #### bash
463
-
464
- Execute a shell command and add output to conversation context. Output streams as `bash_execution_update` events while the command runs; the response contains the final result.
465
-
466
- ```json
467
- {"id": "req-1", "type": "bash", "command": "ls -la"}
468
- ```
469
-
470
- Include an `id` to associate streamed `bash_execution_update` events with this command.
471
-
472
- Response:
473
- ```json
474
- {
475
- "id": "req-1",
476
- "type": "response",
477
- "command": "bash",
478
- "success": true,
479
- "data": {
480
- "output": "total 48\ndrwxr-xr-x ...",
481
- "exitCode": 0,
482
- "cancelled": false,
483
- "truncated": false
484
- }
485
- }
486
- ```
487
-
488
- If output was truncated, includes `fullOutputPath`:
489
- ```json
490
- {
491
- "type": "response",
492
- "command": "bash",
493
- "success": true,
494
- "data": {
495
- "output": "truncated output...",
496
- "exitCode": 0,
497
- "cancelled": false,
498
- "truncated": true,
499
- "fullOutputPath": "/tmp/diffex-bash-abc123.log"
500
- }
501
- }
502
- ```
503
-
504
- **How bash results reach the LLM:**
505
-
506
- The `bash` command executes immediately and returns a `BashResult`. Internally, a `BashExecutionMessage` is created and stored in the agent's message state.
507
-
508
- When the next `prompt` command is sent, all messages (including `BashExecutionMessage`) are transformed before being sent to the LLM. The `BashExecutionMessage` is converted to a `UserMessage` with this format:
509
-
510
- ````
511
- Ran `ls -la`
512
- ```
513
- total 48
514
- drwxr-xr-x ...
515
- ```
516
- ````
517
-
518
- This means:
519
- 1. Bash output is included in the LLM context on the **next prompt**, not immediately
520
- 2. Multiple bash commands can be executed before a prompt; all outputs will be included
521
-
522
- #### abort_bash
523
-
524
- Abort a running bash command.
525
-
526
- ```json
527
- {"type": "abort_bash"}
528
- ```
529
-
530
- Response:
531
- ```json
532
- {"type": "response", "command": "abort_bash", "success": true}
533
- ```
534
-
535
- ### Session
536
-
537
- #### get_session_stats
538
-
539
- Get token usage, cost statistics, and current context window usage.
540
-
541
- ```json
542
- {"type": "get_session_stats"}
543
- ```
544
-
545
- Response:
546
- ```json
547
- {
548
- "type": "response",
549
- "command": "get_session_stats",
550
- "success": true,
551
- "data": {
552
- "sessionFile": "/path/to/session.jsonl",
553
- "sessionId": "abc123",
554
- "userMessages": 5,
555
- "assistantMessages": 5,
556
- "toolCalls": 12,
557
- "toolResults": 12,
558
- "totalMessages": 22,
559
- "tokens": {
560
- "input": 50000,
561
- "output": 10000,
562
- "cacheRead": 40000,
563
- "cacheWrite": 5000,
564
- "total": 105000
565
- },
566
- "cost": 0.45,
567
- "contextUsage": {
568
- "tokens": 60000,
569
- "contextWindow": 200000,
570
- "percent": 30
571
- }
572
- }
573
- }
574
- ```
575
-
576
- `tokens` and `cost` include assistant messages, usage reported by tools, and compaction/branch-summary generation across the full session. `contextUsage` contains the actual current context-window estimate used for compaction and footer display.
577
-
578
- `contextUsage` is omitted when no model or context window is available. `contextUsage.tokens` and `contextUsage.percent` are `null` immediately after compaction until a fresh post-compaction assistant response provides valid usage data.
579
-
580
- #### export_html
581
-
582
- Export session to an HTML file.
583
-
584
- ```json
585
- {"type": "export_html"}
586
- ```
587
-
588
- With custom path:
589
- ```json
590
- {"type": "export_html", "outputPath": "/tmp/session.html"}
591
- ```
592
-
593
- Response:
594
- ```json
595
- {
596
- "type": "response",
597
- "command": "export_html",
598
- "success": true,
599
- "data": {"path": "/tmp/session.html"}
600
- }
601
- ```
602
-
603
- #### switch_session
604
-
605
- Load a different session file. Can be cancelled by a `session_before_switch` extension event handler.
606
-
607
- ```json
608
- {"type": "switch_session", "sessionPath": "/path/to/session.jsonl"}
609
- ```
610
-
611
- Response:
612
- ```json
613
- {"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": false}}
614
- ```
615
-
616
- If an extension cancelled the switch:
617
- ```json
618
- {"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": true}}
619
- ```
620
-
621
- #### fork
622
-
623
- Create a new fork from a previous user message on the active branch. Can be cancelled by a `session_before_fork` extension event handler. Returns the text of the message being forked from.
624
-
625
- ```json
626
- {"type": "fork", "entryId": "abc123"}
627
- ```
628
-
629
- Response:
630
- ```json
631
- {
632
- "type": "response",
633
- "command": "fork",
634
- "success": true,
635
- "data": {"text": "The original prompt text...", "cancelled": false}
636
- }
637
- ```
638
-
639
- If an extension cancelled the fork:
640
- ```json
641
- {
642
- "type": "response",
643
- "command": "fork",
644
- "success": true,
645
- "data": {"text": "The original prompt text...", "cancelled": true}
646
- }
647
- ```
648
-
649
- #### clone
650
-
651
- Duplicate the current active branch into a new session at the current position. Can be cancelled by a `session_before_fork` extension event handler.
652
-
653
- ```json
654
- {"type": "clone"}
655
- ```
656
-
657
- Response:
658
- ```json
659
- {
660
- "type": "response",
661
- "command": "clone",
662
- "success": true,
663
- "data": {"cancelled": false}
664
- }
665
- ```
666
-
667
- If an extension cancelled the clone:
668
- ```json
669
- {
670
- "type": "response",
671
- "command": "clone",
672
- "success": true,
673
- "data": {"cancelled": true}
674
- }
675
- ```
676
-
677
- #### get_fork_messages
678
-
679
- Get user messages available for forking.
680
-
681
- ```json
682
- {"type": "get_fork_messages"}
683
- ```
684
-
685
- Response:
686
- ```json
687
- {
688
- "type": "response",
689
- "command": "get_fork_messages",
690
- "success": true,
691
- "data": {
692
- "messages": [
693
- {"entryId": "abc123", "text": "First prompt..."},
694
- {"entryId": "def456", "text": "Second prompt..."}
695
- ]
696
- }
697
- }
698
- ```
699
-
700
- #### get_entries
701
-
702
- Get all session entries in append order (excluding the session header). The session is an append-only tree of entries with stable ids, so an entry id works as a durable cursor: pass the last entry id you have seen as `since` to get only entries strictly after it, even across client restarts. Unlike `get_messages`, this includes pre-compaction history and abandoned branches.
703
-
704
- ```json
705
- {"type": "get_entries"}
706
- ```
707
-
708
- With a cursor:
709
- ```json
710
- {"type": "get_entries", "since": "abc123"}
711
- ```
712
-
713
- Response:
714
- ```json
715
- {
716
- "type": "response",
717
- "command": "get_entries",
718
- "success": true,
719
- "data": {
720
- "entries": [
721
- {"type": "message", "id": "def456", "parentId": "abc123", "timestamp": "...", "message": {"role": "user", "...": "..."}}
722
- ],
723
- "leafId": "def456"
724
- }
725
- }
726
- ```
727
-
728
- `leafId` is the id of the current leaf entry (`null` for an empty session), so a client can tell in one round trip whether the active branch moved. If `since` does not match any entry id, the response is `success: false`.
729
-
730
- #### get_tree
731
-
732
- Get the session as a tree of entries. Each node is `{entry, children, label?, labelTimestamp?}`. A well-formed session has a single root; orphaned entries (broken parent chain) also appear as roots.
733
-
734
- ```json
735
- {"type": "get_tree"}
736
- ```
737
-
738
- Response:
739
- ```json
740
- {
741
- "type": "response",
742
- "command": "get_tree",
743
- "success": true,
744
- "data": {
745
- "tree": [
746
- {
747
- "entry": {"type": "message", "id": "abc123", "parentId": null, "...": "..."},
748
- "children": [
749
- {"entry": {"type": "message", "id": "def456", "parentId": "abc123", "...": "..."}, "children": []}
750
- ]
751
- }
752
- ],
753
- "leafId": "def456"
754
- }
755
- }
756
- ```
757
-
758
- #### get_last_assistant_text
759
-
760
- Get the text content of the last assistant message.
761
-
762
- ```json
763
- {"type": "get_last_assistant_text"}
764
- ```
765
-
766
- Response:
767
- ```json
768
- {
769
- "type": "response",
770
- "command": "get_last_assistant_text",
771
- "success": true,
772
- "data": {"text": "The assistant's response..."}
773
- }
774
- ```
775
-
776
- Returns `{"text": null}` if no assistant messages exist.
777
-
778
- #### set_session_name
779
-
780
- Set a display name for the current session. The name appears in session listings and helps identify sessions.
781
-
782
- ```json
783
- {"type": "set_session_name", "name": "my-feature-work"}
784
- ```
785
-
786
- Response:
787
- ```json
788
- {
789
- "type": "response",
790
- "command": "set_session_name",
791
- "success": true
792
- }
793
- ```
794
-
795
- The current session name is available via `get_state` in the `sessionName` field. To set the initial name when starting RPC mode, pass `--name <name>` or `-n <name>` to the `diffex --mode rpc` process.
796
-
797
- ### Commands
798
-
799
- #### get_commands
800
-
801
- Get available extension commands and prompt templates. These can be invoked via the `prompt` command by prefixing with `/`.
802
-
803
- ```json
804
- {"type": "get_commands"}
805
- ```
806
-
807
- Response:
808
- ```json
809
- {
810
- "type": "response",
811
- "command": "get_commands",
812
- "success": true,
813
- "data": {
814
- "commands": [
815
- {"name": "session-name", "description": "Set or clear session name", "source": "extension", "path": "/home/user/.diffex/agent/extensions/session.ts"},
816
- {"name": "fix-tests", "description": "Fix failing tests", "source": "prompt", "location": "project", "path": "/home/user/myproject/.diffex/agent/prompts/fix-tests.md"}
817
- ]
818
- }
819
- }
820
- ```
821
-
822
- Each command has:
823
- - `name`: Command name (invoke with `/name`)
824
- - `description`: Human-readable description (optional for extension commands)
825
- - `source`: What kind of command:
826
- - `"extension"`: Registered via `diffex.registerCommand()` in an extension
827
- - `"prompt"`: Loaded from a prompt template `.md` file
828
- - `location`: Where it was loaded from (optional, not present for extensions):
829
- - `"user"`: User-level (`~/.diffex/agent/`)
830
- - `"project"`: Project-level (`./.diffex/agent/`)
831
- - `"path"`: Explicit path via CLI or settings
832
- - `path`: Absolute file path to the command source (optional)
833
-
834
- **Note**: Built-in TUI commands (`/settings`, `/hotkeys`, etc.) are not included. They are handled only in interactive mode and would not execute if sent via `prompt`.
835
-
836
- ## Evolution and Harness Revisions
837
-
838
- Persisted CLI RPC sessions participate in invocation tracing and background evolution when `evolution.enabled` is enabled. The selected harness revision is refreshed at prompt admission, and explicit skill references use the same versioned expansion path as other modes.
839
-
840
- `/evolve` and `/version` are interactive-only controls. RPC currently has no commands to list, select, activate, or roll back harness revisions, and `get_state` does not expose the active revision. An RPC process therefore follows the globally selected compatible harness unless its embedded session was explicitly pinned through SDK composition.
841
-
842
- ## Events
843
-
844
- Events are streamed to stdout as JSON lines during agent operation. Events do not generally include an `id` field; `bash_execution_update` includes the `id` of its originating `bash` command when one was provided.
845
-
846
- ### Event Types
847
-
848
- | Event | Description |
849
- |-------|-------------|
850
- | `agent_start` | Agent begins processing |
851
- | `agent_end` | One low-level agent run completes (may still be followed by retry, compaction, or queued continuations) |
852
- | `agent_settled` | Agent run is fully settled; no automatic retry, compaction retry, or queued continuation remains |
853
- | `turn_start` | New turn begins |
854
- | `turn_end` | Turn completes (includes assistant message and tool results) |
855
- | `message_start` | Message begins |
856
- | `message_update` | Streaming update (text/thinking/toolcall deltas) |
857
- | `message_end` | Message completes |
858
- | `bash_execution_update` | Direct RPC bash command output chunk |
859
- | `tool_execution_start` | Tool begins execution |
860
- | `tool_execution_update` | Tool execution progress (streaming output) |
861
- | `tool_execution_end` | Tool completes |
862
- | `queue_update` | Pending steering/follow-up queue changed |
863
- | `subagent_wait_start` | Parent begins waiting for a frozen, name-sorted child batch |
864
- | `subagent_notice` | One child reaches a terminal state; contains deterministic safe metadata only |
865
- | `subagent_wait_end` | Frozen child batch wait ends or is cancelled |
866
- | `compaction_start` | Compaction begins |
867
- | `compaction_end` | Compaction completes |
868
- | `auto_retry_start` | Auto-retry begins (after transient error) |
869
- | `auto_retry_end` | Auto-retry completes (success or final failure) |
870
- | `summarization_retry_scheduled` | Retry scheduled for a transient compaction or branch-summary summarization error |
871
- | `summarization_retry_attempt_start` | Retried summarization request starts |
872
- | `summarization_retry_finished` | Summarization retry loop completes |
873
- | `extension_error` | Extension threw an error |
874
-
875
- ### agent_start
876
-
877
- Emitted when the agent begins processing a prompt.
878
-
879
- ```json
880
- {"type": "agent_start"}
881
- ```
882
-
883
- ### agent_end
884
-
885
- Emitted when one low-level agent run completes. Contains all messages generated during this run. If `willRetry` is true, an automatic retry will follow.
886
-
887
- ```json
888
- {
889
- "type": "agent_end",
890
- "messages": [...],
891
- "willRetry": false
892
- }
893
- ```
894
-
895
- ### agent_settled
896
-
897
- Emitted after the full session-level run settles.
898
- At this point Diffex will not continue automatically through retry, compaction retry, coordinated child delivery, or queued follow-up messages.
899
-
900
- ```json
901
- {"type": "agent_settled"}
902
- ```
903
-
904
- ### turn_start / turn_end
905
-
906
- A turn consists of one assistant response plus any resulting tool calls and results.
907
-
908
- ```json
909
- {"type": "turn_start"}
910
- ```
911
-
912
- ```json
913
- {
914
- "type": "turn_end",
915
- "message": {...},
916
- "toolResults": [...]
917
- }
918
- ```
919
-
920
- ### message_start / message_end
921
-
922
- Emitted when a message begins and completes. The `message` field contains an `AgentMessage`.
923
-
924
- ```json
925
- {"type": "message_start", "message": {...}}
926
- {"type": "message_end", "message": {...}}
927
- ```
928
-
929
- ### message_update (Streaming)
930
-
931
- Emitted during streaming of assistant messages. Contains a delta event without a cumulative message snapshot.
932
-
933
- ```json
934
- {
935
- "type": "message_update",
936
- "assistantMessageEvent": {
937
- "type": "text_delta",
938
- "contentIndex": 0,
939
- "delta": "Hello "
940
- }
941
- }
942
- ```
943
-
944
- The `assistantMessageEvent` field contains one of these delta types:
945
-
946
- | Type | Description |
947
- |------|-------------|
948
- | `text_start` | Text content block started |
949
- | `text_delta` | Text content chunk |
950
- | `text_end` | Text content block ended |
951
- | `thinking_start` | Thinking block started |
952
- | `thinking_delta` | Thinking content chunk |
953
- | `thinking_end` | Thinking block ended |
954
- | `toolcall_start` | Tool call started |
955
- | `toolcall_delta` | Tool call arguments chunk |
956
- | `toolcall_end` | Tool call ended (includes full `toolCall` object) |
957
-
958
- Example streaming a text response:
959
- ```json
960
- {"type":"message_update","assistantMessageEvent":{"type":"text_start","contentIndex":0}}
961
- {"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
962
- {"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":" world"}}
963
- {"type":"message_update","assistantMessageEvent":{"type":"text_end","contentIndex":0,"content":"Hello world"}}
964
- ```
965
-
966
- `message_update` intentionally omits the former cumulative `message` field and
967
- `assistantMessageEvent.partial`. Clients that need a live partial message must assemble it
968
- from `message_start` and subsequent events using `contentIndex`. Treat `message_end.message`
969
- as authoritative. For tool calls, buffer `toolcall_delta.delta`; `toolcall_end.toolCall`
970
- contains the completed call.
971
-
972
- ### bash_execution_update
973
-
974
- Emitted once for each output chunk from a direct `bash` command. `id` matches the command's `id`, allowing clients to associate output with the correct command.
975
-
976
- Events stream all output while the command runs, even if the final `bash` response's `output` is truncated.
977
-
978
- ```json
979
- {
980
- "type": "bash_execution_update",
981
- "id": "req-1",
982
- "delta": "total 48\n"
983
- }
984
- ```
985
-
986
- ### tool_execution_start / tool_execution_update / tool_execution_end
987
-
988
- Emitted when a tool begins, streams progress, and completes execution.
989
-
990
- ```json
991
- {
992
- "type": "tool_execution_start",
993
- "toolCallId": "call_abc123",
994
- "toolName": "bash",
995
- "args": {"command": "ls -la"}
996
- }
997
- ```
998
-
999
- During execution, `tool_execution_update` events stream partial results (e.g., bash output as it arrives):
1000
-
1001
- ```json
1002
- {
1003
- "type": "tool_execution_update",
1004
- "toolCallId": "call_abc123",
1005
- "toolName": "bash",
1006
- "args": {"command": "ls -la"},
1007
- "partialResult": {
1008
- "content": [{"type": "text", "text": "partial output so far..."}],
1009
- "details": {"truncation": null, "fullOutputPath": null}
1010
- }
1011
- }
1012
- ```
1013
-
1014
- When complete:
1015
-
1016
- ```json
1017
- {
1018
- "type": "tool_execution_end",
1019
- "toolCallId": "call_abc123",
1020
- "toolName": "bash",
1021
- "result": {
1022
- "content": [{"type": "text", "text": "total 48\n..."}],
1023
- "details": {...}
1024
- },
1025
- "isError": false
1026
- }
1027
- ```
1028
-
1029
- Use `toolCallId` to correlate events. The `partialResult` in `tool_execution_update` contains the accumulated output so far (not just the delta), allowing clients to simply replace their display on each update.
1030
-
1031
- ### queue_update
1032
-
1033
- Emitted whenever the pending steering or follow-up queue changes.
1034
-
1035
- ```json
1036
- {
1037
- "type": "queue_update",
1038
- "steering": ["Focus on error handling"],
1039
- "followUp": ["After that, summarize the result"]
1040
- }
1041
- ```
1042
-
1043
- ### subagent_wait_start / subagent_notice / subagent_wait_end
1044
-
1045
- When a parent assistant run ends with unconsumed children spawned through parent tool calls, RPC mode emits `subagent_wait_start` with the frozen, name-sorted batch:
1046
-
1047
- ```json
1048
- {
1049
- "type": "subagent_wait_start",
1050
- "names": ["alpha", "beta"]
1051
- }
1052
- ```
1053
-
1054
- Each child emits one `subagent_notice` when its current attempt reaches a terminal state:
1055
-
1056
- ```json
1057
- {
1058
- "type": "subagent_notice",
1059
- "name": "beta",
1060
- "status": "idle",
1061
- "attempt": "initial",
1062
- "retryAvailable": false,
1063
- "text": "beta has finished execution."
1064
- }
1065
- ```
1066
-
1067
- Notice text is deterministic:
1068
-
1069
- | Condition | Text |
1070
- |-----------|------|
1071
- | Successful completion | `<name> has finished execution.` |
1072
- | Initial failure with a retry available | `<name> failed and a retry is being planned.` |
1073
- | Failure after the coordinated retry | `<name> failed after one retry.` |
1074
- | Interruption | `<name> was interrupted.` |
1075
-
1076
- Notice events never contain child results, partial output, or errors.
1077
- They are not added to agent messages, persisted as session entries, or included in provider context.
1078
-
1079
- After every child is terminal, RPC mode emits the wait end event:
1080
-
1081
- ```json
1082
- {
1083
- "type": "subagent_wait_end",
1084
- "names": ["alpha", "beta"],
1085
- "cancelled": false
1086
- }
1087
- ```
1088
-
1089
- Diffex then supplies one hidden, non-displayed context message to the parent with name-sorted child results, partial output, errors, and retry availability.
1090
- That payload is model context, not a result-bearing session event.
1091
- The parent continues automatically, and a later `agent_settled` marks completion.
1092
-
1093
- Terminal child results explicitly returned by the `agents` tool are consumed and excluded from automatic delivery.
1094
- An initial failure offers one corrective wake through `agent_action` per child for the current parent prompt cycle.
1095
- A second retry in the same cycle is rejected, while a later explicit user prompt starts a fresh cycle.
1096
- The parent can decline a retry and settle normally.
1097
-
1098
- ### compaction_start / compaction_end
1099
-
1100
- Emitted when compaction runs, whether manual or automatic.
1101
-
1102
- ```json
1103
- {"type": "compaction_start", "reason": "threshold"}
1104
- ```
1105
-
1106
- The `reason` field is `"manual"`, `"threshold"`, or `"overflow"`.
1107
-
1108
- ```json
1109
- {
1110
- "type": "compaction_end",
1111
- "reason": "threshold",
1112
- "result": {
1113
- "summary": "Summary of conversation...",
1114
- "firstKeptEntryId": "abc123",
1115
- "tokensBefore": 150000,
1116
- "estimatedTokensAfter": 32000,
1117
- "usage": {
1118
- "input": 32000,
1119
- "output": 1200,
1120
- "cacheRead": 0,
1121
- "cacheWrite": 0,
1122
- "totalTokens": 33200,
1123
- "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}
1124
- },
1125
- "details": {}
1126
- },
1127
- "aborted": false,
1128
- "willRetry": false
1129
- }
1130
- ```
1131
-
1132
- If `reason` was `"overflow"` and compaction succeeds, `willRetry` is `true` and the agent will automatically retry the prompt.
1133
-
1134
- If compaction was aborted, `result` is `null` and `aborted` is `true`.
1135
-
1136
- If compaction failed (e.g., API quota exceeded), `result` is `null`, `aborted` is `false`, and `errorMessage` contains the error description.
1137
-
1138
- ### auto_retry_start / auto_retry_end
1139
-
1140
- Emitted when automatic retry is triggered after a transient error (overloaded, rate limit, 5xx).
1141
-
1142
- ```json
1143
- {
1144
- "type": "auto_retry_start",
1145
- "attempt": 1,
1146
- "maxAttempts": 3,
1147
- "delayMs": 2000,
1148
- "errorMessage": "529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}"
1149
- }
1150
- ```
1151
-
1152
- ```json
1153
- {
1154
- "type": "auto_retry_end",
1155
- "success": true,
1156
- "attempt": 2
1157
- }
1158
- ```
1159
-
1160
- On final failure (max retries exceeded):
1161
- ```json
1162
- {
1163
- "type": "auto_retry_end",
1164
- "success": false,
1165
- "attempt": 3,
1166
- "finalError": "529 overloaded_error: Overloaded"
1167
- }
1168
- ```
1169
-
1170
- ### summarization_retry_scheduled / summarization_retry_attempt_start / summarization_retry_finished
1171
-
1172
- Emitted when compaction or branch-summary summarization retries after a transient provider error. These events use the same retry settings as automatic assistant-turn retries.
1173
-
1174
- ```json
1175
- {
1176
- "type": "summarization_retry_scheduled",
1177
- "attempt": 1,
1178
- "maxAttempts": 3,
1179
- "delayMs": 2000,
1180
- "errorMessage": "terminated"
1181
- }
1182
- ```
1183
-
1184
- ```json
1185
- {
1186
- "type": "summarization_retry_attempt_start",
1187
- "source": "compaction",
1188
- "reason": "threshold"
1189
- }
1190
- ```
1191
-
1192
- For branch summaries, `source` is `"branchSummary"` and no `reason` is present.
1193
-
1194
- ```json
1195
- {
1196
- "type": "summarization_retry_finished"
1197
- }
1198
- ```
1199
-
1200
- ### extension_error
1201
-
1202
- Emitted when an extension throws an error.
1203
-
1204
- ```json
1205
- {
1206
- "type": "extension_error",
1207
- "extensionPath": "/path/to/extension.ts",
1208
- "event": "tool_call",
1209
- "error": "Error message..."
1210
- }
1211
- ```
1212
-
1213
- ## Extension UI Protocol
1214
-
1215
- Extensions can request user interaction via `ctx.ui.select()`, `ctx.ui.confirm()`, etc. In RPC mode, these are translated into a request/response sub-protocol on top of the base command/event flow.
1216
-
1217
- There are two categories of extension UI methods:
1218
-
1219
- - **Dialog methods** (`select`, `confirm`, `input`, `editor`): emit an `extension_ui_request` on stdout and block until the client sends back an `extension_ui_response` on stdin with the matching `id`.
1220
- - **Fire-and-forget methods** (`notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`): emit an `extension_ui_request` on stdout but do not expect a response. The client can display the information or ignore it.
1221
-
1222
- If a dialog method includes a `timeout` field, the agent-side will auto-resolve with a default value when the timeout expires. The client does not need to track timeouts.
1223
-
1224
- Some `ExtensionUIContext` methods are not supported or degraded in RPC mode because they require direct TUI access:
1225
- - `custom()` returns `undefined`
1226
- - `setWorkingMessage()`, `setWorkingIndicator()`, `setFooter()`, `setHeader()`, `setEditorComponent()`, `setToolsExpanded()` are no-ops
1227
- - `getEditorText()` returns `""`
1228
- - `getToolsExpanded()` returns `false`
1229
- - `pasteToEditor()` delegates to `setEditorText()` (no paste/collapse handling)
1230
- - `getAllThemes()` returns `[]`
1231
- - `getTheme()` returns `undefined`
1232
- - `setTheme()` returns `{ success: false, error: "..." }`
1233
-
1234
- Note: `ctx.mode` is `"rpc"` and `ctx.hasUI` is `true` in RPC mode because the dialog and fire-and-forget methods are functional via the extension UI sub-protocol. Use `ctx.mode === "tui"` to guard TUI-specific features like `custom()` that require a real terminal.
1235
-
1236
- ### Extension UI Requests (stdout)
1237
-
1238
- All requests have `type: "extension_ui_request"`, a unique `id`, and a `method` field.
1239
-
1240
- #### select
1241
-
1242
- Prompt the user to choose from a list. Dialog methods with a `timeout` field include the timeout in milliseconds; the agent auto-resolves with `undefined` if the client doesn't respond in time.
1243
-
1244
- ```json
1245
- {
1246
- "type": "extension_ui_request",
1247
- "id": "uuid-1",
1248
- "method": "select",
1249
- "title": "Allow dangerous command?",
1250
- "options": ["Allow", "Block"],
1251
- "timeout": 10000
1252
- }
1253
- ```
1254
-
1255
- Expected response: `extension_ui_response` with `value` (the selected option string) or `cancelled: true`.
1256
-
1257
- #### confirm
1258
-
1259
- Prompt the user for yes/no confirmation.
1260
-
1261
- ```json
1262
- {
1263
- "type": "extension_ui_request",
1264
- "id": "uuid-2",
1265
- "method": "confirm",
1266
- "title": "Clear session?",
1267
- "message": "All messages will be lost.",
1268
- "timeout": 5000
1269
- }
1270
- ```
1271
-
1272
- Expected response: `extension_ui_response` with `confirmed: true/false` or `cancelled: true`.
1273
-
1274
- #### input
1275
-
1276
- Prompt the user for free-form text.
1277
-
1278
- ```json
1279
- {
1280
- "type": "extension_ui_request",
1281
- "id": "uuid-3",
1282
- "method": "input",
1283
- "title": "Enter a value",
1284
- "placeholder": "type something..."
1285
- }
1286
- ```
1287
-
1288
- Expected response: `extension_ui_response` with `value` (the entered text) or `cancelled: true`.
1289
-
1290
- #### editor
1291
-
1292
- Open a multi-line text editor with optional prefilled content.
1293
-
1294
- ```json
1295
- {
1296
- "type": "extension_ui_request",
1297
- "id": "uuid-4",
1298
- "method": "editor",
1299
- "title": "Edit some text",
1300
- "prefill": "Line 1\nLine 2\nLine 3"
1301
- }
1302
- ```
1303
-
1304
- Expected response: `extension_ui_response` with `value` (the edited text) or `cancelled: true`.
1305
-
1306
- #### notify
1307
-
1308
- Display a notification. Fire-and-forget, no response expected.
1309
-
1310
- ```json
1311
- {
1312
- "type": "extension_ui_request",
1313
- "id": "uuid-5",
1314
- "method": "notify",
1315
- "message": "Command blocked by user",
1316
- "notifyType": "warning"
1317
- }
1318
- ```
1319
-
1320
- The `notifyType` field is `"info"`, `"warning"`, or `"error"`. Defaults to `"info"` if omitted.
1321
-
1322
- #### setStatus
1323
-
1324
- Set or clear a status entry in the footer/status bar. Fire-and-forget.
1325
-
1326
- ```json
1327
- {
1328
- "type": "extension_ui_request",
1329
- "id": "uuid-6",
1330
- "method": "setStatus",
1331
- "statusKey": "my-ext",
1332
- "statusText": "Turn 3 running..."
1333
- }
1334
- ```
1335
-
1336
- Send `statusText: undefined` (or omit it) to clear the status entry for that key.
1337
-
1338
- #### setWidget
1339
-
1340
- Set or clear a widget (block of text lines) displayed above or below the editor. Fire-and-forget.
1341
-
1342
- ```json
1343
- {
1344
- "type": "extension_ui_request",
1345
- "id": "uuid-7",
1346
- "method": "setWidget",
1347
- "widgetKey": "my-ext",
1348
- "widgetLines": ["--- My Widget ---", "Line 1", "Line 2"],
1349
- "widgetPlacement": "aboveEditor"
1350
- }
1351
- ```
1352
-
1353
- Send `widgetLines: undefined` (or omit it) to clear the widget. The `widgetPlacement` field is `"aboveEditor"` (default) or `"belowEditor"`. Only string arrays are supported in RPC mode; component factories are ignored.
1354
-
1355
- #### setTitle
1356
-
1357
- Set the terminal window/tab title. Fire-and-forget.
1358
-
1359
- ```json
1360
- {
1361
- "type": "extension_ui_request",
1362
- "id": "uuid-8",
1363
- "method": "setTitle",
1364
- "title": "Diffex - my project"
1365
- }
1366
- ```
1367
-
1368
- #### set_editor_text
1369
-
1370
- Set the text in the input editor. Fire-and-forget.
1371
-
1372
- ```json
1373
- {
1374
- "type": "extension_ui_request",
1375
- "id": "uuid-9",
1376
- "method": "set_editor_text",
1377
- "text": "prefilled text for the user"
1378
- }
1379
- ```
1380
-
1381
- ### Extension UI Responses (stdin)
1382
-
1383
- Responses are sent for dialog methods only (`select`, `confirm`, `input`, `editor`). The `id` must match the request.
1384
-
1385
- #### Value response (select, input, editor)
1386
-
1387
- ```json
1388
- {"type": "extension_ui_response", "id": "uuid-1", "value": "Allow"}
1389
- ```
1390
-
1391
- #### Confirmation response (confirm)
1392
-
1393
- ```json
1394
- {"type": "extension_ui_response", "id": "uuid-2", "confirmed": true}
1395
- ```
1396
-
1397
- #### Cancellation response (any dialog)
1398
-
1399
- Dismiss any dialog method. The extension receives `undefined` (for select/input/editor) or `false` (for confirm).
1400
-
1401
- ```json
1402
- {"type": "extension_ui_response", "id": "uuid-3", "cancelled": true}
1403
- ```
1404
-
1405
- ## Error Handling
1406
-
1407
- Failed commands return a response with `success: false`:
1408
-
1409
- ```json
1410
- {
1411
- "type": "response",
1412
- "command": "set_model",
1413
- "success": false,
1414
- "error": "Model not found: invalid/model"
1415
- }
1416
- ```
1417
-
1418
- Parse errors:
1419
-
1420
- ```json
1421
- {
1422
- "type": "response",
1423
- "command": "parse",
1424
- "success": false,
1425
- "error": "Failed to parse command: Unexpected token..."
1426
- }
1427
- ```
1428
-
1429
- ## Types
1430
-
1431
- Source files:
1432
- - [`packages/ai/src/types.ts`](../../ai/src/types.ts) - `Model`, `UserMessage`, `AssistantMessage`, `ToolResultMessage`
1433
- - [`packages/agent/src/types.ts`](../../agent/src/types.ts) - `AgentMessage`, `AgentEvent`
1434
- - [`src/core/messages.ts`](../src/core/messages.ts) - `BashExecutionMessage`
1435
- - [`src/modes/json-event.ts`](../src/modes/json-event.ts) - `JsonAgentSessionEvent`
1436
- - [`src/modes/rpc/rpc-types.ts`](../src/modes/rpc/rpc-types.ts) - RPC command/response types, extension UI request/response types
1437
-
1438
- ### Model
1439
-
1440
- ```json
1441
- {
1442
- "id": "claude-sonnet-4-20250514",
1443
- "name": "Claude Sonnet 4",
1444
- "api": "anthropic-messages",
1445
- "provider": "anthropic",
1446
- "baseUrl": "https://api.anthropic.com",
1447
- "reasoning": true,
1448
- "input": ["text", "image"],
1449
- "contextWindow": 200000,
1450
- "maxTokens": 16384,
1451
- "cost": {
1452
- "input": 3.0,
1453
- "output": 15.0,
1454
- "cacheRead": 0.3,
1455
- "cacheWrite": 3.75
1456
- }
1457
- }
1458
- ```
1459
-
1460
- ### UserMessage
1461
-
1462
- ```json
1463
- {
1464
- "role": "user",
1465
- "content": "Hello!",
1466
- "timestamp": 1733234567890,
1467
- "attachments": []
1468
- }
1469
- ```
1470
-
1471
- The `content` field can be a string or an array of `TextContent`/`ImageContent` blocks.
1472
-
1473
- ### AssistantMessage
1474
-
1475
- ```json
1476
- {
1477
- "role": "assistant",
1478
- "content": [
1479
- {"type": "text", "text": "Hello! How can I help?"},
1480
- {"type": "thinking", "thinking": "User is greeting me..."},
1481
- {"type": "toolCall", "id": "call_123", "name": "bash", "arguments": {"command": "ls"}}
1482
- ],
1483
- "api": "anthropic-messages",
1484
- "provider": "anthropic",
1485
- "model": "claude-sonnet-4-20250514",
1486
- "usage": {
1487
- "input": 100,
1488
- "output": 50,
1489
- "cacheRead": 0,
1490
- "cacheWrite": 0,
1491
- "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105}
1492
- },
1493
- "stopReason": "stop",
1494
- "timestamp": 1733234567890
1495
- }
1496
- ```
1497
-
1498
- Stop reasons: `"stop"`, `"length"`, `"toolUse"`, `"error"`, `"aborted"`
1499
-
1500
- ### ToolResultMessage
1501
-
1502
- ```json
1503
- {
1504
- "role": "toolResult",
1505
- "toolCallId": "call_123",
1506
- "toolName": "bash",
1507
- "content": [{"type": "text", "text": "total 48\ndrwxr-xr-x ..."}],
1508
- "usage": {
1509
- "input": 100,
1510
- "output": 50,
1511
- "cacheRead": 0,
1512
- "cacheWrite": 0,
1513
- "totalTokens": 150,
1514
- "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105}
1515
- },
1516
- "isError": false,
1517
- "timestamp": 1733234567890
1518
- }
1519
- ```
1520
-
1521
- `usage` is optional and reports nested LLM work performed by the tool. When present, it contributes to session token and cost totals.
1522
-
1523
- ### BashExecutionMessage
1524
-
1525
- Created by the `bash` RPC command (not by LLM tool calls):
1526
-
1527
- ```json
1528
- {
1529
- "role": "bashExecution",
1530
- "command": "ls -la",
1531
- "output": "total 48\ndrwxr-xr-x ...",
1532
- "exitCode": 0,
1533
- "cancelled": false,
1534
- "truncated": false,
1535
- "fullOutputPath": null,
1536
- "timestamp": 1733234567890
1537
- }
1538
- ```
1539
-
1540
- ### Attachment
1541
-
1542
- ```json
1543
- {
1544
- "id": "img1",
1545
- "type": "image",
1546
- "fileName": "photo.jpg",
1547
- "mimeType": "image/jpeg",
1548
- "size": 102400,
1549
- "content": "base64-encoded-data...",
1550
- "extractedText": null,
1551
- "preview": null
1552
- }
1553
- ```
1554
-
1555
- ## Example: Basic Client (Python)
1556
-
1557
- ```python
1558
- import subprocess
1559
- import json
1560
-
1561
- proc = subprocess.Popen(
1562
- ["diffex", "--mode", "rpc", "--no-session"],
1563
- stdin=subprocess.PIPE,
1564
- stdout=subprocess.PIPE,
1565
- text=True
1566
- )
1567
-
1568
- def send(cmd):
1569
- proc.stdin.write(json.dumps(cmd) + "\n")
1570
- proc.stdin.flush()
1571
-
1572
- def read_events():
1573
- for line in proc.stdout:
1574
- yield json.loads(line)
1575
-
1576
- # Send prompt
1577
- send({"type": "prompt", "message": "Hello!"})
1578
-
1579
- # Process events
1580
- for event in read_events():
1581
- if event.get("type") == "message_update":
1582
- delta = event.get("assistantMessageEvent", {})
1583
- if delta.get("type") == "text_delta":
1584
- print(delta["delta"], end="", flush=True)
1585
-
1586
- if event.get("type") == "agent_end":
1587
- print()
1588
- break
1589
- ```
1590
-
1591
- ## Example: Interactive Client (Node.js)
1592
-
1593
- See [`test/rpc-example.ts`](../test/rpc-example.ts) for a complete interactive example, or [`src/modes/rpc/rpc-client.ts`](../src/modes/rpc/rpc-client.ts) for a typed client implementation.
1594
-
1595
- For a complete example of handling the extension UI protocol, see [`examples/rpc-extension-ui.ts`](../examples/rpc-extension-ui.ts) which pairs with the [`examples/extensions/rpc-demo.ts`](../examples/extensions/rpc-demo.ts) extension.
1596
-
1597
- ```javascript
1598
- const { spawn } = require("child_process");
1599
- const { StringDecoder } = require("string_decoder");
1600
-
1601
- const agent = spawn("diffex", ["--mode", "rpc", "--no-session"]);
1602
-
1603
- function attachJsonlReader(stream, onLine) {
1604
- const decoder = new StringDecoder("utf8");
1605
- let buffer = "";
1606
-
1607
- stream.on("data", (chunk) => {
1608
- buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
1609
-
1610
- while (true) {
1611
- const newlineIndex = buffer.indexOf("\n");
1612
- if (newlineIndex === -1) break;
1613
-
1614
- let line = buffer.slice(0, newlineIndex);
1615
- buffer = buffer.slice(newlineIndex + 1);
1616
- if (line.endsWith("\r")) line = line.slice(0, -1);
1617
- onLine(line);
1618
- }
1619
- });
1620
-
1621
- stream.on("end", () => {
1622
- buffer += decoder.end();
1623
- if (buffer.length > 0) {
1624
- onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
1625
- }
1626
- });
1627
- }
1628
-
1629
- attachJsonlReader(agent.stdout, (line) => {
1630
- const event = JSON.parse(line);
1631
-
1632
- if (event.type === "message_update") {
1633
- const { assistantMessageEvent } = event;
1634
- if (assistantMessageEvent.type === "text_delta") {
1635
- process.stdout.write(assistantMessageEvent.delta);
1636
- }
1637
- }
1638
- });
1639
-
1640
- // Send prompt
1641
- agent.stdin.write(JSON.stringify({ type: "prompt", message: "Hello" }) + "\n");
1642
-
1643
- // Abort on Ctrl+C
1644
- process.on("SIGINT", () => {
1645
- agent.stdin.write(JSON.stringify({ type: "abort" }) + "\n");
1646
- });
1647
- ```