shortcutxl 0.2.12 → 0.2.13

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 (110) hide show
  1. package/README.md +26 -26
  2. package/agent-docs/README.md +397 -397
  3. package/agent-docs/docs/compaction.md +390 -390
  4. package/agent-docs/docs/custom-provider.md +580 -580
  5. package/agent-docs/docs/extensions.md +1971 -1971
  6. package/agent-docs/docs/packages.md +209 -209
  7. package/agent-docs/docs/rpc.md +1317 -1317
  8. package/agent-docs/docs/sdk.md +962 -962
  9. package/agent-docs/docs/session.md +412 -412
  10. package/agent-docs/docs/termux.md +127 -127
  11. package/agent-docs/docs/tui.md +887 -887
  12. package/agent-docs/examples/README.md +25 -25
  13. package/agent-docs/examples/extensions/README.md +205 -205
  14. package/agent-docs/examples/extensions/antigravity-image-gen.ts +447 -447
  15. package/agent-docs/examples/extensions/auto-commit-on-exit.ts +49 -49
  16. package/agent-docs/examples/extensions/bash-spawn-hook.ts +30 -30
  17. package/agent-docs/examples/extensions/bookmark.ts +50 -50
  18. package/agent-docs/examples/extensions/built-in-tool-renderer.ts +256 -256
  19. package/agent-docs/examples/extensions/claude-rules.ts +86 -86
  20. package/agent-docs/examples/extensions/commands.ts +75 -75
  21. package/agent-docs/examples/extensions/confirm-destructive.ts +59 -59
  22. package/agent-docs/examples/extensions/custom-compaction.ts +126 -126
  23. package/agent-docs/examples/extensions/custom-footer.ts +63 -63
  24. package/agent-docs/examples/extensions/custom-header.ts +73 -73
  25. package/agent-docs/examples/extensions/custom-provider-anthropic/index.ts +660 -660
  26. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/index.ts +362 -362
  27. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/test.ts +88 -88
  28. package/agent-docs/examples/extensions/custom-provider-qwen-cli/index.ts +349 -349
  29. package/agent-docs/examples/extensions/dirty-repo-guard.ts +56 -56
  30. package/agent-docs/examples/extensions/doom-overlay/doom-component.ts +133 -133
  31. package/agent-docs/examples/extensions/doom-overlay/doom-keys.ts +108 -108
  32. package/agent-docs/examples/extensions/doom-overlay/index.ts +74 -74
  33. package/agent-docs/examples/extensions/dynamic-resources/index.ts +15 -15
  34. package/agent-docs/examples/extensions/dynamic-tools.ts +77 -77
  35. package/agent-docs/examples/extensions/event-bus.ts +43 -43
  36. package/agent-docs/examples/extensions/file-trigger.ts +41 -41
  37. package/agent-docs/examples/extensions/git-checkpoint.ts +53 -53
  38. package/agent-docs/examples/extensions/handoff.ts +155 -155
  39. package/agent-docs/examples/extensions/hello.ts +25 -25
  40. package/agent-docs/examples/extensions/inline-bash.ts +94 -94
  41. package/agent-docs/examples/extensions/input-transform.ts +43 -43
  42. package/agent-docs/examples/extensions/interactive-shell.ts +209 -209
  43. package/agent-docs/examples/extensions/mac-system-theme.ts +47 -47
  44. package/agent-docs/examples/extensions/message-renderer.ts +59 -59
  45. package/agent-docs/examples/extensions/minimal-mode.ts +430 -430
  46. package/agent-docs/examples/extensions/modal-editor.ts +90 -90
  47. package/agent-docs/examples/extensions/model-status.ts +31 -31
  48. package/agent-docs/examples/extensions/notify.ts +55 -55
  49. package/agent-docs/examples/extensions/overlay-qa-tests.ts +936 -936
  50. package/agent-docs/examples/extensions/overlay-test.ts +159 -159
  51. package/agent-docs/examples/extensions/permission-gate.ts +37 -37
  52. package/agent-docs/examples/extensions/pirate.ts +47 -47
  53. package/agent-docs/examples/extensions/plan-mode/index.ts +363 -363
  54. package/agent-docs/examples/extensions/preset.ts +418 -418
  55. package/agent-docs/examples/extensions/protected-paths.ts +30 -30
  56. package/agent-docs/examples/extensions/qna.ts +122 -122
  57. package/agent-docs/examples/extensions/question.ts +278 -278
  58. package/agent-docs/examples/extensions/questionnaire.ts +440 -440
  59. package/agent-docs/examples/extensions/rainbow-editor.ts +90 -90
  60. package/agent-docs/examples/extensions/reload-runtime.ts +37 -37
  61. package/agent-docs/examples/extensions/rpc-demo.ts +124 -124
  62. package/agent-docs/examples/extensions/sandbox/index.ts +324 -324
  63. package/agent-docs/examples/extensions/send-user-message.ts +97 -97
  64. package/agent-docs/examples/extensions/session-name.ts +27 -27
  65. package/agent-docs/examples/extensions/shutdown-command.ts +69 -69
  66. package/agent-docs/examples/extensions/snake.ts +343 -343
  67. package/agent-docs/examples/extensions/space-invaders.ts +566 -566
  68. package/agent-docs/examples/extensions/ssh.ts +233 -233
  69. package/agent-docs/examples/extensions/status-line.ts +40 -40
  70. package/agent-docs/examples/extensions/subagent/agents.ts +130 -130
  71. package/agent-docs/examples/extensions/subagent/index.ts +1068 -1068
  72. package/agent-docs/examples/extensions/summarize.ts +206 -206
  73. package/agent-docs/examples/extensions/system-prompt-header.ts +17 -17
  74. package/agent-docs/examples/extensions/timed-confirm.ts +72 -72
  75. package/agent-docs/examples/extensions/titlebar-spinner.ts +58 -58
  76. package/agent-docs/examples/extensions/todo.ts +314 -314
  77. package/agent-docs/examples/extensions/tool-override.ts +146 -146
  78. package/agent-docs/examples/extensions/tools.ts +145 -145
  79. package/agent-docs/examples/extensions/trigger-compact.ts +40 -40
  80. package/agent-docs/examples/extensions/truncated-tool.ts +194 -194
  81. package/agent-docs/examples/extensions/widget-placement.ts +17 -17
  82. package/agent-docs/examples/extensions/with-deps/index.ts +37 -37
  83. package/agent-docs/examples/rpc-extension-ui.ts +654 -654
  84. package/agent-docs/examples/sdk/01-minimal.ts +22 -22
  85. package/agent-docs/examples/sdk/02-custom-model.ts +48 -48
  86. package/agent-docs/examples/sdk/03-custom-prompt.ts +55 -55
  87. package/agent-docs/examples/sdk/04-skills.ts +53 -53
  88. package/agent-docs/examples/sdk/05-tools.ts +56 -56
  89. package/agent-docs/examples/sdk/06-extensions.ts +88 -88
  90. package/agent-docs/examples/sdk/07-context-files.ts +40 -40
  91. package/agent-docs/examples/sdk/08-prompt-templates.ts +47 -47
  92. package/agent-docs/examples/sdk/09-api-keys-and-oauth.ts +48 -48
  93. package/agent-docs/examples/sdk/10-settings.ts +54 -54
  94. package/agent-docs/examples/sdk/11-sessions.ts +48 -48
  95. package/agent-docs/examples/sdk/12-full-control.ts +82 -82
  96. package/agent-docs/examples/sdk/README.md +144 -144
  97. package/agent-docs/xll-spec.md +110 -110
  98. package/dist/core/auth-storage.js +21 -2
  99. package/package.json +1 -1
  100. package/xll/ShortcutXL.xll +0 -0
  101. package/xll/modules/debug_render.py +272 -272
  102. package/xll/modules/gameboy.py +241 -241
  103. package/xll/modules/pong.py +188 -188
  104. package/xll/modules/shortcut_xl/_diff_highlight.py +176 -0
  105. package/xll/modules/shortcut_xl/_log.py +12 -12
  106. package/xll/modules/shortcut_xl/_registry.py +44 -44
  107. package/xll/modules/stocks.py +100 -100
  108. /package/skills/{com-advanced-api → COM-advanced-api}/SKILL.md +0 -0
  109. /package/skills/{com-advanced-api → COM-advanced-api}/excel-type-library.py +0 -0
  110. /package/skills/{com-advanced-api → COM-advanced-api}/office-type-library.py +0 -0
