@salesforce/sfdx-agent-harness-mastra 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 (40) hide show
  1. package/LICENSE.txt +21 -0
  2. package/README.md +66 -0
  3. package/dist/default-model-config-factory.d.ts +11 -0
  4. package/dist/default-model-config-factory.js +18 -0
  5. package/dist/default-model-config-factory.js.map +1 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +8 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/llmg-express-model-config-factory.d.ts +23 -0
  10. package/dist/llmg-express-model-config-factory.js +28 -0
  11. package/dist/llmg-express-model-config-factory.js.map +1 -0
  12. package/dist/mastra-event-adapter.d.ts +73 -0
  13. package/dist/mastra-event-adapter.js +204 -0
  14. package/dist/mastra-event-adapter.js.map +1 -0
  15. package/dist/mastra-harness-factory.d.ts +9 -0
  16. package/dist/mastra-harness-factory.js +17 -0
  17. package/dist/mastra-harness-factory.js.map +1 -0
  18. package/dist/mastra-harness.d.ts +292 -0
  19. package/dist/mastra-harness.js +838 -0
  20. package/dist/mastra-harness.js.map +1 -0
  21. package/dist/mastra-message-mapper.d.ts +42 -0
  22. package/dist/mastra-message-mapper.js +195 -0
  23. package/dist/mastra-message-mapper.js.map +1 -0
  24. package/dist/mastra-tool-mapper.d.ts +29 -0
  25. package/dist/mastra-tool-mapper.js +55 -0
  26. package/dist/mastra-tool-mapper.js.map +1 -0
  27. package/dist/mcp-config-mapper.d.ts +20 -0
  28. package/dist/mcp-config-mapper.js +73 -0
  29. package/dist/mcp-config-mapper.js.map +1 -0
  30. package/dist/model-config-factory.d.ts +16 -0
  31. package/dist/model-config-factory.js +6 -0
  32. package/dist/model-config-factory.js.map +1 -0
  33. package/dist/salesforce-llm-gateway.d.ts +29 -0
  34. package/dist/salesforce-llm-gateway.js +266 -0
  35. package/dist/salesforce-llm-gateway.js.map +1 -0
  36. package/dist/test/tsconfig.tsbuildinfo +1 -0
  37. package/dist/utils.d.ts +10 -0
  38. package/dist/utils.js +29 -0
  39. package/dist/utils.js.map +1 -0
  40. package/package.json +71 -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,66 @@
