assistant-stream 0.1.3 → 0.1.5

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.js CHANGED
@@ -40,7 +40,9 @@ __export(index_exports, {
40
40
  ToolExecutionStream: () => ToolExecutionStream,
41
41
  ToolResponse: () => ToolResponse,
42
42
  createAssistantStream: () => createAssistantStream,
43
- createAssistantStreamResponse: () => createAssistantStreamResponse
43
+ createAssistantStreamResponse: () => createAssistantStreamResponse,
44
+ unstable_runPendingTools: () => unstable_runPendingTools,
45
+ unstable_toolResultStream: () => toolResultStream
44
46
  });
45
47
  module.exports = __toCommonJS(index_exports);
46
48
 
@@ -62,16 +64,19 @@ var AssistantStream = {
62
64
  }
63
65
  };
64
66
 
65
- // src/core/utils/stream/merge.ts
66
- var promiseWithResolvers = () => {
67
+ // src/utils/promiseWithResolvers.ts
68
+ var promiseWithResolvers = function() {
67
69
  let resolve;
68
70
  let reject;
69
71
  const promise = new Promise((res, rej) => {
70
72
  resolve = res;
71
73
  reject = rej;
72
74
  });
75
+ if (!resolve || !reject) throw new Error("Failed to create promise");
73
76
  return { promise, resolve, reject };
74
77
  };
78
+
79
+ // src/core/utils/stream/merge.ts
75
80
  var createMergeStream = () => {
76
81
  const list = [];
77
82
  let sealed = false;
@@ -952,18 +957,8 @@ function createAssistantStream(callback) {
952
957
  }
953
958
  return controller.__internal_getReadable();
954
959
  }
955
- var promiseWithResolvers2 = function() {
956
- let resolve;
957
- let reject;
958
- const promise = new Promise((res, rej) => {
959
- resolve = res;
960
- reject = rej;
961
- });
962
- if (!resolve || !reject) throw new Error("Failed to create promise");
963
- return { promise, resolve, reject };
964
- };
965
960
  function createAssistantStreamController() {
966
- const { resolve, promise } = promiseWithResolvers2();
961
+ const { resolve, promise } = promiseWithResolvers();
967
962
  let controller;
968
963
  const stream = createAssistantStream((c) => {
969
964
  controller = c;
@@ -981,126 +976,10 @@ function createAssistantStreamResponse(callback) {
981
976
  );
982
977
  }
983
978
 
984
- // src/core/effects/ToolExecutionStream.ts
979
+ // src/utils/json/parse-partial-json-object.ts
985
980
  var import_secure_json_parse = __toESM(require("secure-json-parse"));
986
981
 
987
- // src/core/utils/withPromiseOrValue.ts
988
- function withPromiseOrValue(callback, thenHandler, catchHandler) {
989
- try {
990
- const promiseOrValue = callback();
991
- if (typeof promiseOrValue === "object" && promiseOrValue !== null && "then" in promiseOrValue) {
992
- return promiseOrValue.then(thenHandler, catchHandler);
993
- } else {
994
- thenHandler(promiseOrValue);
995
- }
996
- } catch (e) {
997
- catchHandler(e);
998
- }
999
- }
1000
-
1001
- // src/core/effects/ToolExecutionStream.ts
1002
- var ToolExecutionStream = class extends PipeableTransformStream {
1003
- constructor(toolCallback) {
1004
- const toolCallPromises = /* @__PURE__ */ new Map();
1005
- const toolCallArgsText = {};
1006
- super((readable) => {
1007
- const transform = new TransformStream({
1008
- transform(chunk, controller) {
1009
- if (chunk.type !== "part-finish" || chunk.meta.type !== "tool-call") {
1010
- controller.enqueue(chunk);
1011
- }
1012
- const type = chunk.type;
1013
- switch (type) {
1014
- case "text-delta": {
1015
- if (chunk.meta.type === "tool-call") {
1016
- const toolCallId = chunk.meta.toolCallId;
1017
- if (toolCallArgsText[toolCallId] === void 0) {
1018
- toolCallArgsText[toolCallId] = chunk.textDelta;
1019
- } else {
1020
- toolCallArgsText[toolCallId] += chunk.textDelta;
1021
- }
1022
- }
1023
- break;
1024
- }
1025
- case "tool-call-args-text-finish": {
1026
- if (chunk.meta.type !== "tool-call") break;
1027
- const { toolCallId, toolName } = chunk.meta;
1028
- const argsText = toolCallArgsText[toolCallId];
1029
- const promise = withPromiseOrValue(
1030
- () => {
1031
- if (!argsText) {
1032
- console.log(
1033
- "Encountered tool call without argsText, this should never happen"
1034
- );
1035
- throw new Error(
1036
- "Encountered tool call without argsText, this is unexpected."
1037
- );
1038
- }
1039
- let args;
1040
- try {
1041
- args = import_secure_json_parse.default.parse(argsText);
1042
- } catch (e) {
1043
- throw new Error(
1044
- `Function parameter parsing failed. ${JSON.stringify(e.message)}`
1045
- );
1046
- }
1047
- return toolCallback({
1048
- toolCallId,
1049
- toolName,
1050
- args
1051
- });
1052
- },
1053
- (c) => {
1054
- if (c === void 0) return;
1055
- controller.enqueue({
1056
- type: "result",
1057
- path: chunk.path,
1058
- artifact: c.artifact,
1059
- result: c.result,
1060
- isError: c.isError
1061
- });
1062
- },
1063
- (e) => {
1064
- controller.enqueue({
1065
- type: "result",
1066
- path: chunk.path,
1067
- result: String(e),
1068
- isError: true
1069
- });
1070
- }
1071
- );
1072
- if (promise) {
1073
- toolCallPromises.set(toolCallId, promise);
1074
- }
1075
- break;
1076
- }
1077
- case "part-finish": {
1078
- if (chunk.meta.type !== "tool-call") break;
1079
- const { toolCallId } = chunk.meta;
1080
- const toolCallPromise = toolCallPromises.get(toolCallId);
1081
- if (toolCallPromise) {
1082
- toolCallPromise.then(() => {
1083
- controller.enqueue(chunk);
1084
- });
1085
- } else {
1086
- controller.enqueue(chunk);
1087
- }
1088
- }
1089
- }
1090
- },
1091
- async flush() {
1092
- await Promise.all(toolCallPromises.values());
1093
- }
1094
- });
1095
- return readable.pipeThrough(new AssistantMetaTransformStream()).pipeThrough(transform);
1096
- });
1097
- }
1098
- };
1099
-
1100
- // src/core/utils/json/parse-partial-json-object.ts
1101
- var import_secure_json_parse2 = __toESM(require("secure-json-parse"));
1102
-
1103
- // src/core/utils/json/fix-json.ts
982
+ // src/utils/json/fix-json.ts
1104
983
  function fixJson(input) {
1105
984
  const stack = ["ROOT"];
1106
985
  let lastValidIndex = -1;
@@ -1459,17 +1338,20 @@ function fixJson(input) {
1459
1338
  return [result, path];
1460
1339
  }
1461
1340
 
1462
- // src/core/utils/json/parse-partial-json-object.ts
1341
+ // src/utils/json/parse-partial-json-object.ts
1463
1342
  var PARTIAL_JSON_OBJECT_META_SYMBOL = Symbol(
1464
1343
  "aui.parse-partial-json-object.meta"
1465
1344
  );
1345
+ var getPartialJsonObjectMeta = (obj) => {
1346
+ return obj?.[PARTIAL_JSON_OBJECT_META_SYMBOL];
1347
+ };
1466
1348
  var parsePartialJsonObject = (json) => {
1467
1349
  if (json.length === 0)
1468
1350
  return {
1469
1351
  [PARTIAL_JSON_OBJECT_META_SYMBOL]: { state: "partial", partialPath: [] }
1470
1352
  };
1471
1353
  try {
1472
- const res = import_secure_json_parse2.default.parse(json);
1354
+ const res = import_secure_json_parse.default.parse(json);
1473
1355
  if (typeof res !== "object" || res === null)
1474
1356
  throw new Error("argsText is expected to be an object");
1475
1357
  res[PARTIAL_JSON_OBJECT_META_SYMBOL] = {
@@ -1480,7 +1362,7 @@ var parsePartialJsonObject = (json) => {
1480
1362
  } catch {
1481
1363
  try {
1482
1364
  const [fixedJson, partialPath] = fixJson(json);
1483
- const res = import_secure_json_parse2.default.parse(fixedJson);
1365
+ const res = import_secure_json_parse.default.parse(fixedJson);
1484
1366
  if (typeof res !== "object" || res === null)
1485
1367
  throw new Error("argsText is expected to be an object");
1486
1368
  res[PARTIAL_JSON_OBJECT_META_SYMBOL] = {
@@ -1493,6 +1375,26 @@ var parsePartialJsonObject = (json) => {
1493
1375
  }
1494
1376
  }
1495
1377
  };
1378
+ var getFieldState = (parent, parentMeta, fieldPath) => {
1379
+ if (typeof parent !== "object" || parent === null) return parentMeta.state;
1380
+ if (parentMeta.state === "complete") return "complete";
1381
+ if (fieldPath.length === 0) return parentMeta.state;
1382
+ const [field, ...restPath] = fieldPath;
1383
+ if (!Object.prototype.hasOwnProperty.call(parent, field)) return "partial";
1384
+ const [partialField, ...restPartialPath] = parentMeta.partialPath;
1385
+ if (field !== partialField) return "complete";
1386
+ const child = parent[field];
1387
+ const childMeta = {
1388
+ state: "partial",
1389
+ partialPath: restPartialPath
1390
+ };
1391
+ return getFieldState(child, childMeta, restPath);
1392
+ };
1393
+ var getPartialJsonObjectFieldState = (obj, fieldPath) => {
1394
+ const meta = getPartialJsonObjectMeta(obj);
1395
+ if (!meta) throw new Error("unable to determine object state");
1396
+ return getFieldState(obj, meta, fieldPath.map(String));
1397
+ };
1496
1398
 
1497
1399
  // src/core/accumulators/assistant-message-accumulator.ts
1498
1400
  var createInitialMessage = () => ({
@@ -1886,7 +1788,7 @@ var AssistantMessageStream = class _AssistantMessageStream {
1886
1788
  }
1887
1789
  };
1888
1790
 
1889
- // src/core/ToolResponse.ts
1791
+ // src/core/tool/ToolResponse.ts
1890
1792
  var TOOL_RESPONSE_SYMBOL = Symbol.for("aui.tool-response");
1891
1793
  var ToolResponse = class {
1892
1794
  get [TOOL_RESPONSE_SYMBOL]() {
@@ -1904,6 +1806,521 @@ var ToolResponse = class {
1904
1806
  return typeof obj === "object" && obj !== null && TOOL_RESPONSE_SYMBOL in obj;
1905
1807
  }
1906
1808
  };
1809
+
1810
+ // src/core/tool/ToolExecutionStream.ts
1811
+ var import_secure_json_parse2 = __toESM(require("secure-json-parse"));
1812
+
1813
+ // src/core/utils/withPromiseOrValue.ts
1814
+ function withPromiseOrValue(callback, thenHandler, catchHandler) {
1815
+ try {
1816
+ const promiseOrValue = callback();
1817
+ if (typeof promiseOrValue === "object" && promiseOrValue !== null && "then" in promiseOrValue) {
1818
+ return promiseOrValue.then(thenHandler, catchHandler);
1819
+ } else {
1820
+ thenHandler(promiseOrValue);
1821
+ }
1822
+ } catch (e) {
1823
+ catchHandler(e);
1824
+ }
1825
+ }
1826
+
1827
+ // src/core/tool/ToolCallReader.ts
1828
+ function getField(obj, fieldPath) {
1829
+ let current = obj;
1830
+ for (const key of fieldPath) {
1831
+ if (current === void 0 || current === null) {
1832
+ return void 0;
1833
+ }
1834
+ current = current[key];
1835
+ }
1836
+ return current;
1837
+ }
1838
+ var GetHandle = class {
1839
+ resolve;
1840
+ reject;
1841
+ disposed = false;
1842
+ fieldPath;
1843
+ constructor(resolve, reject, fieldPath) {
1844
+ this.resolve = resolve;
1845
+ this.reject = reject;
1846
+ this.fieldPath = fieldPath;
1847
+ }
1848
+ update(args) {
1849
+ if (this.disposed) return;
1850
+ try {
1851
+ if (getPartialJsonObjectFieldState(
1852
+ args,
1853
+ this.fieldPath
1854
+ ) === "complete") {
1855
+ const value = getField(args, this.fieldPath);
1856
+ if (value !== void 0) {
1857
+ this.resolve(value);
1858
+ this.dispose();
1859
+ }
1860
+ }
1861
+ } catch (e) {
1862
+ this.reject(e);
1863
+ this.dispose();
1864
+ }
1865
+ }
1866
+ dispose() {
1867
+ this.disposed = true;
1868
+ }
1869
+ };
1870
+ var StreamValuesHandle = class {
1871
+ controller;
1872
+ disposed = false;
1873
+ fieldPath;
1874
+ constructor(controller, fieldPath) {
1875
+ this.controller = controller;
1876
+ this.fieldPath = fieldPath;
1877
+ }
1878
+ update(args) {
1879
+ if (this.disposed) return;
1880
+ try {
1881
+ const value = getField(args, this.fieldPath);
1882
+ if (value !== void 0) {
1883
+ this.controller.enqueue(value);
1884
+ }
1885
+ if (getPartialJsonObjectFieldState(
1886
+ args,
1887
+ this.fieldPath
1888
+ ) === "complete") {
1889
+ this.controller.close();
1890
+ this.dispose();
1891
+ }
1892
+ } catch (e) {
1893
+ this.controller.error(e);
1894
+ this.dispose();
1895
+ }
1896
+ }
1897
+ dispose() {
1898
+ this.disposed = true;
1899
+ }
1900
+ };
1901
+ var StreamTextHandle = class {
1902
+ controller;
1903
+ disposed = false;
1904
+ fieldPath;
1905
+ lastValue = void 0;
1906
+ constructor(controller, fieldPath) {
1907
+ this.controller = controller;
1908
+ this.fieldPath = fieldPath;
1909
+ }
1910
+ update(args) {
1911
+ if (this.disposed) return;
1912
+ try {
1913
+ const value = getField(args, this.fieldPath);
1914
+ if (value !== void 0 && typeof value === "string") {
1915
+ const delta = value.substring(this.lastValue?.length || 0);
1916
+ this.lastValue = value;
1917
+ this.controller.enqueue(delta);
1918
+ }
1919
+ if (getPartialJsonObjectFieldState(
1920
+ args,
1921
+ this.fieldPath
1922
+ ) === "complete") {
1923
+ this.controller.close();
1924
+ this.dispose();
1925
+ }
1926
+ } catch (e) {
1927
+ this.controller.error(e);
1928
+ this.dispose();
1929
+ }
1930
+ }
1931
+ dispose() {
1932
+ this.disposed = true;
1933
+ }
1934
+ };
1935
+ var ForEachHandle = class {
1936
+ controller;
1937
+ disposed = false;
1938
+ fieldPath;
1939
+ processedIndexes = /* @__PURE__ */ new Set();
1940
+ constructor(controller, fieldPath) {
1941
+ this.controller = controller;
1942
+ this.fieldPath = fieldPath;
1943
+ }
1944
+ update(args) {
1945
+ if (this.disposed) return;
1946
+ try {
1947
+ const array = getField(args, this.fieldPath);
1948
+ if (!Array.isArray(array)) {
1949
+ return;
1950
+ }
1951
+ for (let i = 0; i < array.length; i++) {
1952
+ if (!this.processedIndexes.has(i)) {
1953
+ const elementPath = [...this.fieldPath, i];
1954
+ if (getPartialJsonObjectFieldState(
1955
+ args,
1956
+ elementPath
1957
+ ) === "complete") {
1958
+ this.controller.enqueue(array[i]);
1959
+ this.processedIndexes.add(i);
1960
+ }
1961
+ }
1962
+ }
1963
+ if (getPartialJsonObjectFieldState(
1964
+ args,
1965
+ this.fieldPath
1966
+ ) === "complete") {
1967
+ this.controller.close();
1968
+ this.dispose();
1969
+ }
1970
+ } catch (e) {
1971
+ this.controller.error(e);
1972
+ this.dispose();
1973
+ }
1974
+ }
1975
+ dispose() {
1976
+ this.disposed = true;
1977
+ }
1978
+ };
1979
+ var ToolCallArgsReaderImpl = class {
1980
+ argTextDeltas;
1981
+ handles = /* @__PURE__ */ new Set();
1982
+ args = parsePartialJsonObject("");
1983
+ constructor(argTextDeltas) {
1984
+ this.argTextDeltas = argTextDeltas;
1985
+ this.processStream();
1986
+ }
1987
+ async processStream() {
1988
+ try {
1989
+ let accumulatedText = "";
1990
+ const reader = this.argTextDeltas.getReader();
1991
+ while (true) {
1992
+ const { value, done } = await reader.read();
1993
+ if (done) break;
1994
+ accumulatedText += value;
1995
+ const parsedArgs = parsePartialJsonObject(accumulatedText);
1996
+ if (parsedArgs !== void 0) {
1997
+ this.args = parsedArgs;
1998
+ for (const handle of this.handles) {
1999
+ handle.update(parsedArgs);
2000
+ }
2001
+ }
2002
+ }
2003
+ } catch (error) {
2004
+ console.error("Error processing argument stream:", error);
2005
+ for (const handle of this.handles) {
2006
+ handle.dispose();
2007
+ }
2008
+ }
2009
+ }
2010
+ get(...fieldPath) {
2011
+ return new Promise((resolve, reject) => {
2012
+ const handle = new GetHandle(resolve, reject, fieldPath);
2013
+ if (this.args && getPartialJsonObjectFieldState(
2014
+ this.args,
2015
+ fieldPath
2016
+ ) === "complete") {
2017
+ const value = getField(this.args, fieldPath);
2018
+ if (value !== void 0) {
2019
+ resolve(value);
2020
+ return;
2021
+ }
2022
+ }
2023
+ this.handles.add(handle);
2024
+ handle.update(this.args);
2025
+ });
2026
+ }
2027
+ streamValues(...fieldPath) {
2028
+ const simplePath = fieldPath;
2029
+ const stream = new ReadableStream({
2030
+ start: (controller) => {
2031
+ const handle = new StreamValuesHandle(controller, simplePath);
2032
+ this.handles.add(handle);
2033
+ handle.update(this.args);
2034
+ },
2035
+ cancel: () => {
2036
+ for (const handle of this.handles) {
2037
+ if (handle instanceof StreamValuesHandle) {
2038
+ handle.dispose();
2039
+ this.handles.delete(handle);
2040
+ break;
2041
+ }
2042
+ }
2043
+ }
2044
+ });
2045
+ return stream;
2046
+ }
2047
+ streamText(...fieldPath) {
2048
+ const simplePath = fieldPath;
2049
+ const stream = new ReadableStream({
2050
+ start: (controller) => {
2051
+ const handle = new StreamTextHandle(controller, simplePath);
2052
+ this.handles.add(handle);
2053
+ handle.update(this.args);
2054
+ },
2055
+ cancel: () => {
2056
+ for (const handle of this.handles) {
2057
+ if (handle instanceof StreamTextHandle) {
2058
+ handle.dispose();
2059
+ this.handles.delete(handle);
2060
+ break;
2061
+ }
2062
+ }
2063
+ }
2064
+ });
2065
+ return stream;
2066
+ }
2067
+ forEach(...fieldPath) {
2068
+ const simplePath = fieldPath;
2069
+ const stream = new ReadableStream({
2070
+ start: (controller) => {
2071
+ const handle = new ForEachHandle(controller, simplePath);
2072
+ this.handles.add(handle);
2073
+ handle.update(this.args);
2074
+ },
2075
+ cancel: () => {
2076
+ for (const handle of this.handles) {
2077
+ if (handle instanceof ForEachHandle) {
2078
+ handle.dispose();
2079
+ this.handles.delete(handle);
2080
+ break;
2081
+ }
2082
+ }
2083
+ }
2084
+ });
2085
+ return stream;
2086
+ }
2087
+ };
2088
+ var ToolCallResponseReaderImpl = class {
2089
+ constructor(promise) {
2090
+ this.promise = promise;
2091
+ }
2092
+ get() {
2093
+ return this.promise;
2094
+ }
2095
+ };
2096
+ var ToolCallReaderImpl = class {
2097
+ args;
2098
+ response;
2099
+ writable;
2100
+ resolve;
2101
+ argsText = "";
2102
+ constructor() {
2103
+ const stream = new TransformStream();
2104
+ this.writable = stream.writable;
2105
+ this.args = new ToolCallArgsReaderImpl(stream.readable);
2106
+ const { promise, resolve } = promiseWithResolvers();
2107
+ this.resolve = resolve;
2108
+ this.response = new ToolCallResponseReaderImpl(promise);
2109
+ }
2110
+ async appendArgsTextDelta(text) {
2111
+ const writer = this.writable.getWriter();
2112
+ try {
2113
+ await writer.write(text);
2114
+ } catch (err) {
2115
+ console.warn(err);
2116
+ } finally {
2117
+ writer.releaseLock();
2118
+ }
2119
+ this.argsText += text;
2120
+ }
2121
+ setResponse(value) {
2122
+ this.resolve(value);
2123
+ }
2124
+ result = {
2125
+ get: async () => {
2126
+ const response = await this.response.get();
2127
+ return response.result;
2128
+ }
2129
+ };
2130
+ };
2131
+
2132
+ // src/core/tool/ToolExecutionStream.ts
2133
+ var ToolExecutionStream = class extends PipeableTransformStream {
2134
+ constructor(options) {
2135
+ const toolCallPromises = /* @__PURE__ */ new Map();
2136
+ const toolCallControllers = /* @__PURE__ */ new Map();
2137
+ super((readable) => {
2138
+ const transform = new TransformStream({
2139
+ transform(chunk, controller) {
2140
+ if (chunk.type !== "part-finish" || chunk.meta.type !== "tool-call") {
2141
+ controller.enqueue(chunk);
2142
+ }
2143
+ const type = chunk.type;
2144
+ switch (type) {
2145
+ case "part-start":
2146
+ if (chunk.part.type === "tool-call") {
2147
+ const reader = new ToolCallReaderImpl();
2148
+ toolCallControllers.set(chunk.part.toolCallId, reader);
2149
+ options.streamCall({
2150
+ reader,
2151
+ toolCallId: chunk.part.toolCallId,
2152
+ toolName: chunk.part.toolName
2153
+ });
2154
+ }
2155
+ break;
2156
+ case "text-delta": {
2157
+ if (chunk.meta.type === "tool-call") {
2158
+ const toolCallId = chunk.meta.toolCallId;
2159
+ const controller2 = toolCallControllers.get(toolCallId);
2160
+ if (!controller2)
2161
+ throw new Error("No controller found for tool call");
2162
+ controller2.appendArgsTextDelta(chunk.textDelta);
2163
+ }
2164
+ break;
2165
+ }
2166
+ case "tool-call-args-text-finish": {
2167
+ if (chunk.meta.type !== "tool-call") break;
2168
+ const { toolCallId, toolName } = chunk.meta;
2169
+ const streamController = toolCallControllers.get(toolCallId);
2170
+ if (!streamController)
2171
+ throw new Error("No controller found for tool call");
2172
+ const promise = withPromiseOrValue(
2173
+ () => {
2174
+ if (!streamController.argsText) {
2175
+ console.log(
2176
+ "Encountered tool call without args, this should never happen"
2177
+ );
2178
+ throw new Error(
2179
+ "Encountered tool call without args, this is unexpected."
2180
+ );
2181
+ }
2182
+ let args;
2183
+ try {
2184
+ args = import_secure_json_parse2.default.parse(streamController.argsText);
2185
+ } catch (e) {
2186
+ throw new Error(
2187
+ `Function parameter parsing failed. ${JSON.stringify(e.message)}`
2188
+ );
2189
+ }
2190
+ return options.execute({
2191
+ toolCallId,
2192
+ toolName,
2193
+ args
2194
+ });
2195
+ },
2196
+ (c) => {
2197
+ if (c === void 0) return;
2198
+ const result = new ToolResponse({
2199
+ artifact: c.artifact,
2200
+ result: c.result,
2201
+ isError: c.isError
2202
+ });
2203
+ streamController.setResponse(result);
2204
+ controller.enqueue({
2205
+ type: "result",
2206
+ path: chunk.path,
2207
+ ...result
2208
+ });
2209
+ },
2210
+ (e) => {
2211
+ const result = new ToolResponse({
2212
+ result: String(e),
2213
+ isError: true
2214
+ });
2215
+ streamController.setResponse(result);
2216
+ controller.enqueue({
2217
+ type: "result",
2218
+ path: chunk.path,
2219
+ ...result
2220
+ });
2221
+ }
2222
+ );
2223
+ if (promise) {
2224
+ toolCallPromises.set(toolCallId, promise);
2225
+ }
2226
+ break;
2227
+ }
2228
+ case "part-finish": {
2229
+ if (chunk.meta.type !== "tool-call") break;
2230
+ const { toolCallId } = chunk.meta;
2231
+ const toolCallPromise = toolCallPromises.get(toolCallId);
2232
+ if (toolCallPromise) {
2233
+ toolCallPromise.then(() => {
2234
+ toolCallPromises.delete(toolCallId);
2235
+ toolCallControllers.delete(toolCallId);
2236
+ controller.enqueue(chunk);
2237
+ });
2238
+ } else {
2239
+ controller.enqueue(chunk);
2240
+ }
2241
+ }
2242
+ }
2243
+ },
2244
+ async flush() {
2245
+ await Promise.all(toolCallPromises.values());
2246
+ }
2247
+ });
2248
+ return readable.pipeThrough(new AssistantMetaTransformStream()).pipeThrough(transform);
2249
+ });
2250
+ }
2251
+ };
2252
+
2253
+ // src/core/tool/toolResultStream.ts
2254
+ var isStandardSchemaV1 = (schema) => {
2255
+ return typeof schema === "object" && schema !== null && "~standard" in schema && schema["~standard"].version === 1;
2256
+ };
2257
+ function getToolResponse(tools, abortSignal, toolCall) {
2258
+ const tool = tools?.[toolCall.toolName];
2259
+ if (!tool || !tool.execute) return void 0;
2260
+ const getResult = async (toolExecute) => {
2261
+ let executeFn = toolExecute;
2262
+ if (isStandardSchemaV1(tool.parameters)) {
2263
+ let result2 = tool.parameters["~standard"].validate(toolCall.args);
2264
+ if (result2 instanceof Promise) result2 = await result2;
2265
+ if (result2.issues) {
2266
+ executeFn = tool.experimental_onSchemaValidationError ?? (() => {
2267
+ throw new Error(
2268
+ `Function parameter validation failed. ${JSON.stringify(result2.issues)}`
2269
+ );
2270
+ });
2271
+ }
2272
+ }
2273
+ const result = await executeFn(toolCall.args, {
2274
+ toolCallId: toolCall.toolCallId,
2275
+ abortSignal
2276
+ });
2277
+ if (result instanceof ToolResponse) return result;
2278
+ return new ToolResponse({
2279
+ result: result === void 0 ? "<no result>" : result
2280
+ });
2281
+ };
2282
+ return getResult(tool.execute);
2283
+ }
2284
+ function getToolStreamResponse(tools, abortSignal, reader, context) {
2285
+ tools?.[context.toolName]?.streamCall?.(reader, {
2286
+ toolCallId: context.toolCallId,
2287
+ abortSignal
2288
+ });
2289
+ }
2290
+ async function unstable_runPendingTools(message, tools, abortSignal) {
2291
+ for (const part of message.parts) {
2292
+ if (part.type === "tool-call") {
2293
+ const promiseOrUndefined = getToolResponse(tools, abortSignal, part);
2294
+ if (promiseOrUndefined) {
2295
+ const result = await promiseOrUndefined;
2296
+ const updatedParts = message.parts.map((p) => {
2297
+ if (p.type === "tool-call" && p.toolCallId === part.toolCallId) {
2298
+ return {
2299
+ ...p,
2300
+ state: "result",
2301
+ artifact: result.artifact,
2302
+ result: result.result,
2303
+ isError: result.isError
2304
+ };
2305
+ }
2306
+ return p;
2307
+ });
2308
+ message = {
2309
+ ...message,
2310
+ parts: updatedParts,
2311
+ content: updatedParts
2312
+ };
2313
+ }
2314
+ }
2315
+ }
2316
+ return message;
2317
+ }
2318
+ function toolResultStream(tools, abortSignal) {
2319
+ return new ToolExecutionStream({
2320
+ execute: (toolCall) => getToolResponse(tools, abortSignal, toolCall),
2321
+ streamCall: ({ reader, ...context }) => getToolStreamResponse(tools, abortSignal, reader, context)
2322
+ });
2323
+ }
1907
2324
  // Annotate the CommonJS export names for ESM import in node:
1908
2325
  0 && (module.exports = {
1909
2326
  AssistantMessageAccumulator,
@@ -1916,6 +2333,8 @@ var ToolResponse = class {
1916
2333
  ToolExecutionStream,
1917
2334
  ToolResponse,
1918
2335
  createAssistantStream,
1919
- createAssistantStreamResponse
2336
+ createAssistantStreamResponse,
2337
+ unstable_runPendingTools,
2338
+ unstable_toolResultStream
1920
2339
  });
1921
2340
  //# sourceMappingURL=index.js.map