@salesforce/sfdx-agent-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE.txt +21 -0
  2. package/README.md +508 -0
  3. package/dist/agent-connectivity-resolver.d.ts +62 -0
  4. package/dist/agent-connectivity-resolver.js +47 -0
  5. package/dist/agent-connectivity-resolver.js.map +1 -0
  6. package/dist/agent-manager.d.ts +134 -0
  7. package/dist/agent-manager.js +266 -0
  8. package/dist/agent-manager.js.map +1 -0
  9. package/dist/agent.d.ts +218 -0
  10. package/dist/agent.js +313 -0
  11. package/dist/agent.js.map +1 -0
  12. package/dist/chat-session.d.ts +298 -0
  13. package/dist/chat-session.js +407 -0
  14. package/dist/chat-session.js.map +1 -0
  15. package/dist/errors.d.ts +12 -0
  16. package/dist/errors.js +20 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/harness/agent-harness.d.ts +200 -0
  19. package/dist/harness/agent-harness.js +6 -0
  20. package/dist/harness/agent-harness.js.map +1 -0
  21. package/dist/harness/harness-bus-owner.d.ts +34 -0
  22. package/dist/harness/harness-bus-owner.js +78 -0
  23. package/dist/harness/harness-bus-owner.js.map +1 -0
  24. package/dist/harness/harness-config.d.ts +89 -0
  25. package/dist/harness/harness-config.js +26 -0
  26. package/dist/harness/harness-config.js.map +1 -0
  27. package/dist/harness/harness-factory.d.ts +21 -0
  28. package/dist/harness/harness-factory.js +6 -0
  29. package/dist/harness/harness-factory.js.map +1 -0
  30. package/dist/harness/index.d.ts +4 -0
  31. package/dist/harness/index.js +6 -0
  32. package/dist/harness/index.js.map +1 -0
  33. package/dist/index.d.ts +23 -0
  34. package/dist/index.js +20 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/internal/telemetry-router.d.ts +41 -0
  37. package/dist/internal/telemetry-router.js +128 -0
  38. package/dist/internal/telemetry-router.js.map +1 -0
  39. package/dist/mcp-auth.d.ts +20 -0
  40. package/dist/mcp-auth.js +40 -0
  41. package/dist/mcp-auth.js.map +1 -0
  42. package/dist/mcp-config.d.ts +52 -0
  43. package/dist/mcp-config.js +13 -0
  44. package/dist/mcp-config.js.map +1 -0
  45. package/dist/test/tsconfig.tsbuildinfo +1 -0
  46. package/dist/types/events.d.ts +151 -0
  47. package/dist/types/events.js +6 -0
  48. package/dist/types/events.js.map +1 -0
  49. package/dist/types/index.d.ts +4 -0
  50. package/dist/types/index.js +6 -0
  51. package/dist/types/index.js.map +1 -0
  52. package/dist/types/messages.d.ts +60 -0
  53. package/dist/types/messages.js +6 -0
  54. package/dist/types/messages.js.map +1 -0
  55. package/dist/types/telemetry-events.d.ts +93 -0
  56. package/dist/types/telemetry-events.js +6 -0
  57. package/dist/types/telemetry-events.js.map +1 -0
  58. package/dist/types/tools.d.ts +57 -0
  59. package/dist/types/tools.js +6 -0
  60. package/dist/types/tools.js.map +1 -0
  61. package/dist/types/usage.d.ts +31 -0
  62. package/dist/types/usage.js +6 -0
  63. package/dist/types/usage.js.map +1 -0
  64. package/dist/workspace.d.ts +15 -0
  65. package/dist/workspace.js +48 -0
  66. package/dist/workspace.js.map +1 -0
  67. package/package.json +64 -0