1
+ # @salesforce/sfdx-agent-harness-mastra
2
+
3
+ Mastra-backed `AgentHarness` implementation for [`@salesforce/sfdx-agent-sdk`](../sfdx-agent-sdk). Provides
4
+ `MastraHarnessFactory`, the entry point consumers pass to `createAgentManager`.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm install @salesforce/sfdx-agent-sdk @salesforce/sfdx-agent-harness-mastra
10
+ ```
11
+
12
+ ## Quick start
13
+
14
+ ```ts
15
+ import { createAgentManager } from '@salesforce/sfdx-agent-sdk';
16
+ import { MastraHarnessFactory } from '@salesforce/sfdx-agent-harness-mastra';
17
+
18
+ const manager = await createAgentManager('/path/to/storage', new MastraHarnessFactory());
19
+ ```
20
+
21
+ See the [`@salesforce/sfdx-agent-sdk` README](../sfdx-agent-sdk/README.md) for the full consumer-facing API. For
22
+ internal architecture, see [ARCHITECTURE.md](ARCHITECTURE.md).
23
+
24
+ ## Public API
25
+
26
+ | Export | Kind | Description |
27
+ | ------------------------------------- | --------- | ----------------------------------------------------------------------------------------- |
28
+ | `MastraHarnessFactory` | class | `HarnessFactory` that produces a Mastra-backed `AgentHarness` bound to a storage root. |
29
+ | `MastraModelConfigFactory` | interface | Strategy for creating model configurations; injected into `MastraHarnessFactory`. |
30
+ | `ResolvedModelConfig` | type | Return type of `MastraModelConfigFactory.create()` — wraps a `MastraModelConfig`. |
31
+ | `DefaultMastraModelConfigFactory` | class | Default factory using the Salesforce LLM Gateway (`SalesforceMastraModelGateway`). |
32
+ | `LLMGExpressMastraModelConfigFactory` | class | Factory for LLM Gateway Express (API-key-authenticated, OpenAI-compatible endpoint). |
33
+ | `LLMGExpressConfig` | type | Configuration for `LLMGExpressMastraModelConfigFactory` (`apiKey`, `baseUrl`, `modelId`). |
34
+
35
+ ### Using LLM Gateway Express
36
+
37
+ ```ts
38
+ import { createAgentManager } from '@salesforce/sfdx-agent-sdk';
39
+ import { MastraHarnessFactory, LLMGExpressMastraModelConfigFactory } from '@salesforce/sfdx-agent-harness-mastra';
40
+
41
+ const harnessFactory = new MastraHarnessFactory(
42
+ new LLMGExpressMastraModelConfigFactory({
43
+ apiKey: process.env.LLMG_EXPRESS_API_KEY!,
44
+ baseUrl: process.env.LLMG_EXPRESS_BASE_URL!,
45
+ modelId: 'claude-sonnet-4-20250514',
46
+ }),
47
+ );
48
+
49
+ const manager = await createAgentManager('/path/to/storage', harnessFactory);
50
+ ```
51
+
52
+ ## Development
53
+
54
+ ```bash
55
+ npm run build # TypeScript compilation
56
+ npm run test # Unit tests with coverage
57
+ npm run lint # ESLint
58
+ npm run lint:fix # Auto-fix ESLint issues
59
+ npm run format # Prettier
60
+ npm run clean # Remove build artifacts
61
+ ```
62
+
63
+ From the repo root:
64
+
65
+ - `npm run build -w @salesforce/sfdx-agent-harness-mastra`
66
+ - `npm run test -w @salesforce/sfdx-agent-harness-mastra`
@@ -0,0 +1,11 @@
1
+ import type { LLMGatewayClient } from '@salesforce/llm-gateway-sdk';
2
+ import type { MastraModelConfigFactory, ResolvedModelConfig } from './model-config-factory.js';
3
+ /**
4
+ * Default model configuration factory that uses the Salesforce LLM Gateway.
5
+ *
6
+ * Wraps the LLMGatewayClient in a SalesforceMastraModelGateway and calls
7
+ * resolveLanguageModel() to produce the LanguageModelV2 that Mastra consumes.
8
+ */
9
+ export declare class DefaultMastraModelConfigFactory implements MastraModelConfigFactory {
10
+ create(llmGatewayClient: LLMGatewayClient): ResolvedModelConfig;
11
+ }
@@ -0,0 +1,18 @@
1
+ /*
2
+ * Copyright 2026, Salesforce, Inc. All rights reserved.
3
+ * See LICENSE.txt for license terms.
4
+ */
5
+ import { SalesforceMastraModelGateway } from './salesforce-llm-gateway.js';
6
+ /**
7
+ * Default model configuration factory that uses the Salesforce LLM Gateway.
8
+ *
9
+ * Wraps the LLMGatewayClient in a SalesforceMastraModelGateway and calls
10
+ * resolveLanguageModel() to produce the LanguageModelV2 that Mastra consumes.
11
+ */
12
+ export class DefaultMastraModelConfigFactory {
13
+ create(llmGatewayClient) {
14
+ const agentGateway = new SalesforceMastraModelGateway(llmGatewayClient);
15
+ return { model: agentGateway.resolveLanguageModel() };
16
+ }
17
+ }
18
+ //# sourceMappingURL=default-model-config-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-model-config-factory.js","sourceRoot":"","sources":["../src/default-model-config-factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,4BAA4B,EAAE,MAAM,6BAA6B,CAAC;AAE3E;;;;;GAKG;AACH,MAAM,OAAO,+BAA+B;IACxC,MAAM,CAAC,gBAAkC;QACrC,MAAM,YAAY,GAAG,IAAI,4BAA4B,CAAC,gBAAgB,CAAC,CAAC;QACxE,OAAO,EAAE,KAAK,EAAE,YAAY,CAAC,oBAAoB,EAAE,EAAE,CAAC;IAC1D,CAAC;CACJ"}
@@ -0,0 +1,4 @@
1
+ export { MastraHarnessFactory } from './mastra-harness-factory.js';
2
+ export type { MastraModelConfigFactory, ResolvedModelConfig } from './model-config-factory.js';
3
+ export { DefaultMastraModelConfigFactory } from './default-model-config-factory.js';
4
+ export { LLMGExpressMastraModelConfigFactory, type LLMGExpressConfig } from './llmg-express-model-config-factory.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ /*
2
+ * Copyright 2026, Salesforce, Inc. All rights reserved.
3
+ * See LICENSE.txt for license terms.
4
+ */
5
+ export { MastraHarnessFactory } from './mastra-harness-factory.js';
6
+ export { DefaultMastraModelConfigFactory } from './default-model-config-factory.js';
7
+ export { LLMGExpressMastraModelConfigFactory } from './llmg-express-model-config-factory.js';
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAEnE,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AACpF,OAAO,EAAE,mCAAmC,EAA0B,MAAM,wCAAwC,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { LLMGatewayClient } from '@salesforce/llm-gateway-sdk';
2
+ import type { MastraModelConfigFactory, ResolvedModelConfig } from './model-config-factory.js';
3
+ export interface LLMGExpressConfig {
4
+ /** API key for authenticating with LLM Gateway Express. */
5
+ apiKey: string;
6
+ /** Base URL of the OpenAI-compatible endpoint. */
7
+ baseUrl: string;
8
+ /** Model identifier at the endpoint (e.g., 'claude-sonnet-4-20250514'). */
9
+ modelId: string;
10
+ }
11
+ /**
12
+ * Model configuration factory for LLM Gateway Express (non-production,
13
+ * API-key-authenticated, OpenAI-compatible endpoint).
14
+ *
15
+ * This factory ignores the LLMGatewayClient parameter entirely and produces
16
+ * a Mastra OpenAICompatibleConfig that Mastra resolves internally using its
17
+ * built-in OpenAI-compatible provider support.
18
+ */
19
+ export declare class LLMGExpressMastraModelConfigFactory implements MastraModelConfigFactory {
20
+ private readonly config;
21
+ constructor(config: LLMGExpressConfig);
22
+ create(_llmGatewayClient: LLMGatewayClient): ResolvedModelConfig;
23
+ }
@@ -0,0 +1,28 @@
1
+ /*
2
+ * Copyright 2026, Salesforce, Inc. All rights reserved.
3
+ * See LICENSE.txt for license terms.
4
+ */
5
+ /**
6
+ * Model configuration factory for LLM Gateway Express (non-production,
7
+ * API-key-authenticated, OpenAI-compatible endpoint).
8
+ *
9
+ * This factory ignores the LLMGatewayClient parameter entirely and produces
10
+ * a Mastra OpenAICompatibleConfig that Mastra resolves internally using its
11
+ * built-in OpenAI-compatible provider support.
12
+ */
13
+ export class LLMGExpressMastraModelConfigFactory {
14
+ config;
15
+ constructor(config) {
16
+ this.config = config;
17
+ }
18
+ create(_llmGatewayClient) {
19
+ const model = {
20
+ providerId: 'llmg-express',
21
+ modelId: this.config.modelId,
22
+ url: this.config.baseUrl,
23
+ apiKey: this.config.apiKey,
24
+ };
25
+ return { model };
26
+ }
27
+ }
28
+ //# sourceMappingURL=llmg-express-model-config-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"llmg-express-model-config-factory.js","sourceRoot":"","sources":["../src/llmg-express-model-config-factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAeH;;;;;;;GAOG;AACH,MAAM,OAAO,mCAAmC;IACf;IAA7B,YAA6B,MAAyB;QAAzB,WAAM,GAAN,MAAM,CAAmB;IAAG,CAAC;IAE1D,MAAM,CAAC,iBAAmC;QACtC,MAAM,KAAK,GAA2B;YAClC,UAAU,EAAE,cAAc;YAC1B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO;YAC5B,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO;YACxB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM;SAC7B,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,CAAC;IACrB,CAAC;CACJ"}
@@ -0,0 +1,73 @@
1
+ import type { ChunkType } from '@mastra/core/stream';
2
+ import { type LogBus } from '@salesforce/agentic-common';
3
+ import type { ChatEvent } from '@salesforce/sfdx-agent-sdk';
4
+ /**
5
+ * Adapts Mastra `ChunkType` stream events to our {@link ChatEvent} discriminated union.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * This adapter is intended to be used by `MastraHarness.stream()` to convert
10
+ * Mastra's framework-specific `fullStream` output into the harness-agnostic
11
+ * `eventStream` expected by `ChatSession`.
12
+ *
13
+ * ```typescript
14
+ * // Inside MastraHarness.stream():
15
+ * const output = await agent.stream(message, options);
16
+ * const adapter = new MastraEventAdapter();
17
+ *
18
+ * async function* createEventStream() {
19
+ * for await (const chunk of output.fullStream) {
20
+ * const event = adapter.toChatEvent(chunk);
21
+ * if (event) yield event;
22
+ * }
23
+ * }
24
+ * ```
25
+ *
26
+ * ### Stream Event Mapping
27
+ *
28
+ * | Mastra ChunkType | Our ChatEvent | Payload Mapping |
29
+ * | ----------------------- | ------------------------- | ------------------------------------------------------ |
30
+ * | `text-delta` | `text-delta` | `{ text }` from `payload.text` |
31
+ * | `reasoning-delta` | `reasoning-delta` | `{ text }` from `payload.text` |
32
+ * | `tool-call` | `tool-call` | `{ toolCallId, toolName, args }` |
33
+ * | `tool-call-approval` | `tool-approval-request` | `{ toolCall: { toolCallId, toolName, args } }` — stream suspends |
34
+ * | `tool-result` | `tool-result` | `{ toolCallId, toolName, result, isError: false }` |
35
+ * | `tool-error` | `tool-result` | `{ toolCallId, toolName, result: error, isError: true}`|
36
+ * | `step-start` | `step-start` | `{ stepIndex }` from step metadata |
37
+ * | `step-finish` | `step-finish` | `{ stepIndex, finishReason, usage }` from `stepResult` |
38
+ * | `finish` | `finish` | `{ finishReason, usage }` from `output` |
39
+ * | `error` / `tripwire` | `error` | `{ error, code? }` |
40
+ * | `abort` | `error` | `{ error: DOMException('AbortError'), code: 'abort' }` |
41
+ * | `start` | `start` | Symmetric counterpart to `finish` |
42
+ * | `text-start`, | *(skipped)* | Informational lifecycle events — `undefined` returned |
43
+ * | `text-end`, | | |
44
+ * | `reasoning-start`, | | |
45
+ * | `reasoning-end` | | |
46
+ * | `source`, `file`, | *(skipped)* | Known but unsupported — future ChatEvent candidates |
47
+ * | `tool-call-delta`, | | |
48
+ * | `tool-call-suspended`, | | |
49
+ * | `object`, `tool-output` | | |
50
+ * | *(all others)* | `unmapped-chunk` | `{ chunkType, rawChunk }` for observability |
51
+ *
52
+ * Stateful per stream — a new instance must be created for each `MastraHarness.stream()` call.
53
+ */
54
+ export declare class MastraEventAdapter {
55
+ private readonly logBus?;
56
+ private stepIndex;
57
+ /**
58
+ * @param logBus - Optional structured-log sink. When supplied, the adapter emits a `debug`
59
+ * log for each chunk it intentionally drops (informational lifecycle events the SDK
60
+ * doesn't model, and known-but-unsupported chunk types) so consumers can observe what's
61
+ * being filtered without it leaking into the public `ChatEvent` stream.
62
+ */
63
+ constructor(logBus?: LogBus | undefined);
64
+ /**
65
+ * Convert a Mastra stream chunk to a ChatEvent.
66
+ *
67
+ * @param chunk - A Mastra `ChunkType` from `agent.stream().fullStream`.
68
+ * @returns The corresponding {@link ChatEvent}, `undefined` for
69
+ * informational chunks that should be silently skipped, or an
70
+ * `UnmappedChunkEvent` for truly unrecognized chunk types.
71
+ */
72
+ toChatEvent(chunk: ChunkType): ChatEvent | undefined;
73
+ }
@@ -0,0 +1,204 @@
1
+ /*
2
+ * Copyright 2026, Salesforce, Inc. All rights reserved.
3
+ * See LICENSE.txt for license terms.
4
+ */
5
+ import { getErrorMessage } from '@salesforce/agentic-common';
6
+ /**
7
+ * Adapts Mastra `ChunkType` stream events to our {@link ChatEvent} discriminated union.
8
+ *
9
+ * ### Usage
10
+ *
11
+ * This adapter is intended to be used by `MastraHarness.stream()` to convert
12
+ * Mastra's framework-specific `fullStream` output into the harness-agnostic
13
+ * `eventStream` expected by `ChatSession`.
14
+ *
15
+ * ```typescript
16
+ * // Inside MastraHarness.stream():
17
+ * const output = await agent.stream(message, options);
18
+ * const adapter = new MastraEventAdapter();
19
+ *
20
+ * async function* createEventStream() {
21
+ * for await (const chunk of output.fullStream) {
22
+ * const event = adapter.toChatEvent(chunk);
23
+ * if (event) yield event;
24
+ * }
25
+ * }
26
+ * ```
27
+ *
28
+ * ### Stream Event Mapping
29
+ *
30
+ * | Mastra ChunkType | Our ChatEvent | Payload Mapping |
31
+ * | ----------------------- | ------------------------- | ------------------------------------------------------ |
32
+ * | `text-delta` | `text-delta` | `{ text }` from `payload.text` |
33
+ * | `reasoning-delta` | `reasoning-delta` | `{ text }` from `payload.text` |
34
+ * | `tool-call` | `tool-call` | `{ toolCallId, toolName, args }` |
35
+ * | `tool-call-approval` | `tool-approval-request` | `{ toolCall: { toolCallId, toolName, args } }` — stream suspends |
36
+ * | `tool-result` | `tool-result` | `{ toolCallId, toolName, result, isError: false }` |
37
+ * | `tool-error` | `tool-result` | `{ toolCallId, toolName, result: error, isError: true}`|
38
+ * | `step-start` | `step-start` | `{ stepIndex }` from step metadata |
39
+ * | `step-finish` | `step-finish` | `{ stepIndex, finishReason, usage }` from `stepResult` |
40
+ * | `finish` | `finish` | `{ finishReason, usage }` from `output` |
41
+ * | `error` / `tripwire` | `error` | `{ error, code? }` |
42
+ * | `abort` | `error` | `{ error: DOMException('AbortError'), code: 'abort' }` |
43
+ * | `start` | `start` | Symmetric counterpart to `finish` |
44
+ * | `text-start`, | *(skipped)* | Informational lifecycle events — `undefined` returned |
45
+ * | `text-end`, | | |
46
+ * | `reasoning-start`, | | |
47
+ * | `reasoning-end` | | |
48
+ * | `source`, `file`, | *(skipped)* | Known but unsupported — future ChatEvent candidates |
49
+ * | `tool-call-delta`, | | |
50
+ * | `tool-call-suspended`, | | |
51
+ * | `object`, `tool-output` | | |
52
+ * | *(all others)* | `unmapped-chunk` | `{ chunkType, rawChunk }` for observability |
53
+ *
54
+ * Stateful per stream — a new instance must be created for each `MastraHarness.stream()` call.
55
+ */
56
+ export class MastraEventAdapter {
57
+ logBus;
58
+ stepIndex = 0;
59
+ /**
60
+ * @param logBus - Optional structured-log sink. When supplied, the adapter emits a `debug`
61
+ * log for each chunk it intentionally drops (informational lifecycle events the SDK
62
+ * doesn't model, and known-but-unsupported chunk types) so consumers can observe what's
63
+ * being filtered without it leaking into the public `ChatEvent` stream.
64
+ */
65
+ constructor(logBus) {
66
+ this.logBus = logBus;
67
+ }
68
+ /**
69
+ * Convert a Mastra stream chunk to a ChatEvent.
70
+ *
71
+ * @param chunk - A Mastra `ChunkType` from `agent.stream().fullStream`.
72
+ * @returns The corresponding {@link ChatEvent}, `undefined` for
73
+ * informational chunks that should be silently skipped, or an
74
+ * `UnmappedChunkEvent` for truly unrecognized chunk types.
75
+ */
76
+ toChatEvent(chunk) {
77
+ switch (chunk.type) {
78
+ case 'text-delta':
79
+ return { type: 'text-delta', text: chunk.payload.text };
80
+ case 'reasoning-delta':
81
+ return { type: 'reasoning-delta', text: chunk.payload.text };
82
+ case 'tool-call':
83
+ return {
84
+ type: 'tool-call',
85
+ toolCallId: chunk.payload.toolCallId,
86
+ toolName: chunk.payload.toolName,
87
+ args: (chunk.payload.args ?? {}),
88
+ };
89
+ case 'tool-call-approval':
90
+ return {
91
+ type: 'tool-approval-request',
92
+ toolCall: {
93
+ toolCallId: chunk.payload.toolCallId,
94
+ toolName: chunk.payload.toolName,
95
+ args: chunk.payload.args,
96
+ },
97
+ };
98
+ case 'tool-result':
99
+ return {
100
+ type: 'tool-result',
101
+ toolCallId: chunk.payload.toolCallId,
102
+ toolName: chunk.payload.toolName,
103
+ result: chunk.payload.result,
104
+ isError: false,
105
+ };
106
+ case 'tool-error':
107
+ return {
108
+ type: 'tool-result',
109
+ toolCallId: chunk.payload.toolCallId,
110
+ toolName: chunk.payload.toolName,
111
+ result: getErrorMessage(chunk.payload.error),
112
+ isError: true,
113
+ };
114
+ case 'step-start':
115
+ return { type: 'step-start', stepIndex: this.stepIndex++ };
116
+ case 'step-finish':
117
+ return {
118
+ type: 'step-finish',
119
+ stepIndex: Math.max(this.stepIndex - 1, 0),
120
+ finishReason: mapFinishReason(chunk.payload.stepResult.reason),
121
+ usage: mapUsage(chunk.payload.output.usage),
122
+ };
123
+ case 'finish': {
124
+ const rawReason = chunk.payload.stepResult.reason;
125
+ // Mastra/AI SDK have no dedicated 'max-steps' finish reason. When the step
126
+ // limit is hit, Mastra terminates the loop and reports the LLM's last reason
127
+ // — 'tool-calls' — because the model wanted to invoke tools but the loop was
128
+ // killed before they could execute. A terminal `finish` with 'tool-calls' can
129
+ // ONLY occur during truncation; normal tool-call progress produces `step-finish`
130
+ // (the loop continues). This positional invariant is the detection mechanism.
131
+ const event = {
132
+ type: 'finish',
133
+ finishReason: rawReason === 'tool-calls' ? 'max-steps' : mapFinishReason(rawReason),
134
+ usage: mapUsage(chunk.payload.output.usage),
135
+ };
136
+ this.stepIndex = 0;
137
+ return event;
138
+ }
139
+ case 'error': {
140
+ const rawError = chunk.payload.error;
141
+ return {
142
+ type: 'error',
143
+ error: rawError instanceof Error ? rawError : new Error(String(rawError)),
144
+ };
145
+ }
146
+ case 'tripwire':
147
+ return {
148
+ type: 'error',
149
+ error: new Error(chunk.payload.reason),
150
+ code: 'tripwire',
151
+ };
152
+ case 'abort':
153
+ return {
154
+ type: 'error',
155
+ error: new DOMException('The stream was aborted.', 'AbortError'),
156
+ code: 'abort',
157
+ };
158
+ case 'start':
159
+ return { type: 'start' };
160
+ // Informational lifecycle chunks from the harness with no semantic
161
+ // equivalent in our harness-agnostic ChatEvent model. Silently dropped.
162
+ case 'text-start':
163
+ case 'text-end':
164
+ case 'reasoning-start':
165
+ case 'reasoning-end':
166
+ this.logBus?.debug('Skipping informational Mastra chunk', { chunkType: chunk.type });
167
+ return undefined;
168
+ // Known harness chunk types not yet supported in the SDK's ChatEvent
169
+ // model. Silently dropped to avoid leaking harness internals via
170
+ // unmapped-chunk. Candidates for future ChatEvent variants when the
171
+ // corresponding features (citations, file generation, tool arg
172
+ // streaming, tool suspension, structured output) are supported.
173
+ case 'source':
174
+ case 'file':
175
+ case 'tool-call-delta':
176
+ case 'tool-call-input-streaming-start':
177
+ case 'tool-call-input-streaming-end':
178
+ case 'tool-call-suspended':
179
+ case 'object':
180
+ case 'tool-output':
181
+ this.logBus?.debug('Skipping unsupported Mastra chunk type', { chunkType: chunk.type });
182
+ return undefined;
183
+ default:
184
+ return { type: 'unmapped-chunk', chunkType: chunk.type, rawChunk: chunk };
185
+ }
186
+ }
187
+ }
188
+ function mapFinishReason(reason) {
189
+ if (reason === 'unknown')
190
+ return 'other';
191
+ return reason;
192
+ }
193
+ function mapUsage(usage) {
194
+ if (!usage)
195
+ return undefined;
196
+ return {
197
+ inputTokens: usage.inputTokens ?? undefined,
198
+ outputTokens: usage.outputTokens ?? undefined,
199
+ totalTokens: usage.totalTokens ?? undefined,
200
+ reasoningTokens: usage.reasoningTokens,
201
+ cachedInputTokens: usage.cachedInputTokens,
202
+ };
203
+ }
204
+ //# sourceMappingURL=mastra-event-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra-event-adapter.js","sourceRoot":"","sources":["../src/mastra-event-adapter.ts"],"names":[],"mappings":"AAAA;;;GA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AC;YACrC,KAAK,qBAAqB,CAAC;YAC3B,KAAK,QAAQ,CAAC;YACd,KAAK,aAAa;gBACd,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,wCAAwC,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;gBACxF,OAAO,SAAS,CAAC;YAErB;gBACI,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;QAClF,CAAC;IACL,CAAC;CACJ;AAED,SAAS,eAAe,CAAC,MAAc;IACnC,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC;IACzC,OAAO,MAAsB,CAAC;AAClC,CAAC;AAED,SAAS,QAAQ,CAAC,KAAqC;IACnD,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO;QACH,WAAW,EAAE,KAAK,CAAC,WAAW,IAAI,SAAS;QAC3C,YAAY,EAAE,KAAK,CAAC,YAAY,IAAI,SAAS;QAC7C,WAAW,EAAE,KAAK,CAAC,WAAW,IAAI,SAAS;QAC3C,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;KAC7C,CAAC;AACN,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { AgentHarness, HarnessFactory } from '@salesforce/sfdx-agent-sdk';
2
+ import type { MastraModelConfigFactory } from './model-config-factory.js';
3
+ export declare class MastraHarnessFactory implements HarnessFactory {
4
+ private readonly modelConfigFactory?;
5
+ readonly harnessId = "mastra";
6
+ readonly protocolVersion = 1;
7
+ constructor(modelConfigFactory?: MastraModelConfigFactory | undefined);
8
+ create(storageRootFolder: string): Promise<AgentHarness>;
9
+ }
@@ -0,0 +1,17 @@
1
+ /*
2
+ * Copyright 2026, Salesforce, Inc. All rights reserved.
3
+ * See LICENSE.txt for license terms.
4
+ */
5
+ import { MastraHarness } from './mastra-harness.js';
6
+ export class MastraHarnessFactory {
7
+ modelConfigFactory;
8
+ harnessId = 'mastra';
9
+ protocolVersion = 1;
10
+ constructor(modelConfigFactory) {
11
+ this.modelConfigFactory = modelConfigFactory;
12
+ }
13
+ async create(storageRootFolder) {
14
+ return new MastraHarness(storageRootFolder, this.modelConfigFactory);
15
+ }
16
+ }
17
+ //# sourceMappingURL=mastra-harness-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra-harness-factory.js","sourceRoot":"","sources":["../src/mastra-harness-factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,MAAM,OAAO,oBAAoB;IAIA;IAHpB,SAAS,GAAG,QAAQ,CAAC;IACrB,eAAe,GAAG,CAAC,CAAC;IAE7B,YAA6B,kBAA6C;QAA7C,uBAAkB,GAAlB,kBAAkB,CAA2B;IAAG,CAAC;IAE9E,KAAK,CAAC,MAAM,CAAC,iBAAyB;QAClC,OAAO,IAAI,aAAa,CAAC,iBAAiB,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;IACzE,CAAC;CACJ"}