@@ -1,962 +1,962 @@
1
- > Shortcut can help you use the SDK. Ask it to build an integration for your use case.
2
-
3
- # SDK
4
-
5
- The SDK provides programmatic access to Shortcut's agent capabilities. Use it to embed Shortcut in other applications, build custom interfaces, or integrate with automated workflows.
6
-
7
- **Example use cases:**
8
- - Build a custom UI (web, desktop, mobile)
9
- - Integrate agent capabilities into existing applications
10
- - Create automated pipelines with agent reasoning
11
- - Build custom tools that spawn sub-agents
12
- - Test agent behavior programmatically
13
-
14
- See [examples/sdk/](../examples/sdk/) for working examples from minimal to full control.
15
-
16
- ## Quick Start
17
-
18
- ```typescript
19
- import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "shortcutxl";
20
-
21
- // Set up credential storage and model registry
22
- const authStorage = AuthStorage.create();
23
- const modelRegistry = new ModelRegistry(authStorage);
24
-
25
- const { session } = await createAgentSession({
26
- sessionManager: SessionManager.inMemory(),
27
- authStorage,
28
- modelRegistry,
29
- });
30
-
31
- session.subscribe((event) => {
32
- if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
33
- process.stdout.write(event.assistantMessageEvent.delta);
34
- }
35
- });
36
-
37
- await session.prompt("What files are in the current directory?");
38
- ```
39
-
40
- ## Installation
41
-
42
- ```bash
43
- npm install shortcutxl
44
- ```
45
-
46
- The SDK is included in the main package. No separate installation needed.
47
-
48
- ## Core Concepts
49
-
50
- ### createAgentSession()
51
-
52
- The main factory function. Creates an `AgentSession` with configurable options.
53
-
54
- `createAgentSession()` uses a `ResourceLoader` to supply extensions, skills, prompt templates, themes, and context files. If you do not provide one, it uses `DefaultResourceLoader` with standard discovery.
55
-
56
- ```typescript
57
- import { createAgentSession } from "shortcutxl";
58
-
59
- // Minimal: defaults with DefaultResourceLoader
60
- const { session } = await createAgentSession();
61
-
62
- // Custom: override specific options
63
- const { session } = await createAgentSession({
64
- model: myModel,
65
- tools: [readTool, bashTool],
66
- sessionManager: SessionManager.inMemory(),
67
- });
68
- ```
69
-
70
- ### AgentSession
71
-
72
- The session manages the agent lifecycle, message history, and event streaming.
73
-
74
- ```typescript
75
- interface AgentSession {
76
- // Send a prompt and wait for completion
77
- // If streaming, requires streamingBehavior option to queue the message
78
- prompt(text: string, options?: PromptOptions): Promise<void>;
79
-
80
- // Queue messages during streaming
81
- steer(text: string): Promise<void>; // Interrupt: delivered after current tool, skips remaining
82
- followUp(text: string): Promise<void>; // Wait: delivered only when agent finishes
83
-
84
- // Subscribe to events (returns unsubscribe function)
85
- subscribe(listener: (event: AgentSessionEvent) => void): () => void;
86
-
87
- // Session info
88
- sessionFile: string | undefined; // undefined for in-memory
89
- sessionId: string;
90
-
91
- // Model control
92
- setModel(model: Model): Promise<void>;
93
- setThinkingLevel(level: ThinkingLevel): void;
94
- cycleModel(): Promise<ModelCycleResult | undefined>;
95
- cycleThinkingLevel(): ThinkingLevel | undefined;
96
-
97
- // State access
98
- agent: Agent;
99
- model: Model | undefined;
100
- thinkingLevel: ThinkingLevel;
101
- messages: AgentMessage[];
102
- isStreaming: boolean;
103
-
104
- // Session management
105
- newSession(options?: { parentSession?: string }): Promise<boolean>; // Returns false if cancelled by hook
106
- switchSession(sessionPath: string): Promise<boolean>;
107
-
108
- // Forking
109
- fork(entryId: string): Promise<{ selectedText: string; cancelled: boolean }>; // Creates new session file
110
- navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean }>; // In-place navigation
111
-
112
- // Hook message injection
113
- sendHookMessage(message: HookMessage, triggerTurn?: boolean): Promise<void>;
114
-
115
- // Compaction
116
- compact(customInstructions?: string): Promise<CompactionResult>;
117
- abortCompaction(): void;
118
-
119
- // Abort current operation
120
- abort(): Promise<void>;
121
-
122
- // Cleanup
123
- dispose(): void;
124
- }
125
- ```
126
-
127
- ### Prompting and Message Queueing
128
-
129
- The `prompt()` method handles prompt templates, extension commands, and message sending:
130
-
131
- ```typescript
132
- // Basic prompt (when not streaming)
133
- await session.prompt("What files are here?");
134
-
135
- // With images
136
- await session.prompt("What's in this image?", {
137
- images: [{ type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } }]
138
- });
139
-
140
- // During streaming: must specify how to queue the message
141
- await session.prompt("Stop and do this instead", { streamingBehavior: "steer" });
142
- await session.prompt("After you're done, also check X", { streamingBehavior: "followUp" });
143
- ```
144
-
145
- **Behavior:**
146
- - **Extension commands** (e.g., `/mycommand`): Execute immediately, even during streaming. They manage their own LLM interaction via `shortcut.sendMessage()`.
147
- - **File-based prompt templates** (from `.md` files): Expanded to their content before sending/queueing.
148
- - **During streaming without `streamingBehavior`**: Throws an error. Use `steer()` or `followUp()` directly, or specify the option.
149
-
150
- For explicit queueing during streaming:
151
-
152
- ```typescript
153
- // Interrupt the agent (delivered after current tool, skips remaining tools)
154
- await session.steer("New instruction");
155
-
156
- // Wait for agent to finish (delivered only when agent stops)
157
- await session.followUp("After you're done, also do this");
158
- ```
159
-
160
- Both `steer()` and `followUp()` expand file-based prompt templates but error on extension commands (extension commands cannot be queued).
161
-
162
- ### Agent and AgentState
163
-
164
- The `Agent` class (from `shortcutxl`) handles the core LLM interaction. Access it via `session.agent`.
165
-
166
- ```typescript
167
- // Access current state
168
- const state = session.agent.state;
169
-
170
- // state.messages: AgentMessage[] - conversation history
171
- // state.model: Model - current model
172
- // state.thinkingLevel: ThinkingLevel - current thinking level
173
- // state.systemPrompt: string - system prompt
174
- // state.tools: Tool[] - available tools
175
-
176
- // Replace messages (useful for branching, restoration)
177
- session.agent.replaceMessages(messages);
178
-
179
- // Wait for agent to finish processing
180
- await session.agent.waitForIdle();
181
- ```
182
-
183
- ### Events
184
-
185
- Subscribe to events to receive streaming output and lifecycle notifications.
186
-
187
- ```typescript
188
- session.subscribe((event) => {
189
- switch (event.type) {
190
- // Streaming text from assistant
191
- case "message_update":
192
- if (event.assistantMessageEvent.type === "text_delta") {
193
- process.stdout.write(event.assistantMessageEvent.delta);
194
- }
195
- if (event.assistantMessageEvent.type === "thinking_delta") {
196
- // Thinking output (if thinking enabled)
197
- }
198
- break;
199
-
200
- // Tool execution
201
- case "tool_execution_start":
202
- console.log(`Tool: ${event.toolName}`);
203
- break;
204
- case "tool_execution_update":
205
- // Streaming tool output
206
- break;
207
- case "tool_execution_end":
208
- console.log(`Result: ${event.isError ? "error" : "success"}`);
209
- break;
210
-
211
- // Message lifecycle
212
- case "message_start":
213
- // New message starting
214
- break;
215
- case "message_end":
216
- // Message complete
217
- break;
218
-
219
- // Agent lifecycle
220
- case "agent_start":
221
- // Agent started processing prompt
222
- break;
223
- case "agent_end":
224
- // Agent finished (event.messages contains new messages)
225
- break;
226
-
227
- // Turn lifecycle (one LLM response + tool calls)
228
- case "turn_start":
229
- break;
230
- case "turn_end":
231
- // event.message: assistant response
232
- // event.toolResults: tool results from this turn
233
- break;
234
-
235
- // Session events (auto-compaction, retry)
236
- case "auto_compaction_start":
237
- case "auto_compaction_end":
238
- case "auto_retry_start":
239
- case "auto_retry_end":
240
- break;
241
- }
242
- });
243
- ```
244
-
245
- ## Options Reference
246
-
247
- ### Directories
248
-
249
- ```typescript
250
- const { session } = await createAgentSession({
251
- // Working directory for DefaultResourceLoader discovery
252
- cwd: process.cwd(), // default
253
-
254
- // Global config directory
255
- agentDir: "~/.shortcut/agent", // default (expands ~)
256
- });
257
- ```
258
-
259
- `cwd` is used by `DefaultResourceLoader` for:
260
- - Project extensions (`.shortcut/extensions/`)
261
- - Project skills:
262
- - `.shortcut/skills/`
263
- - `.agents/skills/` in `cwd` and ancestor directories (up to git repo root, or filesystem root when not in a repo)
264
- - Project prompts (`.shortcut/prompts/`)
265
- - Context files (`AGENTS.md` walking up from cwd)
266
- - Session directory naming
267
-
268
- `agentDir` is used by `DefaultResourceLoader` for:
269
- - Global extensions (`extensions/`)
270
- - Global skills:
271
- - `skills/` under `agentDir` (for example `~/.shortcut/agent/skills/`)
272
- - `~/.agents/skills/`
273
- - Global prompts (`prompts/`)
274
- - Global context file (`AGENTS.md`)
275
- - Settings (`settings.json`)
276
- - Custom models (`models.json`)
277
- - Credentials (`auth.json`)
278
- - Sessions (`sessions/`)
279
-
280
- When you pass a custom `ResourceLoader`, `cwd` and `agentDir` no longer control resource discovery. They still influence session naming and tool path resolution.
281
-
282
- ### Model
283
-
284
- ```typescript
285
- import { getModel } from "shortcutxl";
286
- import { AuthStorage, ModelRegistry } from "shortcutxl";
287
-
288
- const authStorage = AuthStorage.create();
289
- const modelRegistry = new ModelRegistry(authStorage);
290
-
291
- // Find specific built-in model (doesn't check if API key exists)
292
- const opus = getModel("anthropic", "claude-opus-4-5");
293
- if (!opus) throw new Error("Model not found");
294
-
295
- // Find any model by provider/id, including custom models from models.json
296
- // (doesn't check if API key exists)
297
- const customModel = modelRegistry.find("my-provider", "my-model");
298
-
299
- // Get only models that have valid API keys configured
300
- const available = await modelRegistry.getAvailable();
301
-
302
- const { session } = await createAgentSession({
303
- model: opus,
304
- thinkingLevel: "medium", // off, minimal, low, medium, high, xhigh
305
-
306
- authStorage,
307
- modelRegistry,
308
- });
309
- ```
310
-
311
- If no model is provided:
312
- 1. Tries to restore from session (if continuing)
313
- 2. Uses default from settings
314
- 3. Falls back to first available model
315
-
316
- > See [examples/sdk/02-custom-model.ts](../examples/sdk/02-custom-model.ts)
317
-
318
- ### API Keys and OAuth
319
-
320
- API key resolution priority (handled by AuthStorage):
321
- 1. Runtime overrides (via `setRuntimeApiKey`, not persisted)
322
- 2. Stored credentials in `auth.json` (API keys or OAuth tokens)
323
- 3. Environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, etc.)
324
- 4. Fallback resolver (for custom provider keys from `models.json`)
325
-
326
- ```typescript
327
- import { AuthStorage, ModelRegistry } from "shortcutxl";
328
-
329
- // Default: uses ~/.shortcut/agent/auth.json and ~/.shortcut/agent/models.json
330
- const authStorage = AuthStorage.create();
331
- const modelRegistry = new ModelRegistry(authStorage);
332
-
333
- const { session } = await createAgentSession({
334
- sessionManager: SessionManager.inMemory(),
335
- authStorage,
336
- modelRegistry,
337
- });
338
-
339
- // Runtime API key override (not persisted to disk)
340
- authStorage.setRuntimeApiKey("anthropic", "sk-my-temp-key");
341
-
342
- // Custom auth storage location
343
- const customAuth = AuthStorage.create("/my/app/auth.json");
344
- const customRegistry = new ModelRegistry(customAuth, "/my/app/models.json");
345
-
346
- const { session } = await createAgentSession({
347
- sessionManager: SessionManager.inMemory(),
348
- authStorage: customAuth,
349
- modelRegistry: customRegistry,
350
- });
351
-
352
- // No custom models.json (built-in models only)
353
- const simpleRegistry = new ModelRegistry(authStorage);
354
- ```
355
-
356
- > See [examples/sdk/09-api-keys-and-oauth.ts](../examples/sdk/09-api-keys-and-oauth.ts)
357
-
358
- ### System Prompt
359
-
360
- Use a `ResourceLoader` to override the system prompt:
361
-
362
- ```typescript
363
- import { createAgentSession, DefaultResourceLoader } from "shortcutxl";
364
-
365
- const loader = new DefaultResourceLoader({
366
- systemPromptOverride: () => "You are a helpful assistant.",
367
- });
368
- await loader.reload();
369
-
370
- const { session } = await createAgentSession({ resourceLoader: loader });
371
- ```
372
-
373
- > See [examples/sdk/03-custom-prompt.ts](../examples/sdk/03-custom-prompt.ts)
374
-
375
- ### Tools
376
-
377
- ```typescript
378
- import {
379
- codingTools, // read, bash, edit, write (default)
380
- readOnlyTools, // read, grep, find, ls
381
- readTool, bashTool, editTool, writeTool,
382
- grepTool, findTool, lsTool,
383
- } from "shortcutxl";
384
-
385
- // Use built-in tool set
386
- const { session } = await createAgentSession({
387
- tools: readOnlyTools,
388
- });
389
-
390
- // Pick specific tools
391
- const { session } = await createAgentSession({
392
- tools: [readTool, bashTool, grepTool],
393
- });
394
- ```
395
-
396
- #### Tools with Custom cwd
397
-
398
- **Important:** The pre-built tool instances (`readTool`, `bashTool`, etc.) use `process.cwd()` for path resolution. When you specify a custom `cwd` AND provide explicit `tools`, you must use the tool factory functions to ensure paths resolve correctly:
399
-
400
- ```typescript
401
- import {
402
- createCodingTools, // Creates [read, bash, edit, write] for specific cwd
403
- createReadOnlyTools, // Creates [read, grep, find, ls] for specific cwd
404
- createReadTool,
405
- createBashTool,
406
- createEditTool,
407
- createWriteTool,
408
- createGrepTool,
409
- createFindTool,
410
- createLsTool,
411
- } from "shortcutxl";
412
-
413
- const cwd = "/path/to/project";
414
-
415
- // Use factory for tool sets
416
- const { session } = await createAgentSession({
417
- cwd,
418
- tools: createCodingTools(cwd), // Tools resolve paths relative to cwd
419
- });
420
-
421
- // Or pick specific tools
422
- const { session } = await createAgentSession({
423
- cwd,
424
- tools: [createReadTool(cwd), createBashTool(cwd), createGrepTool(cwd)],
425
- });
426
- ```
427
-
428
- **When you don't need factories:**
429
- - If you omit `tools`, Shortcut automatically creates them with the correct `cwd`
430
- - If you use `process.cwd()` as your `cwd`, the pre-built instances work fine
431
-
432
- **When you must use factories:**
433
- - When you specify both `cwd` (different from `process.cwd()`) AND `tools`
434
-
435
- > See [examples/sdk/05-tools.ts](../examples/sdk/05-tools.ts)
436
-
437
- ### Custom Tools
438
-
439
- ```typescript
440
- import { Type } from "@sinclair/typebox";
441
- import { createAgentSession, type ToolDefinition } from "shortcutxl";
442
-
443
- // Inline custom tool
444
- const myTool: ToolDefinition = {
445
- name: "my_tool",
446
- label: "My Tool",
447
- description: "Does something useful",
448
- parameters: Type.Object({
449
- input: Type.String({ description: "Input value" }),
450
- }),
451
- execute: async (toolCallId, params, onUpdate, ctx, signal) => ({
452
- content: [{ type: "text", text: `Result: ${params.input}` }],
453
- details: {},
454
- }),
455
- };
456
-
457
- // Pass custom tools directly
458
- const { session } = await createAgentSession({
459
- customTools: [myTool],
460
- });
461
- ```
462
-
463
- Custom tools passed via `customTools` are combined with extension-registered tools. Extensions loaded by the ResourceLoader can also register tools via `shortcut.registerTool()`.
464
-
465
- > See [examples/sdk/05-tools.ts](../examples/sdk/05-tools.ts)
466
-
467
- ### Extensions
468
-
469
- Extensions are loaded by the `ResourceLoader`. `DefaultResourceLoader` discovers extensions from `~/.shortcut/agent/extensions/`, `.shortcut/extensions/`, and settings.json extension sources.
470
-
471
- ```typescript
472
- import { createAgentSession, DefaultResourceLoader } from "shortcutxl";
473
-
474
- const loader = new DefaultResourceLoader({
475
- additionalExtensionPaths: ["/path/to/my-extension.ts"],
476
- extensionFactories: [
477
- (shortcut) => {
478
- shortcut.on("agent_start", () => {
479
- console.log("[Inline Extension] Agent starting");
480
- });
481
- },
482
- ],
483
- });
484
- await loader.reload();
485
-
486
- const { session } = await createAgentSession({ resourceLoader: loader });
487
- ```
488
-
489
- Extensions can register tools, subscribe to events, add commands, and more. See [extensions.md](extensions.md) for the full API.
490
-
491
- **Event Bus:** Extensions can communicate via `shortcut.events`. Pass a shared `eventBus` to `DefaultResourceLoader` if you need to emit or listen from outside:
492
-
493
- ```typescript
494
- import { createEventBus, DefaultResourceLoader } from "shortcutxl";
495
-
496
- const eventBus = createEventBus();
497
- const loader = new DefaultResourceLoader({
498
- eventBus,
499
- });
500
- await loader.reload();
501
-
502
- eventBus.on("my-extension:status", (data) => console.log(data));
503
- ```
504
-
505
- > See [examples/sdk/06-extensions.ts](../examples/sdk/06-extensions.ts) and [docs/extensions.md](extensions.md)
506
-
507
- ### Skills
508
-
509
- ```typescript
510
- import {
511
- createAgentSession,
512
- DefaultResourceLoader,
513
- type Skill,
514
- } from "shortcutxl";
515
-
516
- const customSkill: Skill = {
517
- name: "my-skill",
518
- description: "Custom instructions",
519
- filePath: "/path/to/SKILL.md",
520
- baseDir: "/path/to",
521
- source: "custom",
522
- };
523
-
524
- const loader = new DefaultResourceLoader({
525
- skillsOverride: (current) => ({
526
- skills: [...current.skills, customSkill],
527
- diagnostics: current.diagnostics,
528
- }),
529
- });
530
- await loader.reload();
531
-
532
- const { session } = await createAgentSession({ resourceLoader: loader });
533
- ```
534
-
535
- > See [examples/sdk/04-skills.ts](../examples/sdk/04-skills.ts)
536
-
537
- ### Context Files
538
-
539
- ```typescript
540
- import { createAgentSession, DefaultResourceLoader } from "shortcutxl";
541
-
542
- const loader = new DefaultResourceLoader({
543
- agentsFilesOverride: (current) => ({
544
- agentsFiles: [
545
- ...current.agentsFiles,
546
- { path: "/virtual/AGENTS.md", content: "# Guidelines\n\n- Be concise" },
547
- ],
548
- }),
549
- });
550
- await loader.reload();
551
-
552
- const { session } = await createAgentSession({ resourceLoader: loader });
553
- ```
554
-
555
- > See [examples/sdk/07-context-files.ts](../examples/sdk/07-context-files.ts)
556
-
557
- ### Slash Commands
558
-
559
- ```typescript
560
- import {
561
- createAgentSession,
562
- DefaultResourceLoader,
563
- type PromptTemplate,
564
- } from "shortcutxl";
565
-
566
- const customCommand: PromptTemplate = {
567
- name: "deploy",
568
- description: "Deploy the application",
569
- source: "(custom)",
570
- content: "# Deploy\n\n1. Build\n2. Test\n3. Deploy",
571
- };
572
-
573
- const loader = new DefaultResourceLoader({
574
- promptsOverride: (current) => ({
575
- prompts: [...current.prompts, customCommand],
576
- diagnostics: current.diagnostics,
577
- }),
578
- });
579
- await loader.reload();
580
-
581
- const { session } = await createAgentSession({ resourceLoader: loader });
582
- ```
583
-
584
- > See [examples/sdk/08-prompt-templates.ts](../examples/sdk/08-prompt-templates.ts)
585
-
586
- ### Session Management
587
-
588
- Sessions use a tree structure with `id`/`parentId` linking, enabling in-place branching.
589
-
590
- ```typescript
591
- import { createAgentSession, SessionManager } from "shortcutxl";
592
-
593
- // In-memory (no persistence)
594
- const { session } = await createAgentSession({
595
- sessionManager: SessionManager.inMemory(),
596
- });
597
-
598
- // New persistent session
599
- const { session } = await createAgentSession({
600
- sessionManager: SessionManager.create(process.cwd()),
601
- });
602
-
603
- // Continue most recent
604
- const { session, modelFallbackMessage } = await createAgentSession({
605
- sessionManager: SessionManager.continueRecent(process.cwd()),
606
- });
607
- if (modelFallbackMessage) {
608
- console.log("Note:", modelFallbackMessage);
609
- }
610
-
611
- // Open specific file
612
- const { session } = await createAgentSession({
613
- sessionManager: SessionManager.open("/path/to/session.jsonl"),
614
- });
615
-
616
- // List available sessions (async with optional progress callback)
617
- const sessions = await SessionManager.list(process.cwd());
618
- for (const info of sessions) {
619
- console.log(`${info.id}: ${info.firstMessage} (${info.messageCount} messages, cwd: ${info.cwd})`);
620
- }
621
-
622
- // List all sessions across all projects
623
- const allSessions = await SessionManager.listAll((loaded, total) => {
624
- console.log(`Loading ${loaded}/${total}...`);
625
- });
626
-
627
- // Custom session directory (no cwd encoding)
628
- const customDir = "/path/to/my-sessions";
629
- const { session } = await createAgentSession({
630
- sessionManager: SessionManager.create(process.cwd(), customDir),
631
- });
632
- ```
633
-
634
- **SessionManager tree API:**
635
-
636
- ```typescript
637
- const sm = SessionManager.open("/path/to/session.jsonl");
638
-
639
- // Tree traversal
640
- const entries = sm.getEntries(); // All entries (excludes header)
641
- const tree = sm.getTree(); // Full tree structure
642
- const path = sm.getPath(); // Path from root to current leaf
643
- const leaf = sm.getLeafEntry(); // Current leaf entry
644
- const entry = sm.getEntry(id); // Get entry by ID
645
- const children = sm.getChildren(id); // Direct children of entry
646
-
647
- // Labels
648
- const label = sm.getLabel(id); // Get label for entry
649
- sm.appendLabelChange(id, "checkpoint"); // Set label
650
-
651
- // Branching
652
- sm.branch(entryId); // Move leaf to earlier entry
653
- sm.branchWithSummary(id, "Summary..."); // Branch with context summary
654
- sm.createBranchedSession(leafId); // Extract path to new file
655
- ```
656
-
657
- > See [examples/sdk/11-sessions.ts](../examples/sdk/11-sessions.ts) and [docs/session.md](session.md)
658
-
659
- ### Settings Management
660
-
661
- ```typescript
662
- import { createAgentSession, SettingsManager, SessionManager } from "shortcutxl";
663
-
664
- // Default: loads from files (global + project merged)
665
- const { session } = await createAgentSession({
666
- settingsManager: SettingsManager.create(),
667
- });
668
-
669
- // With overrides
670
- const settingsManager = SettingsManager.create();
671
- settingsManager.applyOverrides({
672
- compaction: { enabled: false },
673
- retry: { enabled: true, maxRetries: 5 },
674
- });
675
- const { session } = await createAgentSession({ settingsManager });
676
-
677
- // In-memory (no file I/O, for testing)
678
- const { session } = await createAgentSession({
679
- settingsManager: SettingsManager.inMemory({ compaction: { enabled: false } }),
680
- sessionManager: SessionManager.inMemory(),
681
- });
682
-
683
- // Custom directories
684
- const { session } = await createAgentSession({
685
- settingsManager: SettingsManager.create("/custom/cwd", "/custom/agent"),
686
- });
687
- ```
688
-
689
- **Static factories:**
690
- - `SettingsManager.create(cwd?, agentDir?)` - Load from files
691
- - `SettingsManager.inMemory(settings?)` - No file I/O
692
-
693
- **Project-specific settings:**
694
-
695
- Settings load from two locations and merge:
696
- 1. Global: `~/.shortcut/agent/settings.json`
697
- 2. Project: `<cwd>/.shortcut/settings.json`
698
-
699
- Project overrides global. Nested objects merge keys. Setters modify global settings by default.
700
-
701
- **Persistence and error handling semantics:**
702
-
703
- - Settings getters/setters are synchronous for in-memory state.
704
- - Setters enqueue persistence writes asynchronously.
705
- - Call `await settingsManager.flush()` when you need a durability boundary (for example, before process exit or before asserting file contents in tests).
706
- - `SettingsManager` does not print settings I/O errors. Use `settingsManager.drainErrors()` and report them in your app layer.
707
-
708
- > See [examples/sdk/10-settings.ts](../examples/sdk/10-settings.ts)
709
-
710
- ## ResourceLoader
711
-
712
- Use `DefaultResourceLoader` to discover extensions, skills, prompts, themes, and context files.
713
-
714
- ```typescript
715
- import {
716
- DefaultResourceLoader,
717
- getAgentDir,
718
- } from "shortcutxl";
719
-
720
- const loader = new DefaultResourceLoader({
721
- cwd,
722
- agentDir: getAgentDir(),
723
- });
724
- await loader.reload();
725
-
726
- const extensions = loader.getExtensions();
727
- const skills = loader.getSkills();
728
- const prompts = loader.getPrompts();
729
- const themes = loader.getThemes();
730
- const contextFiles = loader.getAgentsFiles().agentsFiles;
731
- ```
732
-
733
- ## Return Value
734
-
735
- `createAgentSession()` returns:
736
-
737
- ```typescript
738
- interface CreateAgentSessionResult {
739
- // The session
740
- session: AgentSession;
741
-
742
- // Extensions result (for runner setup)
743
- extensionsResult: LoadExtensionsResult;
744
-
745
- // Warning if session model couldn't be restored
746
- modelFallbackMessage?: string;
747
- }
748
-
749
- interface LoadExtensionsResult {
750
- extensions: Extension[];
751
- errors: Array<{ path: string; error: string }>;
752
- runtime: ExtensionRuntime;
753
- }
754
- ```
755
-
756
- ## Complete Example
757
-
758
- ```typescript
759
- import { getModel } from "shortcutxl";
760
- import { Type } from "@sinclair/typebox";
761
- import {
762
- AuthStorage,
763
- createAgentSession,
764
- DefaultResourceLoader,
765
- ModelRegistry,
766
- SessionManager,
767
- SettingsManager,
768
- readTool,
769
- bashTool,
770
- type ToolDefinition,
771
- } from "shortcutxl";
772
-
773
- // Set up auth storage (custom location)
774
- const authStorage = AuthStorage.create("/custom/agent/auth.json");
775
-
776
- // Runtime API key override (not persisted)
777
- if (process.env.MY_KEY) {
778
- authStorage.setRuntimeApiKey("anthropic", process.env.MY_KEY);
779
- }
780
-
781
- // Model registry (no custom models.json)
782
- const modelRegistry = new ModelRegistry(authStorage);
783
-
784
- // Inline tool
785
- const statusTool: ToolDefinition = {
786
- name: "status",
787
- label: "Status",
788
- description: "Get system status",
789
- parameters: Type.Object({}),
790
- execute: async () => ({
791
- content: [{ type: "text", text: `Uptime: ${process.uptime()}s` }],
792
- details: {},
793
- }),
794
- };
795
-
796
- const model = getModel("anthropic", "claude-opus-4-5");
797
- if (!model) throw new Error("Model not found");
798
-
799
- // In-memory settings with overrides
800
- const settingsManager = SettingsManager.inMemory({
801
- compaction: { enabled: false },
802
- retry: { enabled: true, maxRetries: 2 },
803
- });
804
-
805
- const loader = new DefaultResourceLoader({
806
- cwd: process.cwd(),
807
- agentDir: "/custom/agent",
808
- settingsManager,
809
- systemPromptOverride: () => "You are a minimal assistant. Be concise.",
810
- });
811
- await loader.reload();
812
-
813
- const { session } = await createAgentSession({
814
- cwd: process.cwd(),
815
- agentDir: "/custom/agent",
816
-
817
- model,
818
- thinkingLevel: "off",
819
- authStorage,
820
- modelRegistry,
821
-
822
- tools: [readTool, bashTool],
823
- customTools: [statusTool],
824
- resourceLoader: loader,
825
-
826
- sessionManager: SessionManager.inMemory(),
827
- settingsManager,
828
- });
829
-
830
- session.subscribe((event) => {
831
- if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
832
- process.stdout.write(event.assistantMessageEvent.delta);
833
- }
834
- });
835
-
836
- await session.prompt("Get status and list files.");
837
- ```
838
-
839
- ## Run Modes
840
-
841
- The SDK exports run mode utilities for building custom interfaces on top of `createAgentSession()`:
842
-
843
- ### InteractiveMode
844
-
845
- Full TUI interactive mode with editor, chat history, and all built-in commands:
846
-
847
- ```typescript
848
- import { createAgentSession, InteractiveMode } from "shortcutxl";
849
-
850
- const { session } = await createAgentSession({ /* ... */ });
851
-
852
- const mode = new InteractiveMode(session, {
853
- // All optional
854
- migratedProviders: [], // Show migration warnings
855
- modelFallbackMessage: undefined, // Show model restore warning
856
- initialMessage: "Hello", // Send on startup
857
- initialImages: [], // Images with initial message
858
- initialMessages: [], // Additional startup prompts
859
- });
860
-
861
- await mode.run(); // Blocks until exit
862
- ```
863
-
864
- ### runPrintMode
865
-
866
- Single-shot mode: send prompts, output result, exit:
867
-
868
- ```typescript
869
- import { createAgentSession, runPrintMode } from "shortcutxl";
870
-
871
- const { session } = await createAgentSession({ /* ... */ });
872
-
873
- await runPrintMode(session, {
874
- mode: "text", // "text" for final response, "json" for all events
875
- initialMessage: "Hello", // First message (can include @file content)
876
- initialImages: [], // Images with initial message
877
- messages: ["Follow up"], // Additional prompts
878
- });
879
- ```
880
-
881
- ### runRpcMode
882
-
883
- JSON-RPC mode for subprocess integration:
884
-
885
- ```typescript
886
- import { createAgentSession, runRpcMode } from "shortcutxl";
887
-
888
- const { session } = await createAgentSession({ /* ... */ });
889
-
890
- await runRpcMode(session); // Reads JSON commands from stdin, writes to stdout
891
- ```
892
-
893
- See [RPC documentation](rpc.md) for the JSON protocol.
894
-
895
- ## RPC Mode Alternative
896
-
897
- For subprocess-based integration without building with the SDK, use the CLI directly:
898
-
899
- ```bash
900
- shortcut --mode rpc --no-session
901
- ```
902
-
903
- See [RPC documentation](rpc.md) for the JSON protocol.
904
-
905
- The SDK is preferred when:
906
- - You want type safety
907
- - You're in the same Node.js process
908
- - You need direct access to agent state
909
- - You want to customize tools/extensions programmatically
910
-
911
- RPC mode is preferred when:
912
- - You're integrating from another language
913
- - You want process isolation
914
- - You're building a language-agnostic client
915
-
916
- ## Exports
917
-
918
- The main entry point exports:
919
-
920
- ```typescript
921
- // Factory
922
- createAgentSession
923
-
924
- // Auth and Models
925
- AuthStorage
926
- ModelRegistry
927
-
928
- // Resource loading
929
- DefaultResourceLoader
930
- type ResourceLoader
931
- createEventBus
932
-
933
- // Helpers
934
-
935
- // Session management
936
- SessionManager
937
- SettingsManager
938
-
939
- // Built-in tools (use process.cwd())
940
- codingTools
941
- readOnlyTools
942
- readTool, bashTool, editTool, writeTool
943
- grepTool, findTool, lsTool
944
-
945
- // Tool factories (for custom cwd)
946
- createCodingTools
947
- createReadOnlyTools
948
- createReadTool, createBashTool, createEditTool, createWriteTool
949
- createGrepTool, createFindTool, createLsTool
950
-
951
- // Types
952
- type CreateAgentSessionOptions
953
- type CreateAgentSessionResult
954
- type ExtensionFactory
955
- type ExtensionAPI
956
- type ToolDefinition
957
- type Skill
958
- type PromptTemplate
959
- type Tool
960
- ```
961
-
962
- For extension types, see [extensions.md](extensions.md) for the full API.
1
+ > Shortcut can help you use the SDK. Ask it to build an integration for your use case.
2
+
3
+ # SDK
4
+
5
+ The SDK provides programmatic access to Shortcut's agent capabilities. Use it to embed Shortcut in other applications, build custom interfaces, or integrate with automated workflows.
6
+
7
+ **Example use cases:**
8
+ - Build a custom UI (web, desktop, mobile)
9
+ - Integrate agent capabilities into existing applications
10
+ - Create automated pipelines with agent reasoning
11
+ - Build custom tools that spawn sub-agents
12
+ - Test agent behavior programmatically
13
+
14
+ See [examples/sdk/](../examples/sdk/) for working examples from minimal to full control.
15
+
16
+ ## Quick Start
17
+
18
+ ```typescript
19
+ import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "shortcutxl";
20
+
21
+ // Set up credential storage and model registry
22
+ const authStorage = AuthStorage.create();
23
+ const modelRegistry = new ModelRegistry(authStorage);
24
+
25
+ const { session } = await createAgentSession({
26
+ sessionManager: SessionManager.inMemory(),
27
+ authStorage,
28
+ modelRegistry,
29
+ });
30
+
31
+ session.subscribe((event) => {
32
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
33
+ process.stdout.write(event.assistantMessageEvent.delta);
34
+ }
35
+ });
36
+
37
+ await session.prompt("What files are in the current directory?");
38
+ ```
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ npm install shortcutxl
44
+ ```
45
+
46
+ The SDK is included in the main package. No separate installation needed.
47
+
48
+ ## Core Concepts
49
+
50
+ ### createAgentSession()
51
+
52
+ The main factory function. Creates an `AgentSession` with configurable options.
53
+
54
+ `createAgentSession()` uses a `ResourceLoader` to supply extensions, skills, prompt templates, themes, and context files. If you do not provide one, it uses `DefaultResourceLoader` with standard discovery.
55
+
56
+ ```typescript
57
+ import { createAgentSession } from "shortcutxl";
58
+
59
+ // Minimal: defaults with DefaultResourceLoader
60
+ const { session } = await createAgentSession();
61
+
62
+ // Custom: override specific options
63
+ const { session } = await createAgentSession({
64
+ model: myModel,
65
+ tools: [readTool, bashTool],
66
+ sessionManager: SessionManager.inMemory(),
67
+ });
68
+ ```
69
+
70
+ ### AgentSession
71
+
72
+ The session manages the agent lifecycle, message history, and event streaming.
73
+
74
+ ```typescript
75
+ interface AgentSession {
76
+ // Send a prompt and wait for completion
77
+ // If streaming, requires streamingBehavior option to queue the message
78
+ prompt(text: string, options?: PromptOptions): Promise<void>;
79
+
80
+ // Queue messages during streaming
81
+ steer(text: string): Promise<void>; // Interrupt: delivered after current tool, skips remaining
82
+ followUp(text: string): Promise<void>; // Wait: delivered only when agent finishes
83
+
84
+ // Subscribe to events (returns unsubscribe function)
85
+ subscribe(listener: (event: AgentSessionEvent) => void): () => void;
86
+
87
+ // Session info
88
+ sessionFile: string | undefined; // undefined for in-memory
89
+ sessionId: string;
90
+
91
+ // Model control
92
+ setModel(model: Model): Promise<void>;
93
+ setThinkingLevel(level: ThinkingLevel): void;
94
+ cycleModel(): Promise<ModelCycleResult | undefined>;
95
+ cycleThinkingLevel(): ThinkingLevel | undefined;
96
+
97
+ // State access
98
+ agent: Agent;
99
+ model: Model | undefined;
100
+ thinkingLevel: ThinkingLevel;
101
+ messages: AgentMessage[];
102
+ isStreaming: boolean;
103
+
104
+ // Session management
105
+ newSession(options?: { parentSession?: string }): Promise<boolean>; // Returns false if cancelled by hook
106
+ switchSession(sessionPath: string): Promise<boolean>;
107
+
108
+ // Forking
109
+ fork(entryId: string): Promise<{ selectedText: string; cancelled: boolean }>; // Creates new session file
110
+ navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean }>; // In-place navigation
111
+
112
+ // Hook message injection
113
+ sendHookMessage(message: HookMessage, triggerTurn?: boolean): Promise<void>;
114
+
115
+ // Compaction
116
+ compact(customInstructions?: string): Promise<CompactionResult>;
117
+ abortCompaction(): void;
118
+
119
+ // Abort current operation
120
+ abort(): Promise<void>;
121
+
122
+ // Cleanup
123
+ dispose(): void;
124
+ }
125
+ ```
126
+
127
+ ### Prompting and Message Queueing
128
+
129
+ The `prompt()` method handles prompt templates, extension commands, and message sending:
130
+
131
+ ```typescript
132
+ // Basic prompt (when not streaming)
133
+ await session.prompt("What files are here?");
134
+
135
+ // With images
136
+ await session.prompt("What's in this image?", {
137
+ images: [{ type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } }]
138
+ });
139
+
140
+ // During streaming: must specify how to queue the message
141
+ await session.prompt("Stop and do this instead", { streamingBehavior: "steer" });
142
+ await session.prompt("After you're done, also check X", { streamingBehavior: "followUp" });
143
+ ```
144
+
145
+ **Behavior:**
146
+ - **Extension commands** (e.g., `/mycommand`): Execute immediately, even during streaming. They manage their own LLM interaction via `shortcut.sendMessage()`.
147
+ - **File-based prompt templates** (from `.md` files): Expanded to their content before sending/queueing.
148
+ - **During streaming without `streamingBehavior`**: Throws an error. Use `steer()` or `followUp()` directly, or specify the option.
149
+
150
+ For explicit queueing during streaming:
151
+
152
+ ```typescript
153
+ // Interrupt the agent (delivered after current tool, skips remaining tools)
154
+ await session.steer("New instruction");
155
+
156
+ // Wait for agent to finish (delivered only when agent stops)
157
+ await session.followUp("After you're done, also do this");
158
+ ```
159
+
160
+ Both `steer()` and `followUp()` expand file-based prompt templates but error on extension commands (extension commands cannot be queued).
161
+
162
+ ### Agent and AgentState
163
+
164
+ The `Agent` class (from `shortcutxl`) handles the core LLM interaction. Access it via `session.agent`.
165
+
166
+ ```typescript
167
+ // Access current state
168
+ const state = session.agent.state;
169
+
170
+ // state.messages: AgentMessage[] - conversation history
171
+ // state.model: Model - current model
172
+ // state.thinkingLevel: ThinkingLevel - current thinking level
173
+ // state.systemPrompt: string - system prompt
174
+ // state.tools: Tool[] - available tools
175
+
176
+ // Replace messages (useful for branching, restoration)
177
+ session.agent.replaceMessages(messages);
178
+
179
+ // Wait for agent to finish processing
180
+ await session.agent.waitForIdle();
181
+ ```
182
+
183
+ ### Events
184
+
185
+ Subscribe to events to receive streaming output and lifecycle notifications.
186
+
187
+ ```typescript
188
+ session.subscribe((event) => {
189
+ switch (event.type) {
190
+ // Streaming text from assistant
191
+ case "message_update":
192
+ if (event.assistantMessageEvent.type === "text_delta") {
193
+ process.stdout.write(event.assistantMessageEvent.delta);
194
+ }
195
+ if (event.assistantMessageEvent.type === "thinking_delta") {
196
+ // Thinking output (if thinking enabled)
197
+ }
198
+ break;
199
+
200
+ // Tool execution
201
+ case "tool_execution_start":
202
+ console.log(`Tool: ${event.toolName}`);
203
+ break;
204
+ case "tool_execution_update":
205
+ // Streaming tool output
206
+ break;
207
+ case "tool_execution_end":
208
+ console.log(`Result: ${event.isError ? "error" : "success"}`);
209
+ break;
210
+
211
+ // Message lifecycle
212
+ case "message_start":
213
+ // New message starting
214
+ break;
215
+ case "message_end":
216
+ // Message complete
217
+ break;
218
+
219
+ // Agent lifecycle
220
+ case "agent_start":
221
+ // Agent started processing prompt
222
+ break;
223
+ case "agent_end":
224
+ // Agent finished (event.messages contains new messages)
225
+ break;
226
+
227
+ // Turn lifecycle (one LLM response + tool calls)
228
+ case "turn_start":
229
+ break;
230
+ case "turn_end":
231
+ // event.message: assistant response
232
+ // event.toolResults: tool results from this turn
233
+ break;
234
+
235
+ // Session events (auto-compaction, retry)
236
+ case "auto_compaction_start":
237
+ case "auto_compaction_end":
238
+ case "auto_retry_start":
239
+ case "auto_retry_end":
240
+ break;
241
+ }
242
+ });
243
+ ```
244
+
245
+ ## Options Reference
246
+
247
+ ### Directories
248
+
249
+ ```typescript
250
+ const { session } = await createAgentSession({
251
+ // Working directory for DefaultResourceLoader discovery
252
+ cwd: process.cwd(), // default
253
+
254
+ // Global config directory
255
+ agentDir: "~/.shortcut/agent", // default (expands ~)
256
+ });
257
+ ```
258
+
259
+ `cwd` is used by `DefaultResourceLoader` for:
260
+ - Project extensions (`.shortcut/extensions/`)
261
+ - Project skills:
262
+ - `.shortcut/skills/`
263
+ - `.agents/skills/` in `cwd` and ancestor directories (up to git repo root, or filesystem root when not in a repo)
264
+ - Project prompts (`.shortcut/prompts/`)
265
+ - Context files (`AGENTS.md` walking up from cwd)
266
+ - Session directory naming
267
+
268
+ `agentDir` is used by `DefaultResourceLoader` for:
269
+ - Global extensions (`extensions/`)
270
+ - Global skills:
271
+ - `skills/` under `agentDir` (for example `~/.shortcut/agent/skills/`)
272
+ - `~/.agents/skills/`
273
+ - Global prompts (`prompts/`)
274
+ - Global context file (`AGENTS.md`)
275
+ - Settings (`settings.json`)
276
+ - Custom models (`models.json`)
277
+ - Credentials (`auth.json`)
278
+ - Sessions (`sessions/`)
279
+
280
+ When you pass a custom `ResourceLoader`, `cwd` and `agentDir` no longer control resource discovery. They still influence session naming and tool path resolution.
281
+
282
+ ### Model
283
+
284
+ ```typescript
285
+ import { getModel } from "shortcutxl";
286
+ import { AuthStorage, ModelRegistry } from "shortcutxl";
287
+
288
+ const authStorage = AuthStorage.create();
289
+ const modelRegistry = new ModelRegistry(authStorage);
290
+
291
+ // Find specific built-in model (doesn't check if API key exists)
292
+ const opus = getModel("anthropic", "claude-opus-4-5");
293
+ if (!opus) throw new Error("Model not found");
294
+
295
+ // Find any model by provider/id, including custom models from models.json
296
+ // (doesn't check if API key exists)
297
+ const customModel = modelRegistry.find("my-provider", "my-model");
298
+
299
+ // Get only models that have valid API keys configured
300
+ const available = await modelRegistry.getAvailable();
301
+
302
+ const { session } = await createAgentSession({
303
+ model: opus,
304
+ thinkingLevel: "medium", // off, minimal, low, medium, high, xhigh
305
+
306
+ authStorage,
307
+ modelRegistry,
308
+ });
309
+ ```
310
+
311
+ If no model is provided:
312
+ 1. Tries to restore from session (if continuing)
313
+ 2. Uses default from settings
314
+ 3. Falls back to first available model
315
+
316
+ > See [examples/sdk/02-custom-model.ts](../examples/sdk/02-custom-model.ts)
317
+
318
+ ### API Keys and OAuth
319
+
320
+ API key resolution priority (handled by AuthStorage):
321
+ 1. Runtime overrides (via `setRuntimeApiKey`, not persisted)
322
+ 2. Stored credentials in `auth.json` (API keys or OAuth tokens)
323
+ 3. Environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, etc.)
324
+ 4. Fallback resolver (for custom provider keys from `models.json`)
325
+
326
+ ```typescript
327
+ import { AuthStorage, ModelRegistry } from "shortcutxl";
328
+
329
+ // Default: uses ~/.shortcut/agent/auth.json and ~/.shortcut/agent/models.json
330
+ const authStorage = AuthStorage.create();
331
+ const modelRegistry = new ModelRegistry(authStorage);
332
+
333
+ const { session } = await createAgentSession({
334
+ sessionManager: SessionManager.inMemory(),
335
+ authStorage,
336
+ modelRegistry,
337
+ });
338
+
339
+ // Runtime API key override (not persisted to disk)
340
+ authStorage.setRuntimeApiKey("anthropic", "sk-my-temp-key");
341
+
342
+ // Custom auth storage location
343
+ const customAuth = AuthStorage.create("/my/app/auth.json");
344
+ const customRegistry = new ModelRegistry(customAuth, "/my/app/models.json");
345
+
346
+ const { session } = await createAgentSession({
347
+ sessionManager: SessionManager.inMemory(),
348
+ authStorage: customAuth,
349
+ modelRegistry: customRegistry,
350
+ });
351
+
352
+ // No custom models.json (built-in models only)
353
+ const simpleRegistry = new ModelRegistry(authStorage);
354
+ ```
355
+
356
+ > See [examples/sdk/09-api-keys-and-oauth.ts](../examples/sdk/09-api-keys-and-oauth.ts)
357
+
358
+ ### System Prompt
359
+
360
+ Use a `ResourceLoader` to override the system prompt:
361
+
362
+ ```typescript
363
+ import { createAgentSession, DefaultResourceLoader } from "shortcutxl";
364
+
365
+ const loader = new DefaultResourceLoader({
366
+ systemPromptOverride: () => "You are a helpful assistant.",
367
+ });
368
+ await loader.reload();
369
+
370
+ const { session } = await createAgentSession({ resourceLoader: loader });
371
+ ```
372
+
373
+ > See [examples/sdk/03-custom-prompt.ts](../examples/sdk/03-custom-prompt.ts)
374
+
375
+ ### Tools
376
+
377
+ ```typescript
378
+ import {
379
+ codingTools, // read, bash, edit, write (default)
380
+ readOnlyTools, // read, grep, find, ls
381
+ readTool, bashTool, editTool, writeTool,
382
+ grepTool, findTool, lsTool,
383
+ } from "shortcutxl";
384
+
385
+ // Use built-in tool set
386
+ const { session } = await createAgentSession({
387
+ tools: readOnlyTools,
388
+ });
389
+
390
+ // Pick specific tools
391
+ const { session } = await createAgentSession({
392
+ tools: [readTool, bashTool, grepTool],
393
+ });
394
+ ```
395
+
396
+ #### Tools with Custom cwd
397
+
398
+ **Important:** The pre-built tool instances (`readTool`, `bashTool`, etc.) use `process.cwd()` for path resolution. When you specify a custom `cwd` AND provide explicit `tools`, you must use the tool factory functions to ensure paths resolve correctly:
399
+
400
+ ```typescript
401
+ import {
402
+ createCodingTools, // Creates [read, bash, edit, write] for specific cwd
403
+ createReadOnlyTools, // Creates [read, grep, find, ls] for specific cwd
404
+ createReadTool,
405
+ createBashTool,
406
+ createEditTool,
407
+ createWriteTool,
408
+ createGrepTool,
409
+ createFindTool,
410
+ createLsTool,
411
+ } from "shortcutxl";
412
+
413
+ const cwd = "/path/to/project";
414
+
415
+ // Use factory for tool sets
416
+ const { session } = await createAgentSession({
417
+ cwd,
418
+ tools: createCodingTools(cwd), // Tools resolve paths relative to cwd
419
+ });
420
+
421
+ // Or pick specific tools
422
+ const { session } = await createAgentSession({
423
+ cwd,
424
+ tools: [createReadTool(cwd), createBashTool(cwd), createGrepTool(cwd)],
425
+ });
426
+ ```
427
+
428
+ **When you don't need factories:**
429
+ - If you omit `tools`, Shortcut automatically creates them with the correct `cwd`
430
+ - If you use `process.cwd()` as your `cwd`, the pre-built instances work fine
431
+
432
+ **When you must use factories:**
433
+ - When you specify both `cwd` (different from `process.cwd()`) AND `tools`
434
+
435
+ > See [examples/sdk/05-tools.ts](../examples/sdk/05-tools.ts)
436
+
437
+ ### Custom Tools
438
+
439
+ ```typescript
440
+ import { Type } from "@sinclair/typebox";
441
+ import { createAgentSession, type ToolDefinition } from "shortcutxl";
442
+
443
+ // Inline custom tool
444
+ const myTool: ToolDefinition = {
445
+ name: "my_tool",
446
+ label: "My Tool",
447
+ description: "Does something useful",
448
+ parameters: Type.Object({
449
+ input: Type.String({ description: "Input value" }),
450
+ }),
451
+ execute: async (toolCallId, params, onUpdate, ctx, signal) => ({
452
+ content: [{ type: "text", text: `Result: ${params.input}` }],
453
+ details: {},
454
+ }),
455
+ };
456
+
457
+ // Pass custom tools directly
458
+ const { session } = await createAgentSession({
459
+ customTools: [myTool],
460
+ });
461
+ ```
462
+
463
+ Custom tools passed via `customTools` are combined with extension-registered tools. Extensions loaded by the ResourceLoader can also register tools via `shortcut.registerTool()`.
464
+
465
+ > See [examples/sdk/05-tools.ts](../examples/sdk/05-tools.ts)
466
+
467
+ ### Extensions
468
+
469
+ Extensions are loaded by the `ResourceLoader`. `DefaultResourceLoader` discovers extensions from `~/.shortcut/agent/extensions/`, `.shortcut/extensions/`, and settings.json extension sources.
470
+
471
+ ```typescript
472
+ import { createAgentSession, DefaultResourceLoader } from "shortcutxl";
473
+
474
+ const loader = new DefaultResourceLoader({
475
+ additionalExtensionPaths: ["/path/to/my-extension.ts"],
476
+ extensionFactories: [
477
+ (shortcut) => {
478
+ shortcut.on("agent_start", () => {
479
+ console.log("[Inline Extension] Agent starting");
480
+ });
481
+ },
482
+ ],
483
+ });
484
+ await loader.reload();
485
+
486
+ const { session } = await createAgentSession({ resourceLoader: loader });
487
+ ```
488
+
489
+ Extensions can register tools, subscribe to events, add commands, and more. See [extensions.md](extensions.md) for the full API.
490
+
491
+ **Event Bus:** Extensions can communicate via `shortcut.events`. Pass a shared `eventBus` to `DefaultResourceLoader` if you need to emit or listen from outside:
492
+
493
+ ```typescript
494
+ import { createEventBus, DefaultResourceLoader } from "shortcutxl";
495
+
496
+ const eventBus = createEventBus();
497
+ const loader = new DefaultResourceLoader({
498
+ eventBus,
499
+ });
500
+ await loader.reload();
501
+
502
+ eventBus.on("my-extension:status", (data) => console.log(data));
503
+ ```
504
+
505
+ > See [examples/sdk/06-extensions.ts](../examples/sdk/06-extensions.ts) and [docs/extensions.md](extensions.md)
506
+
507
+ ### Skills
508
+
509
+ ```typescript
510
+ import {
511
+ createAgentSession,
512
+ DefaultResourceLoader,
513
+ type Skill,
514
+ } from "shortcutxl";
515
+
516
+ const customSkill: Skill = {
517
+ name: "my-skill",
518
+ description: "Custom instructions",
519
+ filePath: "/path/to/SKILL.md",
520
+ baseDir: "/path/to",
521
+ source: "custom",
522
+ };
523
+
524
+ const loader = new DefaultResourceLoader({
525
+ skillsOverride: (current) => ({
526
+ skills: [...current.skills, customSkill],
527
+ diagnostics: current.diagnostics,
528
+ }),
529
+ });
530
+ await loader.reload();
531
+
532
+ const { session } = await createAgentSession({ resourceLoader: loader });
533
+ ```
534
+
535
+ > See [examples/sdk/04-skills.ts](../examples/sdk/04-skills.ts)
536
+
537
+ ### Context Files
538
+
539
+ ```typescript
540
+ import { createAgentSession, DefaultResourceLoader } from "shortcutxl";
541
+
542
+ const loader = new DefaultResourceLoader({
543
+ agentsFilesOverride: (current) => ({
544
+ agentsFiles: [
545
+ ...current.agentsFiles,
546
+ { path: "/virtual/AGENTS.md", content: "# Guidelines\n\n- Be concise" },
547
+ ],
548
+ }),
549
+ });
550
+ await loader.reload();
551
+
552
+ const { session } = await createAgentSession({ resourceLoader: loader });
553
+ ```
554
+
555
+ > See [examples/sdk/07-context-files.ts](../examples/sdk/07-context-files.ts)
556
+
557
+ ### Slash Commands
558
+
559
+ ```typescript
560
+ import {
561
+ createAgentSession,
562
+ DefaultResourceLoader,
563
+ type PromptTemplate,
564
+ } from "shortcutxl";
565
+
566
+ const customCommand: PromptTemplate = {
567
+ name: "deploy",
568
+ description: "Deploy the application",
569
+ source: "(custom)",
570
+ content: "# Deploy\n\n1. Build\n2. Test\n3. Deploy",
571
+ };
572
+
573
+ const loader = new DefaultResourceLoader({
574
+ promptsOverride: (current) => ({
575
+ prompts: [...current.prompts, customCommand],
576
+ diagnostics: current.diagnostics,
577
+ }),
578
+ });
579
+ await loader.reload();
580
+
581
+ const { session } = await createAgentSession({ resourceLoader: loader });
582
+ ```
583
+
584
+ > See [examples/sdk/08-prompt-templates.ts](../examples/sdk/08-prompt-templates.ts)
585
+
586
+ ### Session Management
587
+
588
+ Sessions use a tree structure with `id`/`parentId` linking, enabling in-place branching.
589
+
590
+ ```typescript
591
+ import { createAgentSession, SessionManager } from "shortcutxl";
592
+
593
+ // In-memory (no persistence)
594
+ const { session } = await createAgentSession({
595
+ sessionManager: SessionManager.inMemory(),
596
+ });
597
+
598
+ // New persistent session
599
+ const { session } = await createAgentSession({
600
+ sessionManager: SessionManager.create(process.cwd()),
601
+ });
602
+
603
+ // Continue most recent
604
+ const { session, modelFallbackMessage } = await createAgentSession({
605
+ sessionManager: SessionManager.continueRecent(process.cwd()),
606
+ });
607
+ if (modelFallbackMessage) {
608
+ console.log("Note:", modelFallbackMessage);
609
+ }
610
+
611
+ // Open specific file
612
+ const { session } = await createAgentSession({
613
+ sessionManager: SessionManager.open("/path/to/session.jsonl"),
614
+ });
615
+
616
+ // List available sessions (async with optional progress callback)
617
+ const sessions = await SessionManager.list(process.cwd());
618
+ for (const info of sessions) {
619
+ console.log(`${info.id}: ${info.firstMessage} (${info.messageCount} messages, cwd: ${info.cwd})`);
620
+ }
621
+
622
+ // List all sessions across all projects
623
+ const allSessions = await SessionManager.listAll((loaded, total) => {
624
+ console.log(`Loading ${loaded}/${total}...`);
625
+ });
626
+
627
+ // Custom session directory (no cwd encoding)
628
+ const customDir = "/path/to/my-sessions";
629
+ const { session } = await createAgentSession({
630
+ sessionManager: SessionManager.create(process.cwd(), customDir),
631
+ });
632
+ ```
633
+
634
+ **SessionManager tree API:**
635
+
636
+ ```typescript
637
+ const sm = SessionManager.open("/path/to/session.jsonl");
638
+
639
+ // Tree traversal
640
+ const entries = sm.getEntries(); // All entries (excludes header)
641
+ const tree = sm.getTree(); // Full tree structure
642
+ const path = sm.getPath(); // Path from root to current leaf
643
+ const leaf = sm.getLeafEntry(); // Current leaf entry
644
+ const entry = sm.getEntry(id); // Get entry by ID
645
+ const children = sm.getChildren(id); // Direct children of entry
646
+
647
+ // Labels
648
+ const label = sm.getLabel(id); // Get label for entry
649
+ sm.appendLabelChange(id, "checkpoint"); // Set label
650
+
651
+ // Branching
652
+ sm.branch(entryId); // Move leaf to earlier entry
653
+ sm.branchWithSummary(id, "Summary..."); // Branch with context summary
654
+ sm.createBranchedSession(leafId); // Extract path to new file
655
+ ```
656
+
657
+ > See [examples/sdk/11-sessions.ts](../examples/sdk/11-sessions.ts) and [docs/session.md](session.md)
658
+
659
+ ### Settings Management
660
+
661
+ ```typescript
662
+ import { createAgentSession, SettingsManager, SessionManager } from "shortcutxl";
663
+
664
+ // Default: loads from files (global + project merged)
665
+ const { session } = await createAgentSession({
666
+ settingsManager: SettingsManager.create(),
667
+ });
668
+
669
+ // With overrides
670
+ const settingsManager = SettingsManager.create();
671
+ settingsManager.applyOverrides({
672
+ compaction: { enabled: false },
673
+ retry: { enabled: true, maxRetries: 5 },
674
+ });
675
+ const { session } = await createAgentSession({ settingsManager });
676
+
677
+ // In-memory (no file I/O, for testing)
678
+ const { session } = await createAgentSession({
679
+ settingsManager: SettingsManager.inMemory({ compaction: { enabled: false } }),
680
+ sessionManager: SessionManager.inMemory(),
681
+ });
682
+
683
+ // Custom directories
684
+ const { session } = await createAgentSession({
685
+ settingsManager: SettingsManager.create("/custom/cwd", "/custom/agent"),
686
+ });
687
+ ```
688
+
689
+ **Static factories:**
690
+ - `SettingsManager.create(cwd?, agentDir?)` - Load from files
691
+ - `SettingsManager.inMemory(settings?)` - No file I/O
692
+
693
+ **Project-specific settings:**
694
+
695
+ Settings load from two locations and merge:
696
+ 1. Global: `~/.shortcut/agent/settings.json`
697
+ 2. Project: `<cwd>/.shortcut/settings.json`
698
+
699
+ Project overrides global. Nested objects merge keys. Setters modify global settings by default.
700
+
701
+ **Persistence and error handling semantics:**
702
+
703
+ - Settings getters/setters are synchronous for in-memory state.
704
+ - Setters enqueue persistence writes asynchronously.
705
+ - Call `await settingsManager.flush()` when you need a durability boundary (for example, before process exit or before asserting file contents in tests).
706
+ - `SettingsManager` does not print settings I/O errors. Use `settingsManager.drainErrors()` and report them in your app layer.
707
+
708
+ > See [examples/sdk/10-settings.ts](../examples/sdk/10-settings.ts)
709
+
710
+ ## ResourceLoader
711
+
712
+ Use `DefaultResourceLoader` to discover extensions, skills, prompts, themes, and context files.
713
+
714
+ ```typescript
715
+ import {
716
+ DefaultResourceLoader,
717
+ getAgentDir,
718
+ } from "shortcutxl";
719
+
720
+ const loader = new DefaultResourceLoader({
721
+ cwd,
722
+ agentDir: getAgentDir(),
723
+ });
724
+ await loader.reload();
725
+
726
+ const extensions = loader.getExtensions();
727
+ const skills = loader.getSkills();
728
+ const prompts = loader.getPrompts();
729
+ const themes = loader.getThemes();
730
+ const contextFiles = loader.getAgentsFiles().agentsFiles;
731
+ ```
732
+
733
+ ## Return Value
734
+
735
+ `createAgentSession()` returns:
736
+
737
+ ```typescript
738
+ interface CreateAgentSessionResult {
739
+ // The session
740
+ session: AgentSession;
741
+
742
+ // Extensions result (for runner setup)
743
+ extensionsResult: LoadExtensionsResult;
744
+
745
+ // Warning if session model couldn't be restored
746
+ modelFallbackMessage?: string;
747
+ }
748
+
749
+ interface LoadExtensionsResult {
750
+ extensions: Extension[];
751
+ errors: Array<{ path: string; error: string }>;
752
+ runtime: ExtensionRuntime;
753
+ }
754
+ ```
755
+
756
+ ## Complete Example
757
+
758
+ ```typescript
759
+ import { getModel } from "shortcutxl";
760
+ import { Type } from "@sinclair/typebox";
761
+ import {
762
+ AuthStorage,
763
+ createAgentSession,
764
+ DefaultResourceLoader,
765
+ ModelRegistry,
766
+ SessionManager,
767
+ SettingsManager,
768
+ readTool,
769
+ bashTool,
770
+ type ToolDefinition,
771
+ } from "shortcutxl";
772
+
773
+ // Set up auth storage (custom location)
774
+ const authStorage = AuthStorage.create("/custom/agent/auth.json");
775
+
776
+ // Runtime API key override (not persisted)
777
+ if (process.env.MY_KEY) {
778
+ authStorage.setRuntimeApiKey("anthropic", process.env.MY_KEY);
779
+ }
780
+
781
+ // Model registry (no custom models.json)
782
+ const modelRegistry = new ModelRegistry(authStorage);
783
+
784
+ // Inline tool
785
+ const statusTool: ToolDefinition = {
786
+ name: "status",
787
+ label: "Status",
788
+ description: "Get system status",
789
+ parameters: Type.Object({}),
790
+ execute: async () => ({
791
+ content: [{ type: "text", text: `Uptime: ${process.uptime()}s` }],
792
+ details: {},
793
+ }),
794
+ };
795
+
796
+ const model = getModel("anthropic", "claude-opus-4-5");
797
+ if (!model) throw new Error("Model not found");
798
+
799
+ // In-memory settings with overrides
800
+ const settingsManager = SettingsManager.inMemory({
801
+ compaction: { enabled: false },
802
+ retry: { enabled: true, maxRetries: 2 },
803
+ });
804
+
805
+ const loader = new DefaultResourceLoader({
806
+ cwd: process.cwd(),
807
+ agentDir: "/custom/agent",
808
+ settingsManager,
809
+ systemPromptOverride: () => "You are a minimal assistant. Be concise.",
810
+ });
811
+ await loader.reload();
812
+
813
+ const { session } = await createAgentSession({
814
+ cwd: process.cwd(),
815
+ agentDir: "/custom/agent",
816
+
817
+ model,
818
+ thinkingLevel: "off",
819
+ authStorage,
820
+ modelRegistry,
821
+
822
+ tools: [readTool, bashTool],
823
+ customTools: [statusTool],
824
+ resourceLoader: loader,
825
+
826
+ sessionManager: SessionManager.inMemory(),
827
+ settingsManager,
828
+ });
829
+
830
+ session.subscribe((event) => {
831
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
832
+ process.stdout.write(event.assistantMessageEvent.delta);
833
+ }
834
+ });
835
+
836
+ await session.prompt("Get status and list files.");
837
+ ```
838
+
839
+ ## Run Modes
840
+
841
+ The SDK exports run mode utilities for building custom interfaces on top of `createAgentSession()`:
842
+
843
+ ### InteractiveMode
844
+
845
+ Full TUI interactive mode with editor, chat history, and all built-in commands:
846
+
847
+ ```typescript
848
+ import { createAgentSession, InteractiveMode } from "shortcutxl";
849
+
850
+ const { session } = await createAgentSession({ /* ... */ });
851
+
852
+ const mode = new InteractiveMode(session, {
853
+ // All optional
854
+ migratedProviders: [], // Show migration warnings
855
+ modelFallbackMessage: undefined, // Show model restore warning
856
+ initialMessage: "Hello", // Send on startup
857
+ initialImages: [], // Images with initial message
858
+ initialMessages: [], // Additional startup prompts
859
+ });
860
+
861
+ await mode.run(); // Blocks until exit
862
+ ```
863
+
864
+ ### runPrintMode
865
+
866
+ Single-shot mode: send prompts, output result, exit:
867
+
868
+ ```typescript
869
+ import { createAgentSession, runPrintMode } from "shortcutxl";
870
+
871
+ const { session } = await createAgentSession({ /* ... */ });
872
+
873
+ await runPrintMode(session, {
874
+ mode: "text", // "text" for final response, "json" for all events
875
+ initialMessage: "Hello", // First message (can include @file content)
876
+ initialImages: [], // Images with initial message
877
+ messages: ["Follow up"], // Additional prompts
878
+ });
879
+ ```
880
+
881
+ ### runRpcMode
882
+
883
+ JSON-RPC mode for subprocess integration:
884
+
885
+ ```typescript
886
+ import { createAgentSession, runRpcMode } from "shortcutxl";
887
+
888
+ const { session } = await createAgentSession({ /* ... */ });
889
+
890
+ await runRpcMode(session); // Reads JSON commands from stdin, writes to stdout
891
+ ```
892
+
893
+ See [RPC documentation](rpc.md) for the JSON protocol.
894
+
895
+ ## RPC Mode Alternative
896
+
897
+ For subprocess-based integration without building with the SDK, use the CLI directly:
898
+
899
+ ```bash
900
+ shortcut --mode rpc --no-session
901
+ ```
902
+
903
+ See [RPC documentation](rpc.md) for the JSON protocol.
904
+
905
+ The SDK is preferred when:
906
+ - You want type safety
907
+ - You're in the same Node.js process
908
+ - You need direct access to agent state
909
+ - You want to customize tools/extensions programmatically
910
+
911
+ RPC mode is preferred when:
912
+ - You're integrating from another language
913
+ - You want process isolation
914
+ - You're building a language-agnostic client
915
+
916
+ ## Exports
917
+
918
+ The main entry point exports:
919
+
920
+ ```typescript
921
+ // Factory
922
+ createAgentSession
923
+
924
+ // Auth and Models
925
+ AuthStorage
926
+ ModelRegistry
927
+
928
+ // Resource loading
929
+ DefaultResourceLoader
930
+ type ResourceLoader
931
+ createEventBus
932
+
933
+ // Helpers
934
+
935
+ // Session management
936
+ SessionManager
937
+ SettingsManager
938
+
939
+ // Built-in tools (use process.cwd())
940
+ codingTools
941
+ readOnlyTools
942
+ readTool, bashTool, editTool, writeTool
943
+ grepTool, findTool, lsTool
944
+
945
+ // Tool factories (for custom cwd)
946
+ createCodingTools
947
+ createReadOnlyTools
948
+ createReadTool, createBashTool, createEditTool, createWriteTool
949
+ createGrepTool, createFindTool, createLsTool
950
+
951
+ // Types
952
+ type CreateAgentSessionOptions
953
+ type CreateAgentSessionResult
954
+ type ExtensionFactory
955
+ type ExtensionAPI
956
+ type ToolDefinition
957
+ type Skill
958
+ type PromptTemplate
959
+ type Tool
960
+ ```
961
+
962
+ For extension types, see [extensions.md](extensions.md) for the full API.