@salesforce/agents 0.20.0 → 0.21.1

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 (47) hide show
  1. package/README.md +2 -0
  2. package/lib/agent.d.ts +25 -86
  3. package/lib/agent.js +90 -310
  4. package/lib/agent.js.map +1 -1
  5. package/lib/agentTest.js +1 -1
  6. package/lib/agentTestResults.js +1 -1
  7. package/lib/agentTester.js +1 -1
  8. package/lib/agents/agentBase.d.ts +77 -0
  9. package/lib/agents/agentBase.js +106 -0
  10. package/lib/agents/agentBase.js.map +1 -0
  11. package/lib/agents/productionAgent.d.ts +57 -0
  12. package/lib/agents/productionAgent.js +368 -0
  13. package/lib/agents/productionAgent.js.map +1 -0
  14. package/lib/agents/scriptAgent.d.ts +69 -0
  15. package/lib/agents/scriptAgent.js +463 -0
  16. package/lib/agents/scriptAgent.js.map +1 -0
  17. package/lib/{agentPublisher.d.ts → agents/scriptAgentPublisher.d.ts} +23 -10
  18. package/lib/{agentPublisher.js → agents/scriptAgentPublisher.js} +42 -17
  19. package/lib/agents/scriptAgentPublisher.js.map +1 -0
  20. package/lib/apexUtils.js +1 -1
  21. package/lib/index.d.ts +4 -5
  22. package/lib/index.js +8 -10
  23. package/lib/index.js.map +1 -1
  24. package/lib/maybe-mock.js +1 -1
  25. package/lib/templates/agentScriptTemplate.d.ts +9 -0
  26. package/lib/templates/agentScriptTemplate.js +149 -0
  27. package/lib/templates/agentScriptTemplate.js.map +1 -0
  28. package/lib/types.d.ts +44 -13
  29. package/lib/types.js +1 -1
  30. package/lib/types.js.map +1 -1
  31. package/lib/utils.d.ts +68 -7
  32. package/lib/utils.js +215 -20
  33. package/lib/utils.js.map +1 -1
  34. package/package.json +3 -3
  35. package/lib/agentPreview.d.ts +0 -78
  36. package/lib/agentPreview.js +0 -258
  37. package/lib/agentPreview.js.map +0 -1
  38. package/lib/agentPreviewBase.d.ts +0 -59
  39. package/lib/agentPreviewBase.js +0 -55
  40. package/lib/agentPreviewBase.js.map +0 -1
  41. package/lib/agentPublisher.js.map +0 -1
  42. package/lib/agentSimulate.d.ts +0 -79
  43. package/lib/agentSimulate.js +0 -297
  44. package/lib/agentSimulate.js.map +0 -1
  45. package/lib/agentTrace.d.ts +0 -23
  46. package/lib/agentTrace.js +0 -47
  47. package/lib/agentTrace.js.map +0 -1