package/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ Terms of Use
2
+
3
+ Copyright 2026 Salesforce, Inc. All rights reserved.
4
+
5
+ These Terms of Use govern the download, installation, and/or use of this software provided by Salesforce, Inc. ("Salesforce") (the "Software"), were last updated on March 24, 2026, and constitute a legally binding agreement between you and Salesforce. If you do not agree to these Terms of Use, do not install or use the Software. The Software may link to third-party software components licensed under various open source licenses ("Open Source Components"). These Terms of Use pertain solely to Salesforce's proprietary code in the Software. It does not alter or extend any rights or obligations regarding the Open Source Components. For clarity, your use of the Open Source Components is governed by the terms of the applicable open source license(s). You are solely responsible for complying with the terms and conditions of those open source licenses.
6
+
7
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free copyright license to reproduce, revocable, publicly display, publicly perform, sublicense, and distribute the Software and derivative works subject to these Terms. These Terms shall be included in all copies or substantial portions of the Software.
8
+
9
+ Subject to the limited rights expressly granted hereunder, Salesforce reserves all rights, title, and interest in and to all intellectual property subsisting in the Software. No rights are granted to you hereunder other than as expressly set forth herein. Users residing in countries on the United States Office of Foreign Assets Control sanction list, or which are otherwise subject to a US export embargo, may not use the Software.
10
+
11
+ Implementation of the Software may require development work, for which you are responsible. The Software may contain bugs, errors and incompatibilities and is made available on an AS IS basis without support, updates, or service level commitments.
12
+
13
+ Salesforce reserves the right at any time to modify, suspend, or discontinue, the Software (or any part thereof) with or without notice. You agree that Salesforce shall not be liable to you or to any third party for any modification, suspension, or discontinuance.
14
+
15
+ You agree to defend Salesforce against any claim, demand, suit or proceeding made or brought against Salesforce by a third party arising out of or accruing from (a) your use of the Software, and (b) any application you develop with the Software that infringes any copyright, trademark, trade secret, trade dress, patent, or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy (each a "Claim Against Salesforce"), and will indemnify Salesforce from any damages, attorney fees, and costs finally awarded against Salesforce as a result of, or for any amounts paid by Salesforce under a settlement approved by you in writing of, a Claim Against Salesforce, provided Salesforce (x) promptly gives you written notice of the Claim Against Salesforce, (y) gives you sole control of the defense and settlement of the Claim Against Salesforce (except that you may not settle any Claim Against Salesforce unless it unconditionally releases Salesforce of all liability), and (z) gives you all reasonable assistance, at your expense.
16
+
17
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA, OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
18
+
19
+ These Terms of Use shall be governed exclusively by the internal laws of the State of California, without regard to its conflicts of laws rules. Each party hereby consents to the exclusive jurisdiction of the state and federal courts located in San Francisco County, California to adjudicate any dispute arising out of or relating to these Terms of Use and the download, installation, and/or use of the Software. Except as expressly stated herein, these Terms of Use constitute the entire agreement between the parties, and supersede all prior and contemporaneous agreements, proposals, or representations, written or oral, concerning their subject matter. No modification, amendment, or waiver of any provision of these Terms of Use shall be effective unless it is by an update to these Terms of Use that Salesforce makes available, or is in writing and signed by the party against whom the modification, amendment, or waiver is to be asserted.
20
+
21
+ Data Privacy: Salesforce may collect, process, and store device, system, and other information related to your use of the Software. This information includes, but is not limited to, IP address, user metrics, and other data ("Usage Data"). Salesforce may use Usage Data for analytics, product development, and marketing purposes. You acknowledge that files generated in conjunction with the Software may contain sensitive or confidential data, and you are solely responsible for anonymizing and protecting such data.
package/README.md ADDED
@@ -0,0 +1,508 @@
1
+ # @salesforce/sfdx-agent-sdk
2
+
3
+ Harness-agnostic SDK for creating and managing AI agents within the Salesforce developer experience. It provides a
4
+ stable API for agent lifecycle, chat sessions, streaming responses, MCP tool integration, and tool approval flows —
5
+ without coupling consumer code to a specific AI framework.
6
+
7
+ ## Quick Start
8
+
9
+ > This package is not yet published to npm. See [DEVELOPING.md](DEVELOPING.md) to build from source.
10
+
11
+ ```typescript
12
+ import { createAgentManager } from '@salesforce/sfdx-agent-sdk';
13
+ import { MastraHarnessFactory } from '@salesforce/sfdx-agent-harness-mastra';
14
+
15
+ // 1. Create the manager (validates the storage folder exists)
16
+ const manager = await createAgentManager('/path/to/storage', new MastraHarnessFactory());
17
+
18
+ // 2. Create an agent
19
+ const agent = await manager.createAgent('/path/to/project', {
20
+ agentId: 'developer-assistant',
21
+ modelId: 'llmgateway__OpenAIGPT5',
22
+ instructions: 'You are a helpful Salesforce developer assistant.',
23
+ });
24
+
25
+ // 3. Open a chat session and stream a response
26
+ const session = await agent.createChatSession();
27
+ const { eventStream } = await session.chat('Explain Lightning Web Components.');
28
+
29
+ for await (const event of eventStream) {
30
+ if (event.type === 'text-delta') {
31
+ process.stdout.write(event.text);
32
+ } else if (event.type === 'error') {
33
+ console.error(event.error.message);
34
+ break;
35
+ }
36
+ }
37
+
38
+ // 4. Shut down
39
+ await manager.shutdown();
40
+ ```
41
+
42
+ ## API Reference
43
+
44
+ ### `createAgentManager(storageRootFolder, harnessFactory): Promise<AgentManager>`
45
+
46
+ Factory function that creates an `AgentManager` backed by the provided `HarnessFactory`. The `storageRootFolder` must be
47
+ an existing directory and is used for persistent state (database, memory). The SDK verifies that the constructed harness
48
+ uses a supported protocol version before returning the manager.
49
+
50
+ ### `AgentManager`
51
+
52
+ Top-level orchestrator that owns the harness and manages agent lifecycle.
53
+
54
+ | Method | Signature | Description |
55
+ | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
56
+ | `createAgent` | `(projectRoot: string, config?: AgentConfig & { agentId?: string }, options?: { abortSignal?: AbortSignal }) => Promise<Agent>` | Create and register a new agent. `projectRoot` must be an existing directory. If `agentId` is omitted a UUID is generated. |
57
+ | `getAgent` | `(agentId: string) => Agent` | Retrieve an agent by ID. Throws `AgentSDKError` (`AGENT_NOT_FOUND`) if missing. |
58
+ | `getAgentIds` | `() => string[]` | List all managed agent IDs. |
59
+ | `destroyAgent` | `(agentId: string) => Promise<void>` | Destroy an agent and release its resources. Throws `AgentSDKError` (`AGENT_NOT_FOUND`) if missing. |
60
+ | `shutdown` | `() => Promise<void>` | Destroy all agents and shut down the harness. |
61
+ | `onTelemetry` | `(callback: TelemetryEventCallback) => Unsubscribe` | Subscribe to telemetry across all managed agents. |
62
+ | `onLog` | `(callback: (record: LogRecord) => void) => Unsubscribe` | Subscribe to structured logs across all managed agents. |
63
+
64
+ ### `Agent`
65
+
66
+ A configured AI agent. Factory for chat sessions.
67
+
68
+ | Method | Signature | Description |
69
+ | ---------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
70
+ | `getId` | `() => string` | Agent identifier. |
71
+ | `getProjectRoot` | `() => string` | Absolute project path. |
72
+ | `getOrgConnectionInfo` | `() => OrgConnectionInfo` | Org metadata (orgId, alias, instanceUrl, username, env). |
73
+ | `getAgentConfig` | `() => AgentConfig` | Current configuration (shallow copy). |
74
+ | `getMcpServerInfo` | `() => McpServerInfo[]` | MCP server status and discovered tools. |
75
+ | `updateAgentConfig` | `(config?: AgentConfig, options?: { abortSignal?: AbortSignal }) => Promise<void>` | Merge new config into the live agent. |
76
+ | `createChatSession` | `() => Promise<ChatSession>` | Open a new conversation thread. |
77
+ | `getChatSession` | `(sessionId: string) => ChatSession` | Retrieve a session. Throws `AgentSDKError` (`CHAT_SESSION_NOT_FOUND`). |
78
+ | `getChatSessionIds` | `() => string[]` | List active session IDs. |
79
+ | `destroyChatSession` | `(sessionId: string) => Promise<void>` | Destroy a session and its history. |
80
+ | `cloneChatSession` | `(sourceSessionId: string) => Promise<ChatSession>` | Clone a session with its message history. |
81
+ | `compactChatSession` | `(sessionId: string) => Promise<ChatSession>` | Compact a session into a summarized new session. |
82
+ | `destroy` | `() => Promise<void>` | Destroy the agent and all its sessions. |
83
+ | `onTelemetry` | `(callback: TelemetryEventCallback) => Unsubscribe` | Subscribe to telemetry scoped to this agent (and its sessions). |
84
+ | `onLog` | `(callback: (record: LogRecord) => void) => Unsubscribe` | Subscribe to logs scoped to this agent (and its sessions). |
85
+
86
+ ### `ChatSession`
87
+
88
+ A single conversation thread.
89
+
90
+ | Method | Signature | Description |
91
+ | ------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
92
+ | `getId` | `() => string` | Session/thread identifier. |
93
+ | `chat` | `(message: string, options?: ChatOptions) => Promise<ChatStreamResult>` | Send a message and stream the response. |
94
+ | `submitToolResult` | `(toolResult: ToolResultInfo) => Promise<ChatStreamResult>` | Return a consumer-executed tool result and resume the stream. |
95
+ | `approveToolCall` | `(toolCallId: string, options?: { remember?: boolean }) => Promise<ChatStreamResult>` | Approve a pending tool call. |
96
+ | `declineToolCall` | `(toolCallId: string) => Promise<ChatStreamResult>` | Decline a pending tool call. |
97
+ | `getMessageHistory` | `() => Promise<Message[]>` | Retrieve all messages in chronological order. |
98
+ | `clearHistory` | `() => Promise<void>` | Delete all messages. |
99
+ | `addContext` | `(message: string \| Message[]) => Promise<void>` | Inject context without triggering an LLM response. |
100
+ | `subscribe` | `(callback: (event: ChatEvent) => void) => void` | Register a real-time event listener. |
101
+ | `unsubscribe` | `(callback: (event: ChatEvent) => void) => void` | Remove a listener. |
102
+ | `onTelemetry` | `(callback: TelemetryEventCallback) => Unsubscribe` | Subscribe to telemetry scoped to this session. |
103
+ | `onLog` | `(callback: (record: LogRecord) => void) => Unsubscribe` | Subscribe to logs scoped to this session. |
104
+ | `dispose` | `() => void` | Release session-level event resources. Idempotent. |
105
+
106
+ ### `ChatStreamResult`
107
+
108
+ Returned by `chat()`, `submitToolResult()`, `approveToolCall()`, and `declineToolCall()`.
109
+
110
+ | Property | Type | Description |
111
+ | ------------- | --------------------------- | --------------------------------------- |
112
+ | `eventStream` | `AsyncGenerator<ChatEvent>` | Full lifecycle event stream. |
113
+ | `textStream` | `AsyncGenerator<string>` | Convenience stream of text-only tokens. |
114
+
115
+ ### `ChatEvent`
116
+
117
+ Discriminated union (`event.type`) of streaming events:
118
+
119
+ | Type | Key Fields | Description |
120
+ | ----------------------- | ---------------------------------------------- | -------------------------------------------------------- |
121
+ | `start` | — | Stream has begun. |
122
+ | `text-delta` | `text` | Incremental response text. |
123
+ | `reasoning-delta` | `text` | Chain-of-thought fragment. |
124
+ | `tool-call` | `toolCallId`, `toolName`, `args` | Tool invocation. |
125
+ | `tool-approval-request` | `toolCall: ToolCallInfo` | Engine requests approval before executing a tool. |
126
+ | `tool-result` | `toolCallId`, `toolName`, `result`, `isError?` | Tool execution completed. |
127
+ | `step-start` | `stepIndex` | New LLM invocation step began. |
128
+ | `step-finish` | `stepIndex`, `finishReason`, `usage?` | Step completed with per-step token usage. |
129
+ | `error` | `error`, `code?` | Mid-stream error (yielded, not thrown). |
130
+ | `finish` | `finishReason`, `usage?` | Stream completed with aggregate token usage. |
131
+ | `unmapped-chunk` | `chunkType`, `rawChunk` | Unrecognized harness event, preserved for observability. |
132
+
133
+ ### Configuration Types
134
+
135
+ #### `AgentConfig`
136
+
137
+ | Field | Type | Description |
138
+ | --------------- | ------------------ | -------------------------------------------------------------------- |
139
+ | `orgAlias?` | `string` | Salesforce org alias or username. Falls back to project/default org. |
140
+ | `modelId?` | `ModelName` | LLM model identifier (e.g. `'llmgateway__OpenAIGPT5'`). |
141
+ | `name?` | `string` | Human-readable agent name. |
142
+ | `description?` | `string` | Agent purpose description. |
143
+ | `instructions?` | `string` | System instructions for the agent. |
144
+ | `tools?` | `ToolDefinition[]` | Consumer-executed tool schemas. |
145
+ | `mcpServers?` | `MCPConfiguration` | MCP server connections. |
146
+ | `skills?` | `string[]` | Paths to skill directories (relative to project root or absolute). |
147
+
148
+ #### `StreamOptions`
149
+
150
+ | Field | Type | Description |
151
+ | ---------------------- | ------------- | ------------------------------------------------------------------------ |
152
+ | `abortSignal?` | `AbortSignal` | Abort the streaming operation. |
153
+ | `requireToolApproval?` | `boolean` | When `true`, emits `tool-approval-request` before native tool execution. |
154
+
155
+ #### `MCPConfiguration`
156
+
157
+ ```typescript
158
+ type MCPConfiguration = Record<string, MCPServerConfig>;
159
+
160
+ // Stdio server (local subprocess)
161
+ type MCPStdioServerConfig = {
162
+ type: 'stdio';
163
+ command: string;
164
+ args?: string[];
165
+ env?: Record<string, string>;
166
+ enabled?: boolean;
167
+ timeout?: number;
168
+ };
169
+
170
+ // Remote server (HTTP/SSE)
171
+ type MCPRemoteServerConfig = {
172
+ type: 'remote';
173
+ url: string | URL;
174
+ headers?: Record<string, string>;
175
+ enabled?: boolean;
176
+ timeout?: number;
177
+ };
178
+ ```
179
+
180
+ #### `McpServerInfo`
181
+
182
+ | Field | Type | Description |
183
+ | -------- | ------------------------------------------------------ | --------------------------------------- |
184
+ | `name` | `string` | Server identifier. |
185
+ | `status` | `'connected' \| 'connecting' \| 'disabled' \| 'error'` | Connection state. |
186
+ | `tools` | `string[]` | Discovered tool names. |
187
+ | `error?` | `string` | Error message when status is `'error'`. |
188
+
189
+ ### Tool Types
190
+
191
+ ```typescript
192
+ type ToolDefinition = {
193
+ name: string;
194
+ description?: string;
195
+ inputSchema: Record<string, unknown>;
196
+ };
197
+
198
+ type ToolCallInfo = {
199
+ toolCallId: string;
200
+ toolName: string;
201
+ args: Record<string, unknown>;
202
+ };
203
+
204
+ type ToolResultInfo = {
205
+ toolCallId: string;
206
+ toolName: string;
207
+ result: unknown;
208
+ isError?: boolean;
209
+ };
210
+ ```
211
+
212
+ ### Message Types
213
+
214
+ ```typescript
215
+ type Message = {
216
+ id: string;
217
+ role: 'system' | 'user' | 'assistant' | 'tool';
218
+ content: string | MessagePart[];
219
+ createdAt?: Date;
220
+ };
221
+
222
+ type MessagePart = TextPart | ReasoningPart | ToolCallPart | ToolResultPart;
223
+ ```
224
+
225
+ ### Usage & Finish Types
226
+
227
+ ```typescript
228
+ type UsageMetadata = {
229
+ inputTokens?: number;
230
+ outputTokens?: number;
231
+ totalTokens?: number;
232
+ reasoningTokens?: number;
233
+ cachedInputTokens?: number;
234
+ };
235
+
236
+ type FinishReason = 'stop' | 'length' | 'tool-calls' | 'content-filter' | 'error' | 'other';
237
+ ```
238
+
239
+ ### Error Handling
240
+
241
+ The SDK throws `AgentSDKError` for predictable not-found and compatibility conditions. Each error has a `type` property
242
+ from `AgentSDKErrorType`:
243
+
244
+ | Type | Thrown By |
245
+ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
246
+ | `AGENT_NOT_FOUND` | `AgentManager.getAgent()`, `AgentManager.destroyAgent()` |
247
+ | `CHAT_SESSION_NOT_FOUND` | `Agent.getChatSession()`, `Agent.destroyChatSession()`, `Agent.cloneChatSession()`, `Agent.compactChatSession()` |
248
+ | `COMPACTION_FAILED` | `Agent.compactChatSession()` when the harness's underlying summarization call rejects. The original error is attached as `cause`; the source session is left intact. |
249
+ | `DISPOSED` | `Agent` and `ChatSession` methods called after the owner has been destroyed |
250
+ | `INCOMPATIBLE_HARNESS` | `createAgentManager()` when the factory advertises an unsupported `protocolVersion`, or the constructed harness reports a `protocolVersion` that differs from the factory's |
251
+
252
+ ```typescript
253
+ import { AgentSDKError, AgentSDKErrorType } from '@salesforce/sfdx-agent-sdk';
254
+
255
+ try {
256
+ manager.getAgent(id);
257
+ } catch (err) {
258
+ if (err instanceof AgentSDKError && err.type === AgentSDKErrorType.AGENT_NOT_FOUND) {
259
+ // handle not found
260
+ }
261
+ }
262
+ ```
263
+
264
+ #### Streaming method failures
265
+
266
+ The four streaming methods on `ChatSession` — `chat()`, `submitToolResult()`, `approveToolCall()`, and
267
+ `declineToolCall()` — share a single failure contract. Subscribers registered via `subscribe()` are guaranteed to
268
+ receive a terminal event for every turn:
269
+
270
+ - **Pre-stream failure** (the harness rejects before producing a stream): subscribers receive an `ErrorEvent` followed
271
+ by a `FinishEvent(finishReason: 'error')`, and the returned promise then rejects with the original error. Wrap the
272
+ call in `try/catch` if you need to handle this in the caller.
273
+ - **In-stream failure** (the stream yields an `error` event or the underlying generator throws): the `eventStream`
274
+ yields the `ErrorEvent` (synthesizing one from a thrown exception if needed) and, if no `FinishEvent` was already
275
+ emitted, appends a synthetic `FinishEvent(finishReason: 'error')` at the end. The returned promise resolves normally;
276
+ iterate the stream to observe the failure.
277
+ - **Calling a disposed session** throws `AgentSDKError('DISPOSED')` synchronously without notifying subscribers.
278
+
279
+ ### MCP Server Configuration
280
+
281
+ MCP servers are configured at agent creation. Tool discovery runs in the background — the agent is usable immediately,
282
+ and MCP tools become available once `getMcpServerInfo()` shows `status: 'connected'`.
283
+
284
+ ```typescript
285
+ const agent = await manager.createAgent('/project', {
286
+ mcpServers: {
287
+ filesystem: {
288
+ type: 'stdio',
289
+ command: 'npx',
290
+ args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
291
+ },
292
+ },
293
+ });
294
+
295
+ // Poll until connected
296
+ const servers = agent.getMcpServerInfo();
297
+ for (const s of servers) {
298
+ console.log(`${s.name}: ${s.status}, tools: ${s.tools.join(', ')}`);
299
+ }
300
+ ```
301
+
302
+ ### Tool Approval Flow
303
+
304
+ ```typescript
305
+ const { eventStream } = await session.chat('Run the deployment', {
306
+ requireToolApproval: true,
307
+ });
308
+
309
+ for await (const event of eventStream) {
310
+ if (event.type === 'tool-approval-request') {
311
+ const continuation = await session.approveToolCall(event.toolCall.toolCallId);
312
+ for await (const e of continuation.eventStream) {
313
+ // process continuation
314
+ }
315
+ }
316
+ }
317
+ ```
318
+
319
+ ### Consumer-Executed Tools
320
+
321
+ ```typescript
322
+ for await (const event of eventStream) {
323
+ if (event.type === 'tool-call' && event.toolName === 'my-tool') {
324
+ const result = await runLocally(event.args);
325
+ const continuation = await session.submitToolResult({
326
+ toolCallId: event.toolCallId,
327
+ toolName: event.toolName,
328
+ result,
329
+ });
330
+ for await (const e of continuation.eventStream) {
331
+ // process continuation
332
+ }
333
+ }
334
+ }
335
+ ```
336
+
337
+ ### Connectivity Resolution
338
+
339
+ #### `ResolvedConnectivity`
340
+
341
+ Returned by `AgentConnectivityResolver.resolve()`. Contains all resolved runtime artifacts for an agent's org.
342
+
343
+ | Field | Type | Description |
344
+ | ------------------ | ------------------ | ---------------------------------------------------------------------- |
345
+ | `llmGatewayClient` | `LLMGatewayClient` | Pre-configured and authenticated LLM gateway client. |
346
+ | `orgConnection` | `OrgConnection` | Authenticated org connection carrying identity and env inference. |
347
+ | `orgJwt` | `JSONWebToken` | Self-refreshing JWT for the resolved org, used for MCP auth injection. |
348
+
349
+ #### `HarnessAgentConfig`
350
+
351
+ Harness-facing configuration derived from `AgentConfig`. Strips `orgAlias` (resolved above the harness) and adds:
352
+
353
+ | Field | Type | Description |
354
+ | --------- | -------------- | -------------------------------------------------------------------------------------------------------------- |
355
+ | `orgJwt?` | `JSONWebToken` | Self-refreshing JWT. Harness implementations pass this to `resolveMcpServerHeaders()` for auto-auth injection. |
356
+
357
+ ### MCP Auth Helpers
358
+
359
+ #### `resolveMcpServerHeaders(url, orgJwt, headers?): Promise<Record<string, string>>`
360
+
361
+ Resolves final headers for an MCP server request. For Salesforce Hosted MCP Server URLs
362
+ (`https://[env.]api.salesforce.com/platform/mcp/...`), injects `Authorization: Bearer <token>` when no explicit
363
+ Authorization header already exists. For all other URLs, returns headers unmodified.
364
+
365
+ #### `isSalesforcePlatformMcpUrl(url): boolean`
366
+
367
+ Returns `true` if the URL matches a Salesforce Hosted MCP Server endpoint (prod, dev, test, perf, stage).
368
+
369
+ ### Re-exported from `@salesforce/llm-gateway-sdk`
370
+
371
+ - `ModelName` — enum of supported model identifiers
372
+ - `SfApiEnv` — Salesforce API environment enum (`dev`, `perf`, `prod`, `stage`, `test`)
373
+
374
+ ### Telemetry & structured logs
375
+
376
+ The SDK exposes typed `TelemetryEvent` / `LogRecord` streams at the manager, agent, and session scopes. See
377
+ [Telemetry & Logs](#telemetry--logs) below for the event catalog, emit contract, and structured-log table.
378
+
379
+ ## Writing a Harness
380
+
381
+ The SDK ships no harness implementation. Consumers pick one by passing a `HarnessFactory` instance to
382
+ `createAgentManager`. The reference implementation is
383
+ [`@salesforce/sfdx-agent-harness-mastra`](../sfdx-agent-harness-mastra); additional harnesses can ship as independent
384
+ npm packages that depend on this SDK as a `peerDependency`.
385
+
386
+ Harness authors implement two interfaces and can compose one helper class, all exported from this package:
387
+
388
+ | Export | Role |
389
+ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
390
+ | `HarnessFactory` | Construct an `AgentHarness` bound to a storage root. Declares `harnessId` and `protocolVersion`. |
391
+ | `AgentHarness` | Runtime contract: agent / thread / stream / tool / message lifecycle. Declares its own `harnessId` and `protocolVersion`. |
392
+ | `SUPPORTED_PROTOCOL_VERSIONS` | Readonly list of harness protocol versions this SDK accepts. `createAgentManager` checks both the factory and the constructed harness. |
393
+ | `HarnessBusOwner` | Composition helper owning telemetry + log buses with `dispose()` semantics. Reuse it instead of reimplementing bus plumbing. |
394
+
395
+ Minimal skeleton:
396
+
397
+ ```typescript
398
+ import {
399
+ type AgentHarness,
400
+ type HarnessFactory,
401
+ HarnessBusOwner,
402
+ SUPPORTED_PROTOCOL_VERSIONS,
403
+ } from '@salesforce/sfdx-agent-sdk';
404
+
405
+ class MyHarness implements AgentHarness {
406
+ readonly harnessId = 'my-harness';
407
+ readonly protocolVersion = 1;
408
+
409
+ private readonly buses = new HarnessBusOwner();
410
+
411
+ onTelemetry = this.buses.onTelemetry.bind(this.buses);
412
+ onLog = this.buses.onLog.bind(this.buses);
413
+
414
+ async shutdown() {
415
+ this.buses.dispose();
416
+ // release harness-specific resources
417
+ }
418
+ // implement the remaining AgentHarness methods (createAgent, stream, …)
419
+ }
420
+
421
+ export class MyHarnessFactory implements HarnessFactory {
422
+ readonly harnessId = 'my-harness';
423
+ readonly protocolVersion = 1;
424
+ async create(storageRootFolder: string): Promise<AgentHarness> {
425
+ return new MyHarness(storageRootFolder);
426
+ }
427
+ }
428
+ ```
429
+
430
+ Protocol-version rules:
431
+
432
+ - Both `HarnessFactory.protocolVersion` and the constructed `AgentHarness.protocolVersion` must match and must appear in
433
+ `SUPPORTED_PROTOCOL_VERSIONS`. A mismatch throws `AgentSDKError` with type `INCOMPATIBLE_HARNESS`.
434
+ - Bump when you change a method signature, event payload shape, enum value, or ownership of a responsibility. Do not
435
+ bump for additive optional fields or internal refactors.
436
+
437
+ See [ARCHITECTURE.md](ARCHITECTURE.md) for the full interface surface and for details on telemetry routing, which the
438
+ SDK handles transparently as long as the harness emits through `HarnessBusOwner`.
439
+
440
+ ## Telemetry & Logs
441
+
442
+ Subscribe at any of three scopes:
443
+
444
+ ```ts
445
+ manager.onTelemetry((event) => {
446
+ /* every managed agent */
447
+ });
448
+ agent.onTelemetry((event) => {
449
+ /* this agent and its sessions */
450
+ });
451
+ session.onTelemetry((event) => {
452
+ /* this session only */
453
+ });
454
+
455
+ manager.onLog((record) => {
456
+ /* level: 'debug' | 'info' | 'warn' | 'error' */
457
+ });
458
+ ```
459
+
460
+ `onTelemetry` / `onLog` return an `Unsubscribe` function. Subscribers receive only events that originate after they
461
+ subscribe — agent-level subscribers do **not** observe their own `agent-created` event because the consumer obtains the
462
+ agent handle as a result of that event being emitted; the same applies to `session-created` for session-level
463
+ subscribers. Subscribe at the parent level if you need to observe creation events.
464
+
465
+ ### `TelemetryEvent` variants
466
+
467
+ All variants share `{ type: <discriminant>, timestamp: Date }` plus the fields below. Routing fields (`agentId` and
468
+ `threadId`) appear on the variants that carry them.
469
+
470
+ | `type` | Additional fields |
471
+ | -------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
472
+ | `agent-created` | `agentId`, `projectRoot`, `modelName` |
473
+ | `agent-destroyed` | `agentId` |
474
+ | `session-created` | `agentId`, `threadId` |
475
+ | `session-destroyed` | `agentId`, `threadId` |
476
+ | `chat-stream-started` | `agentId`, `threadId`, `trigger` (`'chat' \| 'submit-tool-result' \| 'approve-tool-call' \| 'decline-tool-call'`) |
477
+ | `chat-stream-completed` | `agentId`, `threadId`, `durationMs`, `usage?` |
478
+ | `chat-stream-error` | `agentId`, `threadId`, `durationMs`, `error` |
479
+ | `tool-execution-started` | `agentId`, `threadId`, `toolCallId`, `toolName` |
480
+ | `tool-execution-completed` | `agentId`, `threadId`, `toolCallId`, `toolName`, `durationMs`, `isError` |
481
+ | `tool-approval-requested` | `agentId`, `threadId`, `toolCallId`, `toolName` |
482
+ | `tool-approval-resolved` | `agentId`, `threadId`, `toolCallId`, `approved` |
483
+ | `mcp-server-discovery-started` | `agentId`, `serverName` |
484
+ | `mcp-server-discovery-completed` | `agentId`, `serverName`, `toolCount`, `durationMs` |
485
+ | `mcp-server-discovery-failed` | `agentId`, `serverName`, `durationMs`, `error` |
486
+
487
+ Every chat entry point (`chat`, `submitToolResult`, `approveToolCall`, `declineToolCall`) emits exactly one
488
+ `chat-stream-started` followed by exactly one terminal event — either `chat-stream-completed` (natural completion) or
489
+ `chat-stream-error` (in-stream error, thrown exception, or pre-stream harness rejection). The two terminal events are
490
+ mutually exclusive per stream, and both carry a real `durationMs` measured from the moment `chat-stream-started` fired.
491
+ Abandoning the iterator mid-stream emits no terminal telemetry — the stream did not complete.
492
+
493
+ ### Structured logs
494
+
495
+ | Level | Source | Message | Context |
496
+ | ----- | ------------------- | ---------------------------------------- | ----------------------------------- |
497
+ | info | `sfap-env-resolver` | `Inferred SFAP env from instanceUrl` | `inferred`, `instanceUrl` |
498
+ | info | `sfap-env-resolver` | `SF_API_ENV overrides inferred SFAP env` | `envVar`, `inferred`, `instanceUrl` |
499
+
500
+ Harness implementations may emit additional structured logs through their own `LogBus`. Those records surface to
501
+ consumers via the same `onLog` channel.
502
+
503
+ ## Development
504
+
505
+ See [DEVELOPING.md](DEVELOPING.md) for build-from-source setup, scripts, E2E testing, and packaging.
506
+
507
+ See [ARCHITECTURE.md](ARCHITECTURE.md) for implementation details on the harness abstraction. The reference harness
508
+ implementation lives in [`@salesforce/sfdx-agent-harness-mastra`](../sfdx-agent-harness-mastra).
@@ -0,0 +1,62 @@
1
+ import { type JSONWebToken, type LLMGatewayClient, type LLMGatewayClientFactory } from '@salesforce/llm-gateway-sdk';
2
+ import { type OrgConnection, type OrgConnectionFactory } from '@salesforce/agentic-common';
3
+ import type { AgentConfig } from './harness/harness-config.js';
4
+ /**
5
+ * The result of resolving an agent's org connectivity: a ready-to-use authenticated
6
+ * LLM gateway client and the underlying connection.
7
+ */
8
+ export type ResolvedConnectivity = {
9
+ /** Pre-configured and authenticated LLM gateway client for the resolved org. */
10
+ llmGatewayClient: LLMGatewayClient;
11
+ /** Authenticated org connection carrying identity and env inference. */
12
+ orgConnection: OrgConnection;
13
+ /** Self-refreshing JWT for the resolved org, used for MCP auth injection. */
14
+ orgJwt: JSONWebToken;
15
+ };
16
+ /**
17
+ * Resolves the org connectivity needed to create an agent for a given project and
18
+ * configuration.
19
+ *
20
+ * Implementations are responsible for resolving the org's authentication and constructing
21
+ * an authenticated {@link LLMGatewayClient} and {@link OrgConnection} from an
22
+ * {@link AgentConfig}.
23
+ */
24
+ export interface AgentConnectivityResolver {
25
+ /**
26
+ * Resolve the org connectivity for an agent.
27
+ *
28
+ * @param projectRoot - The root directory of the project the agent operates within.
29
+ * Used to find a project-local `target-org` when no `orgAlias` is configured.
30
+ * @param config - The agent's configuration, including optional org alias and model selection.
31
+ * @returns The resolved LLM gateway client and org connection metadata.
32
+ */
33
+ resolve(projectRoot: string, config: AgentConfig): Promise<ResolvedConnectivity>;
34
+ }
35
+ /**
36
+ * Default implementation of {@link AgentConnectivityResolver}.
37
+ *
38
+ * Delegates org resolution to {@link OrgConnectionFactory} and LLM client creation to
39
+ * {@link LLMGatewayClientFactory}. Both dependencies are injectable for testing.
40
+ */
41
+ export declare class DefaultAgentConnectivityResolver implements AgentConnectivityResolver {
42
+ private readonly connectionFactory;
43
+ private readonly gatewayClientFactory;
44
+ /**
45
+ * @param connectionFactory - Creates authenticated Salesforce org connections.
46
+ * @param gatewayClientFactory - Creates authenticated LLM gateway clients.
47
+ */
48
+ constructor(connectionFactory?: OrgConnectionFactory, gatewayClientFactory?: LLMGatewayClientFactory);
49
+ /**
50
+ * Resolves the org, constructs an authenticated LLM gateway client, and
51
+ * returns the underlying connection.
52
+ *
53
+ * If `config.orgAlias` is set, resolves that alias explicitly; otherwise falls back
54
+ * to the project-local or machine-default org via
55
+ * {@link OrgConnectionFactory.createFromTargetOrg}.
56
+ *
57
+ * @param projectRoot - Project root for project-local org resolution.
58
+ * @param config - Agent configuration with optional org alias and model ID.
59
+ * @returns The resolved LLM gateway client and connection.
60
+ */
61
+ resolve(projectRoot: string, config: AgentConfig): Promise<ResolvedConnectivity>;
62
+ }
@@ -0,0 +1,47 @@
1
+ /*
2
+ * Copyright 2026, Salesforce, Inc. All rights reserved.
3
+ * See LICENSE.txt for license terms.
4
+ */
5
+ import { DefaultLLMGatewayClientFactory, Models, createJWTFromConnection, } from '@salesforce/llm-gateway-sdk';
6
+ import { RealOrgConnectionFactory } from '@salesforce/agentic-common';
7
+ /**
8
+ * Default implementation of {@link AgentConnectivityResolver}.
9
+ *
10
+ * Delegates org resolution to {@link OrgConnectionFactory} and LLM client creation to
11
+ * {@link LLMGatewayClientFactory}. Both dependencies are injectable for testing.
12
+ */
13
+ export class DefaultAgentConnectivityResolver {
14
+ connectionFactory;
15
+ gatewayClientFactory;
16
+ /**
17
+ * @param connectionFactory - Creates authenticated Salesforce org connections.
18
+ * @param gatewayClientFactory - Creates authenticated LLM gateway clients.
19
+ */
20
+ constructor(connectionFactory = new RealOrgConnectionFactory(), gatewayClientFactory = new DefaultLLMGatewayClientFactory()) {
21
+ this.connectionFactory = connectionFactory;
22
+ this.gatewayClientFactory = gatewayClientFactory;
23
+ }
24
+ /**
25
+ * Resolves the org, constructs an authenticated LLM gateway client, and
26
+ * returns the underlying connection.
27
+ *
28
+ * If `config.orgAlias` is set, resolves that alias explicitly; otherwise falls back
29
+ * to the project-local or machine-default org via
30
+ * {@link OrgConnectionFactory.createFromTargetOrg}.
31
+ *
32
+ * @param projectRoot - Project root for project-local org resolution.
33
+ * @param config - Agent configuration with optional org alias and model ID.
34
+ * @returns The resolved LLM gateway client and connection.
35
+ */
36
+ async resolve(projectRoot, config) {
37
+ const orgConnection = config.orgAlias !== undefined
38
+ ? await this.connectionFactory.createFromOrgAliasOrUsername(config.orgAlias)
39
+ : await this.connectionFactory.createFromTargetOrg({ projectRoot });
40
+ const orgJwt = await createJWTFromConnection(orgConnection);
41
+ const llmGatewayClient = this.gatewayClientFactory.create(orgJwt, { env: orgConnection.getInferredSfApiEnv() });
42
+ const modelName = config.modelId ?? Models.getDefault().name;
43
+ llmGatewayClient.setModel(Models.getByName(modelName));
44
+ return { llmGatewayClient, orgConnection, orgJwt };
45
+ }
46
+ }
47
+ //# sourceMappingURL=agent-connectivity-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-connectivity-resolver.js","sourceRoot":"","sources":["../src/agent-connectivity-resolver.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACH,8BAA8B,EAC9B,MAAM,EACN,uBAAuB,GAI1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,wBAAwB,EAAiD,MAAM,4BAA4B,CAAC;AAoCrH;;;;;GAKG;AACH,MAAM,OAAO,gCAAgC;IAMpB;IACA;IANrB;;;OAGG;IACH,YACqB,oBAA0C,IAAI,wBAAwB,EAAE,EACxE,uBAAgD,IAAI,8BAA8B,EAAE;QADpF,sBAAiB,GAAjB,iBAAiB,CAAuD;QACxE,yBAAoB,GAApB,oBAAoB,CAAgE;IACtG,CAAC;IAEJ;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,OAAO,CAAC,WAAmB,EAAE,MAAmB;QAClD,MAAM,aAAa,GACf,MAAM,CAAC,QAAQ,KAAK,SAAS;YACzB,CAAC,CAAC,MAAM,IAAI,CAAC,iBAAiB,CAAC,4BAA4B,CAAC,MAAM,CAAC,QAAQ,CAAC;YAC5E,CAAC,CAAC,MAAM,IAAI,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;QAE5E,MAAM,MAAM,GAAG,MAAM,uBAAuB,CAAC,aAAa,CAAC,CAAC;QAC5D,MAAM,gBAAgB,GAAG,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,aAAa,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;QAEhH,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC;QAC7D,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;QAEvD,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;IACvD,CAAC;CACJ"}