@mastra/client-js 1.28.0-alpha.5 → 1.28.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.
package/dist/index.cjs CHANGED
@@ -1969,7 +1969,6 @@ var Agent = class extends BaseResource {
1969
1969
  throw new Error("No response body");
1970
1970
  }
1971
1971
  try {
1972
- let toolCalls = [];
1973
1972
  let messages = [];
1974
1973
  let streamRunId = processedParams.runId;
1975
1974
  const [streamForController, streamForProcessing] = response.body.tee();
@@ -2009,23 +2008,39 @@ var Agent = class extends BaseResource {
2009
2008
  },
2010
2009
  onFinish: async ({ finishReason, message }) => {
2011
2010
  if (finishReason === "tool-calls") {
2012
- const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
2013
- if (toolCall) {
2011
+ const toolInvocationsById = /* @__PURE__ */ new Map();
2012
+ for (const part of message?.parts ?? []) {
2013
+ if (part.type !== "tool-invocation" || !part.toolInvocation?.toolCallId) {
2014
+ continue;
2015
+ }
2014
2016
  const toolInvocationWithMetadata = message?.toolInvocations?.find(
2015
- (invocation) => invocation.toolCallId === toolCall.toolCallId
2017
+ (invocation) => invocation.toolCallId === part.toolInvocation.toolCallId
2016
2018
  );
2017
- toolCalls.push({
2019
+ toolInvocationsById.set(part.toolInvocation.toolCallId, {
2018
2020
  ...toolInvocationWithMetadata,
2019
- ...toolCall,
2020
- ...!getClientToolObservabilityContext(toolCall) && toolInvocationWithMetadata ? { observability: getClientToolObservabilityContext(toolInvocationWithMetadata) } : {}
2021
+ ...part.toolInvocation,
2022
+ ...!getClientToolObservabilityContext(part.toolInvocation) && toolInvocationWithMetadata ? { observability: getClientToolObservabilityContext(toolInvocationWithMetadata) } : {}
2021
2023
  });
2022
2024
  }
2023
- let shouldExecuteClientTool = false;
2024
- for (const toolCall2 of toolCalls) {
2025
- const clientTool = processedParams.clientTools?.[toolCall2.toolName];
2026
- if (clientTool && clientTool.execute) {
2027
- shouldExecuteClientTool = true;
2028
- const runId = streamRunId ?? toolCall2.toolCallId;
2025
+ for (const toolInvocation of message?.toolInvocations ?? []) {
2026
+ if (!toolInvocation.toolCallId) {
2027
+ continue;
2028
+ }
2029
+ toolInvocationsById.set(toolInvocation.toolCallId, {
2030
+ ...toolInvocationsById.get(toolInvocation.toolCallId),
2031
+ ...toolInvocation
2032
+ });
2033
+ }
2034
+ const executableToolCalls = [...toolInvocationsById.values()].filter((toolCall) => {
2035
+ const clientTool = processedParams.clientTools?.[toolCall.toolName];
2036
+ return Boolean(clientTool?.execute);
2037
+ });
2038
+ if (executableToolCalls.length > 0) {
2039
+ const syntheticChunks = [];
2040
+ const toolResultContents = [];
2041
+ for (const toolCall of executableToolCalls) {
2042
+ const clientTool = processedParams.clientTools?.[toolCall.toolName];
2043
+ const runId = streamRunId ?? toolCall.toolCallId;
2029
2044
  let result;
2030
2045
  let modelOutput;
2031
2046
  let observability;
@@ -2033,16 +2048,16 @@ var Agent = class extends BaseResource {
2033
2048
  try {
2034
2049
  ({ result, observability } = await executeClientToolWithObservability({
2035
2050
  clientTool,
2036
- args: toolCall2?.args,
2037
- toolName: toolCall2.toolName,
2038
- parentContext: getClientToolObservabilityContext(toolCall2),
2051
+ args: toolCall?.args,
2052
+ toolName: toolCall.toolName,
2053
+ parentContext: getClientToolObservabilityContext(toolCall),
2039
2054
  executeContext: {
2040
2055
  requestContext: processedParams.requestContext,
2041
2056
  tracingContext: { currentSpan: void 0 },
2042
2057
  agent: {
2043
2058
  agentId: this.agentId,
2044
2059
  messages: response.messages,
2045
- toolCallId: toolCall2?.toolCallId,
2060
+ toolCallId: toolCall?.toolCallId,
2046
2061
  suspend: async () => {
2047
2062
  },
2048
2063
  threadId,
@@ -2056,8 +2071,8 @@ var Agent = class extends BaseResource {
2056
2071
  runId,
2057
2072
  from: "AGENT",
2058
2073
  payload: {
2059
- toolCallId: toolCall2.toolCallId,
2060
- toolName: toolCall2.toolName,
2074
+ toolCallId: toolCall.toolCallId,
2075
+ toolName: toolCall.toolName,
2061
2076
  result,
2062
2077
  isError: false,
2063
2078
  providerExecuted: false
@@ -2069,19 +2084,31 @@ var Agent = class extends BaseResource {
2069
2084
  runId,
2070
2085
  from: "AGENT",
2071
2086
  payload: {
2072
- toolCallId: toolCall2.toolCallId,
2073
- toolName: toolCall2.toolName,
2087
+ toolCallId: toolCall.toolCallId,
2088
+ toolName: toolCall.toolName,
2074
2089
  error,
2075
- args: toolCall2?.args,
2090
+ args: toolCall?.args,
2076
2091
  providerExecuted: false
2077
2092
  }
2078
2093
  };
2079
2094
  result = { error: error instanceof Error ? error.message : String(error) };
2080
2095
  }
2081
- try {
2082
- await pipePromise;
2083
- } catch {
2084
- }
2096
+ syntheticChunks.push(synthetic);
2097
+ toolResultContents.push({
2098
+ type: "tool-result",
2099
+ toolCallId: toolCall.toolCallId,
2100
+ toolName: toolCall.toolName,
2101
+ input: toolCall.args,
2102
+ result,
2103
+ ...modelOutput != null ? { providerOptions: { mastra: { modelOutput } } } : {},
2104
+ ...observability ? { __mastraObservability: observability } : {}
2105
+ });
2106
+ }
2107
+ try {
2108
+ await pipePromise;
2109
+ } catch {
2110
+ }
2111
+ for (const synthetic of syntheticChunks) {
2085
2112
  try {
2086
2113
  const errorForSerialization = synthetic.type === "tool-error" ? synthetic.payload.error : void 0;
2087
2114
  const serializedError = errorForSerialization instanceof Error ? {
@@ -2097,55 +2124,30 @@ var Agent = class extends BaseResource {
2097
2124
  } catch (enqueueErr) {
2098
2125
  console.error("Failed to enqueue synthetic tool-result chunk:", enqueueErr);
2099
2126
  }
2100
- const lastMessageRaw = messages[messages.length - 1];
2101
- const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
2102
- const toolInvocationPart = lastMessage?.parts?.find(
2103
- (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
2104
- );
2105
- if (toolInvocationPart) {
2106
- toolInvocationPart.toolInvocation = {
2107
- ...toolInvocationPart.toolInvocation,
2108
- state: "result",
2109
- result,
2110
- ...observability ? { __mastraObservability: observability } : {}
2111
- };
2112
- if (modelOutput != null) {
2113
- const partWithMetadata = toolInvocationPart;
2114
- const existingMastra = partWithMetadata.providerMetadata?.mastra != null && typeof partWithMetadata.providerMetadata.mastra === "object" ? partWithMetadata.providerMetadata.mastra : {};
2115
- partWithMetadata.providerMetadata = {
2116
- ...partWithMetadata.providerMetadata,
2117
- mastra: { ...existingMastra, modelOutput }
2118
- };
2119
- }
2120
- }
2121
- const toolInvocation = lastMessage?.toolInvocations?.find(
2122
- (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
2127
+ }
2128
+ const toolResultMessage = {
2129
+ role: "tool",
2130
+ content: toolResultContents
2131
+ };
2132
+ const updatedMessages = threadId ? [toolResultMessage] : [
2133
+ ...Array.isArray(processedParams.messages) ? processedParams.messages : [],
2134
+ ...messages,
2135
+ toolResultMessage
2136
+ ];
2137
+ const recursionRoute = route === "resume-stream" ? "stream" : route === "resume-stream-until-idle" ? "stream-until-idle" : route;
2138
+ try {
2139
+ await this.processStreamResponse(
2140
+ {
2141
+ ...processedParams,
2142
+ messages: updatedMessages
2143
+ },
2144
+ controller,
2145
+ recursionRoute
2123
2146
  );
2124
- if (toolInvocation) {
2125
- toolInvocation.state = "result";
2126
- toolInvocation.result = result;
2127
- if (observability) {
2128
- toolInvocation.__mastraObservability = observability;
2129
- }
2130
- }
2131
- const newMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
2132
- const updatedMessages = threadId ? newMessages : [...Array.isArray(processedParams.messages) ? processedParams.messages : [], ...newMessages];
2133
- const recursionRoute = route === "resume-stream" ? "stream" : route === "resume-stream-until-idle" ? "stream-until-idle" : route;
2134
- try {
2135
- await this.processStreamResponse(
2136
- {
2137
- ...processedParams,
2138
- messages: updatedMessages
2139
- },
2140
- controller,
2141
- recursionRoute
2142
- );
2143
- } catch (error) {
2144
- console.error("Error processing recursive stream response:", error);
2145
- }
2147
+ } catch (error) {
2148
+ console.error("Error processing recursive stream response:", error);
2146
2149
  }
2147
- }
2148
- if (!shouldExecuteClientTool) {
2150
+ } else {
2149
2151
  await pipePromise;
2150
2152
  controller.close();
2151
2153
  }
@@ -2609,28 +2611,6 @@ var Agent = class extends BaseResource {
2609
2611
  }
2610
2612
  }
2611
2613
  });
2612
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
2613
- const toolInvocationPart = lastMessage?.parts?.find(
2614
- (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
2615
- );
2616
- if (toolInvocationPart) {
2617
- toolInvocationPart.toolInvocation = {
2618
- ...toolInvocationPart.toolInvocation,
2619
- state: "result",
2620
- result,
2621
- ...observability ? { __mastraObservability: observability } : {}
2622
- };
2623
- }
2624
- const toolInvocation = lastMessage?.toolInvocations?.find(
2625
- (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
2626
- );
2627
- if (toolInvocation) {
2628
- toolInvocation.state = "result";
2629
- toolInvocation.result = result;
2630
- if (observability) {
2631
- toolInvocation.__mastraObservability = observability;
2632
- }
2633
- }
2634
2614
  const writer = writable.getWriter();
2635
2615
  try {
2636
2616
  await writer.write(
@@ -2644,8 +2624,24 @@ var Agent = class extends BaseResource {
2644
2624
  } finally {
2645
2625
  writer.releaseLock();
2646
2626
  }
2647
- const newMessages = [...messages.filter((m) => m.id !== lastMessage.id), lastMessage];
2648
- const updatedMessages = threadId ? newMessages : [...Array.isArray(processedParams.messages) ? processedParams.messages : [], ...newMessages];
2627
+ const toolResultMessage = {
2628
+ role: "tool",
2629
+ content: [
2630
+ {
2631
+ type: "tool-result",
2632
+ toolCallId: toolCall2.toolCallId,
2633
+ toolName: toolCall2.toolName,
2634
+ input: toolCall2.args,
2635
+ result,
2636
+ ...observability ? { __mastraObservability: observability } : {}
2637
+ }
2638
+ ]
2639
+ };
2640
+ const updatedMessages = threadId ? [toolResultMessage] : [
2641
+ ...Array.isArray(processedParams.messages) ? processedParams.messages : [],
2642
+ ...messages,
2643
+ toolResultMessage
2644
+ ];
2649
2645
  this.processStreamResponseLegacy(
2650
2646
  {
2651
2647
  ...processedParams,
@@ -6087,17 +6083,17 @@ var Channels = class extends BaseResource {
6087
6083
  }
6088
6084
  };
6089
6085
 
6090
- // src/resources/harness.ts
6091
- var HarnessSession = class extends BaseResource {
6092
- constructor(options, harnessId, resourceId) {
6086
+ // src/resources/agent-controller.ts
6087
+ var AgentControllerSession = class extends BaseResource {
6088
+ constructor(options, controllerId, resourceId) {
6093
6089
  super(options);
6094
- this.harnessId = harnessId;
6090
+ this.controllerId = controllerId;
6095
6091
  this.resourceId = resourceId;
6096
6092
  }
6097
- harnessId;
6093
+ controllerId;
6098
6094
  resourceId;
6099
6095
  base() {
6100
- return `/harness/${encodeURIComponent(this.harnessId)}/sessions/${encodeURIComponent(this.resourceId)}`;
6096
+ return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.resourceId)}`;
6101
6097
  }
6102
6098
  /**
6103
6099
  * Create or resume this session. Pass `tags` to scope initial thread
@@ -6107,7 +6103,7 @@ var HarnessSession = class extends BaseResource {
6107
6103
  * most recent thread across the whole resource.
6108
6104
  */
6109
6105
  create(options) {
6110
- return this.request(`/harness/${encodeURIComponent(this.harnessId)}/sessions`, {
6106
+ return this.request(`/agent-controller/${encodeURIComponent(this.controllerId)}/sessions`, {
6111
6107
  method: "POST",
6112
6108
  body: { resourceId: this.resourceId, tags: options?.tags }
6113
6109
  });
@@ -6119,7 +6115,7 @@ var HarnessSession = class extends BaseResource {
6119
6115
  async subscribe(options) {
6120
6116
  const response = await this.request(`${this.base()}/stream`, { stream: true });
6121
6117
  if (!response.body) {
6122
- throw new Error("No response body for harness session stream");
6118
+ throw new Error("No response body for agent controller session stream");
6123
6119
  }
6124
6120
  const reader = response.body.getReader();
6125
6121
  const decoder = new TextDecoder();
@@ -6346,35 +6342,35 @@ var HarnessSession = class extends BaseResource {
6346
6342
  });
6347
6343
  }
6348
6344
  };
6349
- var Harness = class extends BaseResource {
6350
- constructor(options, harnessId) {
6345
+ var AgentController = class extends BaseResource {
6346
+ constructor(options, controllerId) {
6351
6347
  super(options);
6352
- this.harnessId = harnessId;
6348
+ this.controllerId = controllerId;
6353
6349
  }
6354
- harnessId;
6350
+ controllerId;
6355
6351
  basePath() {
6356
- return `/harness/${encodeURIComponent(this.harnessId)}`;
6352
+ return `/agent-controller/${encodeURIComponent(this.controllerId)}`;
6357
6353
  }
6358
- /** List the modes configured on this harness (e.g. build, plan). */
6354
+ /** List the modes configured on this agent controller (e.g. build, plan). */
6359
6355
  async listModes() {
6360
6356
  const body = await this.request(`${this.basePath()}/modes`);
6361
6357
  return body.modes;
6362
6358
  }
6363
- /** List available models on this harness (with auth status and use counts). */
6359
+ /** List available models on this agent controller (with auth status and use counts). */
6364
6360
  async listModels() {
6365
6361
  const body = await this.request(`${this.basePath()}/models`);
6366
6362
  return body.models;
6367
6363
  }
6368
- /** Get workspace status for this harness. */
6364
+ /** Get workspace status for this agent controller. */
6369
6365
  async workspaceStatus() {
6370
6366
  return this.request(`${this.basePath()}/workspace`);
6371
6367
  }
6372
6368
  /** Scope to a session bound to `resourceId` (e.g. a user or conversation id). */
6373
6369
  session(resourceId) {
6374
- return new HarnessSession(this.options, this.harnessId, resourceId);
6370
+ return new AgentControllerSession(this.options, this.controllerId, resourceId);
6375
6371
  }
6376
6372
  };
6377
- function harnessMessageText(message) {
6373
+ function agentControllerMessageText(message) {
6378
6374
  return message.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("");
6379
6375
  }
6380
6376
 
@@ -6421,21 +6417,21 @@ var MastraClient = class extends BaseResource {
6421
6417
  return new Agent(this.options, agentId, version);
6422
6418
  }
6423
6419
  /**
6424
- * Lists the harnesses hosted on the connected Mastra instance.
6425
- * @returns Promise containing an array of harness identifiers
6420
+ * Lists the agent controllers hosted on the connected Mastra instance.
6421
+ * @returns Promise containing an array of agent controller identifiers
6426
6422
  */
6427
- async listHarnesses() {
6428
- const body = await this.request("/harness");
6429
- return body.harnesses;
6423
+ async listAgentControllers() {
6424
+ const body = await this.request("/agent-controller");
6425
+ return body.agentControllers;
6430
6426
  }
6431
6427
  /**
6432
- * Scopes to a harness hosted on the connected Mastra instance. Use
6433
- * `getHarness(id).session(resourceId)` to create/resume a session, stream its
6434
- * events, and send messages.
6435
- * @param harnessId - The id the harness is registered under on Mastra
6428
+ * Scopes to an agent controller hosted on the connected Mastra instance. Use
6429
+ * `getAgentController(id).session(resourceId)` to create/resume a session,
6430
+ * stream its events, and send messages.
6431
+ * @param controllerId - The id the agent controller is registered under on Mastra
6436
6432
  */
6437
- getHarness(harnessId) {
6438
- return new Harness(this.options, harnessId);
6433
+ getAgentController(controllerId) {
6434
+ return new AgentController(this.options, controllerId);
6439
6435
  }
6440
6436
  /**
6441
6437
  * Lists memory threads with optional filtering by resourceId and/or metadata
@@ -8073,7 +8069,7 @@ Object.defineProperty(exports, "RequestContext", {
8073
8069
  exports.ClientTool = ClientTool;
8074
8070
  exports.MastraClient = MastraClient;
8075
8071
  exports.MastraClientError = MastraClientError;
8072
+ exports.agentControllerMessageText = agentControllerMessageText;
8076
8073
  exports.createTool = createTool;
8077
- exports.harnessMessageText = harnessMessageText;
8078
8074
  //# sourceMappingURL=index.cjs.map
8079
8075
  //# sourceMappingURL=index.cjs.map