@@ -0,0 +1,69 @@
1
+ import { SfProject } from '@salesforce/core';
2
+ import { type AgentPreviewEndResponse, AgentPreviewInterface, type AgentPreviewSendResponse, type CompileAgentScriptResponse, ExtendedAgentJobSpec, PlannerResponse, PreviewMetadata, PublishAgent, ScriptAgentOptions } from '../types';
3
+ import { TranscriptEntry } from '../utils';
4
+ import { AgentBase } from './agentBase';
5
+ export declare class ScriptAgent extends AgentBase {
6
+ private options;
7
+ preview: AgentPreviewInterface & {
8
+ setMockMode: (mockMode: 'Mock' | 'Live Test') => void;
9
+ };
10
+ private mockMode;
11
+ private agentScriptContent;
12
+ private agentJson;
13
+ private apiBase;
14
+ private readonly aabDirectory;
15
+ private readonly metaContent;
16
+ constructor(options: ScriptAgentOptions);
17
+ /**
18
+ * Creates an AiAuthoringBundle directory, .script file, and -meta.xml file
19
+ *
20
+ * @returns Promise<void>
21
+ * @beta
22
+ * @param options {
23
+ * project: SfProject;
24
+ * bundleApiName: string;
25
+ * outputDir?: string;
26
+ * agentSpec?: ExtendedAgentJobSpec;
27
+ *}
28
+ */
29
+ static createAuthoringBundle(options: {
30
+ project: SfProject;
31
+ bundleApiName: string;
32
+ outputDir?: string;
33
+ agentSpec?: ExtendedAgentJobSpec;
34
+ }): Promise<void>;
35
+ refreshContent(): Promise<void>;
36
+ getTrace(planId: string): Promise<PlannerResponse>;
37
+ /**
38
+ * Compiles AgentScript returning agent JSON when successful, otherwise the compile errors are returned.
39
+ *
40
+ * @returns Promise<CompileAgentScriptResponse> The raw API response
41
+ * @beta
42
+ */
43
+ compile(): Promise<CompileAgentScriptResponse>;
44
+ /**
45
+ * Publish an AgentJson representation to the org
46
+ *
47
+ * @beta
48
+ * @returns {Promise<PublishAgentJsonResponse>} The publish response
49
+ */
50
+ publish(): Promise<PublishAgent>;
51
+ getHistoryFromDisc(sessionId?: string): Promise<{
52
+ metadata: PreviewMetadata | null;
53
+ transcript: TranscriptEntry[];
54
+ traces: PlannerResponse[];
55
+ }>;
56
+ /**
57
+ * Ending is not required
58
+ * this will save all the transcripts to disc
59
+ *
60
+ * @returns `AgentPreviewEndResponse`
61
+ */
62
+ endSession(): Promise<AgentPreviewEndResponse>;
63
+ getAgentIdForStorage(): string;
64
+ protected canApexDebug(): boolean;
65
+ protected handleApexDebuggingSetup(): Promise<void>;
66
+ protected sendMessage(message: string): Promise<AgentPreviewSendResponse>;
67
+ private setMockMode;
68
+ private startPreview;
69
+ }
@@ -0,0 +1,463 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ScriptAgent = void 0;
37
+ /*
38
+ * Copyright 2026, Salesforce, Inc.
39
+ *
40
+ * Licensed under the Apache License, Version 2.0 (the "License");
41
+ * you may not use this file except in compliance with the License.
42
+ * You may obtain a copy of the License at
43
+ *
44
+ * http://www.apache.org/licenses/LICENSE-2.0
45
+ *
46
+ * Unless required by applicable law or agreed to in writing, software
47
+ * distributed under the License is distributed on an "AS IS" BASIS,
48
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
49
+ * See the License for the specific language governing permissions and
50
+ * limitations under the License.
51
+ */
52
+ const node_fs_1 = __importStar(require("node:fs"));
53
+ const node_path_1 = require("node:path");
54
+ const promises_1 = require("node:fs/promises");
55
+ const node_crypto_1 = require("node:crypto");
56
+ const core_1 = require("@salesforce/core");
57
+ const kit_1 = require("@salesforce/kit");
58
+ const utils_1 = require("../utils");
59
+ const apexUtils_1 = require("../apexUtils");
60
+ const agentScriptTemplate_1 = require("../templates/agentScriptTemplate");
61
+ const scriptAgentPublisher_1 = require("./scriptAgentPublisher");
62
+ const agentBase_1 = require("./agentBase");
63
+ class ScriptAgent extends agentBase_1.AgentBase {
64
+ options;
65
+ preview;
66
+ mockMode = 'Mock';
67
+ agentScriptContent;
68
+ agentJson;
69
+ apiBase = `https://${(0, utils_1.getEndpoint)()}api.salesforce.com/einstein/ai-agent`;
70
+ aabDirectory;
71
+ metaContent;
72
+ constructor(options) {
73
+ super(options.connection);
74
+ this.options = options;
75
+ this.options = options;
76
+ // Find the AAB directory using the project
77
+ const projectDirs = options.project.getPackageDirectories();
78
+ const searchDirs = projectDirs.map((pkgDir) => pkgDir.fullPath);
79
+ const foundDirectory = (0, utils_1.findAuthoringBundle)(searchDirs, options.aabName);
80
+ if (!foundDirectory) {
81
+ throw core_1.SfError.create({
82
+ name: 'AABNotFound',
83
+ message: `Cannot find an authoring bundle named '${options.aabName}' in the project. Searched in: ${searchDirs.join(', ')}`,
84
+ });
85
+ }
86
+ this.aabDirectory = foundDirectory;
87
+ // Set initial name from AAB name (will be updated when agent is compiled)
88
+ this.name = options.aabName;
89
+ // Load the .agent file
90
+ this.agentScriptContent = node_fs_1.default.readFileSync((0, node_path_1.join)(this.aabDirectory, `${options.aabName}.agent`), 'utf-8');
91
+ // Load and validate the bundle-meta.xml file
92
+ const bundleMetaPath = (0, node_path_1.join)(this.aabDirectory, `${options.aabName}.bundle-meta.xml`);
93
+ if (!(0, node_fs_1.existsSync)(bundleMetaPath)) {
94
+ throw core_1.SfError.create({
95
+ name: 'BundleMetaNotFound',
96
+ message: `Cannot find bundle-meta.xml file for '${options.aabName}' at ${bundleMetaPath}`,
97
+ });
98
+ }
99
+ this.metaContent = node_fs_1.default.readFileSync(bundleMetaPath, 'utf-8');
100
+ this.preview = {
101
+ start: (mockMode, apexDebugging) => this.startPreview(mockMode, apexDebugging),
102
+ send: (message) => this.sendMessage(message),
103
+ getAllTraces: () => this.getAllTracesFromDisc(),
104
+ end: () => this.endSession(),
105
+ saveSession: (outputDir) => this.saveSessionTo(outputDir),
106
+ setMockMode: (mockMode) => this.setMockMode(mockMode),
107
+ setApexDebugging: (apexDebugging) => this.setApexDebugging(apexDebugging),
108
+ };
109
+ }
110
+ /**
111
+ * Creates an AiAuthoringBundle directory, .script file, and -meta.xml file
112
+ *
113
+ * @returns Promise<void>
114
+ * @beta
115
+ * @param options {
116
+ * project: SfProject;
117
+ * bundleApiName: string;
118
+ * outputDir?: string;
119
+ * agentSpec?: ExtendedAgentJobSpec;
120
+ *}
121
+ */
122
+ static async createAuthoringBundle(options) {
123
+ // this will eventually be done via AI in the org, but for now, we're hardcoding a valid .agent file boilerplate response
124
+ const agentScript = (0, agentScriptTemplate_1.generateAgentScript)(options.bundleApiName, options.agentSpec);
125
+ // Get default output directory if not specified
126
+ const targetOutputDir = (0, node_path_1.join)(options.outputDir ?? (0, node_path_1.join)(options.project.getDefaultPackage().fullPath, 'main', 'default'), 'aiAuthoringBundles', options.bundleApiName);
127
+ (0, node_fs_1.mkdirSync)(targetOutputDir, { recursive: true });
128
+ // Generate file paths
129
+ const agentPath = (0, node_path_1.join)(targetOutputDir, `${options.bundleApiName}.agent`);
130
+ const metaXmlPath = (0, node_path_1.join)(targetOutputDir, `${options.bundleApiName}.bundle-meta.xml`);
131
+ // Write Agent file
132
+ await (0, promises_1.writeFile)(agentPath, agentScript);
133
+ // Write meta.xml file
134
+ const metaXml = `<?xml version="1.0" encoding="UTF-8"?>
135
+ <AiAuthoringBundle xmlns="http://soap.sforce.com/2006/04/metadata">
136
+ <bundleType>AGENT</bundleType>
137
+ </AiAuthoringBundle>`;
138
+ await (0, promises_1.writeFile)(metaXmlPath, metaXml);
139
+ }
140
+ async refreshContent() {
141
+ this.agentScriptContent = await node_fs_1.default.promises.readFile((0, node_path_1.join)(this.aabDirectory, `${this.options.aabName}.agent`), 'utf-8');
142
+ await this.compile();
143
+ }
144
+ async getTrace(planId) {
145
+ try {
146
+ return await this.connection.request({
147
+ method: 'GET',
148
+ url: `${this.apiBase}/v1.1/preview/sessions/${this.sessionId}/plans/${planId}`,
149
+ headers: {
150
+ 'x-client-name': 'afdx',
151
+ },
152
+ });
153
+ }
154
+ catch (error) {
155
+ const errorName = error?.name ?? '';
156
+ if (errorName.includes('404')) {
157
+ throw core_1.SfError.create({
158
+ name: 'AgentApiNotFound',
159
+ message: `Trace API returned 404. SF_TEST_API=${kit_1.env.getBoolean('SF_TEST_API') ? 'true' : 'false'} If targeting a test.api environment, set SF_TEST_API=true, otherwise it's false.`,
160
+ cause: error,
161
+ });
162
+ }
163
+ throw core_1.SfError.wrap(error);
164
+ }
165
+ }
166
+ /**
167
+ * Compiles AgentScript returning agent JSON when successful, otherwise the compile errors are returned.
168
+ *
169
+ * @returns Promise<CompileAgentScriptResponse> The raw API response
170
+ * @beta
171
+ */
172
+ async compile() {
173
+ const url = `https://${(0, utils_1.getEndpoint)()}api.salesforce.com/einstein/ai-agent/v1.1/authoring/scripts`;
174
+ const compileData = {
175
+ assets: [
176
+ {
177
+ type: 'AFScript',
178
+ name: 'AFScript',
179
+ content: this.agentScriptContent,
180
+ },
181
+ ],
182
+ afScriptVersion: '1.0.1',
183
+ };
184
+ const headers = {
185
+ 'x-client-name': 'afdx',
186
+ 'content-type': 'application/json',
187
+ };
188
+ try {
189
+ const response = await this.connection.request({
190
+ method: 'POST',
191
+ url,
192
+ headers,
193
+ body: JSON.stringify(compileData),
194
+ }, { retry: { maxRetries: 3 } });
195
+ if (response.status === 'success') {
196
+ this.agentJson = response.compiledArtifact;
197
+ // Set the display name from agentJson label, or fallback to AAB name
198
+ this.name = this.agentJson.globalConfiguration.label || this.options.aabName;
199
+ }
200
+ return response;
201
+ }
202
+ catch (error) {
203
+ const errorName = error?.name ?? '';
204
+ if (errorName.includes('404')) {
205
+ throw core_1.SfError.create({
206
+ name: 'AgentApiNotFound',
207
+ message: `Validation API returned 404. SF_TEST_API=${kit_1.env.getBoolean('SF_TEST_API') ? 'true' : 'false'} If targeting a test.api environment, set SF_TEST_API=true, otherwise it's false.`,
208
+ cause: error,
209
+ });
210
+ }
211
+ throw core_1.SfError.wrap(error);
212
+ }
213
+ }
214
+ /**
215
+ * Publish an AgentJson representation to the org
216
+ *
217
+ * @beta
218
+ * @returns {Promise<PublishAgentJsonResponse>} The publish response
219
+ */
220
+ async publish() {
221
+ if (!this.agentJson) {
222
+ await this.compile();
223
+ }
224
+ const publisher = new scriptAgentPublisher_1.ScriptAgentPublisher(this.connection, this.options.project, this.agentJson);
225
+ return publisher.publishAgentJson();
226
+ }
227
+ getHistoryFromDisc(sessionId) {
228
+ // Use provided sessionId, or fall back to this.sessionId, or let getAllHistory find the most recent
229
+ const actualSessionId = sessionId ?? this.sessionId;
230
+ return (0, utils_1.getAllHistory)(this.getAgentIdForStorage(), actualSessionId);
231
+ }
232
+ /**
233
+ * Ending is not required
234
+ * this will save all the transcripts to disc
235
+ *
236
+ * @returns `AgentPreviewEndResponse`
237
+ */
238
+ async endSession() {
239
+ if (!this.sessionId) {
240
+ return Promise.resolve({ messages: [], _links: [] });
241
+ }
242
+ if (this.historyDir) {
243
+ await (0, utils_1.appendTranscriptToHistory)({
244
+ timestamp: new Date().toISOString(),
245
+ agentId: this.getAgentIdForStorage(),
246
+ sessionId: this.sessionId,
247
+ role: 'agent',
248
+ reason: 'UserRequest',
249
+ raw: [],
250
+ }, this.historyDir);
251
+ // Update metadata with end time
252
+ await (0, utils_1.updateMetadataEndTime)(this.historyDir, new Date().toISOString(), this.planIds);
253
+ }
254
+ // Clear session data for next session
255
+ this.sessionId = undefined;
256
+ this.historyDir = undefined;
257
+ this.planIds = new Set();
258
+ return Promise.resolve({ messages: [], _links: [] });
259
+ }
260
+ getAgentIdForStorage() {
261
+ return this.options.aabName;
262
+ }
263
+ canApexDebug() {
264
+ return this.mockMode === 'Live Test';
265
+ }
266
+ async handleApexDebuggingSetup() {
267
+ // ScriptAgent doesn't need trace flag setup for Apex debugging
268
+ // Apex debugging is handled differently for script agents
269
+ // Reference this to satisfy linter
270
+ void this;
271
+ return Promise.resolve();
272
+ }
273
+ async sendMessage(message) {
274
+ if (!this.sessionId) {
275
+ throw core_1.SfError.create({ name: 'noSessionId', message: 'Agent not started, please call .start() first' });
276
+ }
277
+ const url = `${this.apiBase}/v1.1/preview/sessions/${this.sessionId}/messages`;
278
+ const body = {
279
+ message: {
280
+ sequenceId: Date.now(),
281
+ type: 'Text',
282
+ text: message,
283
+ },
284
+ variables: [],
285
+ };
286
+ try {
287
+ const start = Date.now();
288
+ // Handle Apex debugging setup if needed
289
+ if (this.apexDebugging && this.canApexDebug()) {
290
+ await this.handleApexDebuggingSetup();
291
+ }
292
+ const agentId = this.getAgentIdForStorage();
293
+ // Ensure session directory exists
294
+ if (!this.historyDir) {
295
+ this.historyDir = await (0, utils_1.getHistoryDir)(agentId, this.sessionId);
296
+ }
297
+ void (0, utils_1.appendTranscriptToHistory)({
298
+ timestamp: new Date().toISOString(),
299
+ agentId,
300
+ sessionId: this.sessionId,
301
+ role: 'user',
302
+ text: message,
303
+ }, this.historyDir);
304
+ let response;
305
+ try {
306
+ response = await this.connection.request({
307
+ method: 'POST',
308
+ url,
309
+ body: JSON.stringify(body),
310
+ headers: {
311
+ 'x-client-name': 'afdx',
312
+ },
313
+ });
314
+ }
315
+ catch (error) {
316
+ const errorName = error?.name ?? '';
317
+ if (errorName.includes('404')) {
318
+ throw core_1.SfError.create({
319
+ name: 'AgentApiNotFound',
320
+ message: `Preview Send API returned 404. SF_TEST_API=${kit_1.env.getBoolean('SF_TEST_API') ? 'true' : 'false'} If targeting a test.api environment, set SF_TEST_API=true, otherwise it's false.`,
321
+ cause: error,
322
+ });
323
+ }
324
+ throw core_1.SfError.wrap(error);
325
+ }
326
+ const planId = response.messages.at(0).planId;
327
+ this.planIds.add(planId);
328
+ await (0, utils_1.appendTranscriptToHistory)({
329
+ timestamp: new Date().toISOString(),
330
+ agentId,
331
+ sessionId: this.sessionId,
332
+ role: 'agent',
333
+ text: response.messages.at(0)?.message,
334
+ raw: response.messages,
335
+ }, this.historyDir);
336
+ // Fetch and write trace immediately if available
337
+ if (planId) {
338
+ try {
339
+ const trace = await this.getTrace(planId);
340
+ await (0, utils_1.writeTraceToHistory)(planId, trace, this.historyDir);
341
+ }
342
+ catch (error) {
343
+ throw core_1.SfError.wrap(error);
344
+ }
345
+ }
346
+ if (this.apexDebugging && this.canApexDebug()) {
347
+ const apexLog = await (0, apexUtils_1.getDebugLog)(this.connection, start, Date.now());
348
+ if (apexLog) {
349
+ response.apexDebugLog = apexLog;
350
+ }
351
+ }
352
+ return response;
353
+ }
354
+ catch (err) {
355
+ throw core_1.SfError.wrap(err);
356
+ }
357
+ }
358
+ setMockMode(mockMode) {
359
+ this.mockMode = mockMode;
360
+ }
361
+ async startPreview(mockMode, apexDebugging) {
362
+ if (!this.agentJson) {
363
+ void core_1.Lifecycle.getInstance().emit('agents:compiling', {});
364
+ await this.compile();
365
+ }
366
+ if (!this.agentJson) {
367
+ throw core_1.SfError.create({ message: 'error compiling', name: 'unable to start preview' });
368
+ }
369
+ // Use the provided mockMode parameter if given, otherwise keep the previously set one
370
+ if (mockMode !== undefined) {
371
+ this.mockMode = mockMode;
372
+ }
373
+ if (apexDebugging !== undefined) {
374
+ this.apexDebugging = apexDebugging;
375
+ }
376
+ // send bypassUser=false when the compiledAgent.globalConfiguration.defaultAgentUser is INVALID
377
+ let bypassUser = (await this.connection.query(`SELECT Id FROM USER WHERE username='${this.agentJson.globalConfiguration.defaultAgentUser}'`)).totalSize === 1;
378
+ if (bypassUser && this.agentJson.globalConfiguration.agentType === 'AgentforceEmployeeAgent') {
379
+ // another situation which bypassUser = false, is when previewing an agent script, with a valid default_agent_user, and it's an AgentforceEmployeeAgent type
380
+ bypassUser = false;
381
+ }
382
+ const agentDefinition = this.agentJson;
383
+ agentDefinition.agentVersion.developerName = this.metaContent.match(/<target>.*(v\d+)<\/target>/)?.at(1) ?? 'v0';
384
+ const body = {
385
+ agentDefinition,
386
+ enableSimulationMode: this.mockMode === 'Mock',
387
+ externalSessionKey: (0, node_crypto_1.randomUUID)(),
388
+ instanceConfig: {
389
+ endpoint: this.options.connection.instanceUrl,
390
+ },
391
+ variables: [],
392
+ parameters: {},
393
+ streamingCapabilities: {
394
+ chunkTypes: ['Text', 'LightningChunk'],
395
+ },
396
+ richContentCapabilities: {},
397
+ bypassUser,
398
+ executionHistory: [],
399
+ conversationContext: [],
400
+ };
401
+ try {
402
+ void core_1.Lifecycle.getInstance().emit('agents:simulation-starting', {});
403
+ let response;
404
+ try {
405
+ response = await this.connection.request({
406
+ method: 'POST',
407
+ url: `${this.apiBase}/v1.1/preview/sessions`,
408
+ headers: {
409
+ 'x-attributed-client': 'no-builder', // <- removes markdown from responses
410
+ 'x-client-name': 'afdx',
411
+ },
412
+ body: JSON.stringify(body),
413
+ }, { retry: { maxRetries: 3 } });
414
+ }
415
+ catch (error) {
416
+ const errorName = error?.name ?? '';
417
+ if (errorName.includes('404')) {
418
+ throw core_1.SfError.create({
419
+ name: 'AgentApiNotFound',
420
+ message: `Preview Start API returned 404. SF_TEST_API=${kit_1.env.getBoolean('SF_TEST_API') ? 'true' : 'false'} If targeting a test.api environment, set SF_TEST_API=true, otherwise it's false.`,
421
+ cause: error,
422
+ });
423
+ }
424
+ throw core_1.SfError.wrap(error);
425
+ }
426
+ this.sessionId = response.sessionId;
427
+ const agentIdForStorage = this.options.aabName;
428
+ // Initialize session directory and write initial data
429
+ // Session directory structure:
430
+ // .sfdx/agents/<agentId>/sessions/<sessionId>/
431
+ // ├── transcript.jsonl # All transcript entries (one per line)
432
+ // ├── traces/ # Individual trace files
433
+ // │ ├── <planId1>.json
434
+ // │ └── <planId2>.json
435
+ // └── metadata.json # Session metadata (start time, end time, planIds, etc.)
436
+ this.historyDir = await (0, utils_1.getHistoryDir)(agentIdForStorage, response.sessionId);
437
+ // Write initial agent messages immediately
438
+ await (0, utils_1.appendTranscriptToHistory)({
439
+ timestamp: new Date().toISOString(),
440
+ agentId: agentIdForStorage,
441
+ sessionId: response.sessionId,
442
+ role: 'agent',
443
+ text: response.messages.map((m) => m.message).join('\n'),
444
+ raw: response.messages,
445
+ }, this.historyDir);
446
+ // Write initial metadata
447
+ await (0, utils_1.writeMetaFileToHistory)(this.historyDir, {
448
+ sessionId: response.sessionId,
449
+ agentId: agentIdForStorage,
450
+ startTime: new Date().toISOString(),
451
+ apexDebugging: this.apexDebugging,
452
+ mockMode: this.mockMode,
453
+ planIds: [],
454
+ });
455
+ return response;
456
+ }
457
+ catch (err) {
458
+ throw core_1.SfError.wrap(err);
459
+ }
460
+ }
461
+ }
462
+ exports.ScriptAgent = ScriptAgent;
463
+ //# sourceMappingURL=scriptAgent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scriptAgent.js","sourceRoot":"","sources":["../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import { type AgentJson, type PublishAgent } from '../types';
3
3
  /**
4
4
  * Service class responsible for publishing agents to Salesforce orgs
5
5
  */
6
- export declare class AgentPublisher {
6
+ export declare class ScriptAgentPublisher {
7
7
  private readonly maybeMock;
8
- private connection;
8
+ private readonly connection;
9
9
  private project;
10
- private agentJson;
11
- private developerName;
12
- private bundleMetaPath;
10
+ private readonly agentJson;
11
+ private readonly developerName;
12
+ private readonly bundleMetaPath;
13
13
  private bundleDir;
14
+ /**
15
+ * Original connection username, stored to create fresh connections for metadata operations.
16
+ * This ensures metadata operations (retrieve/deploy) use a standard connection that hasn't
17
+ * been upgraded with JWT, which is required for SOAP API operations.
18
+ */
19
+ private readonly originalUsername;
14
20
  private API_URL;
15
21
  private readonly API_HEADERS;
16
22
  /**
@@ -18,6 +24,7 @@ export declare class AgentPublisher {
18
24
  *
19
25
  * @param connection The connection to the Salesforce org
20
26
  * @param project The Salesforce project
27
+ * @param agentJson
21
28
  */
22
29
  constructor(connection: Connection, project: SfProject, agentJson: AgentJson);
23
30
  /**
@@ -26,6 +33,14 @@ export declare class AgentPublisher {
26
33
  * @returns Promise<PublishAgent> The publish response
27
34
  */
28
35
  publishAgentJson(): Promise<PublishAgent>;
36
+ /**
37
+ * Creates a fresh standard connection for metadata operations (retrieve/deploy).
38
+ * This ensures metadata operations use a connection that hasn't been upgraded with JWT,
39
+ * which is required for SOAP API operations.
40
+ *
41
+ * @returns A fresh Connection instance with standard authentication
42
+ */
43
+ private createStandardConnection;
29
44
  /**
30
45
  * Validates and extracts the developer name from the agent configuration,
31
46
  * and locates the corresponding authoring bundle directory and metadata file.
@@ -41,8 +56,7 @@ export declare class AgentPublisher {
41
56
  /**
42
57
  * Retrieve the agent metadata from the org after publishing
43
58
  *
44
- * @param developerName The developer name of the agent
45
- * @param originalConnection The original connection to use for retrieval
59
+ * @param botVersionName The bot version name
46
60
  */
47
61
  private retrieveAgentMetadata;
48
62
  /**
@@ -61,9 +75,8 @@ export declare class AgentPublisher {
61
75
  * The target attribute is required for deployment but should not remain in the
62
76
  * local source files after deployment.
63
77
  *
64
- * @param botVersionId The bot version ID used to construct the target attribute
65
- *
66
78
  * @throws SfError if the deployment fails or if there are component deployment errors
79
+ * @param botVersionName
67
80
  */
68
81
  private deployAuthoringBundle;
69
82
  /**