assistant-stream 0.1.3 → 0.1.4

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,505 @@ 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 ToolCallResultReaderImpl = class {
2089
+ constructor(resultPromise) {
2090
+ this.resultPromise = resultPromise;
2091
+ }
2092
+ get() {
2093
+ return this.resultPromise;
2094
+ }
2095
+ };
2096
+ var ToolCallReaderImpl = class {
2097
+ args;
2098
+ result;
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.result = new ToolCallResultReaderImpl(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
+ setResult(value) {
2122
+ this.resolve(value);
2123
+ }
2124
+ };
2125
+
2126
+ // src/core/tool/ToolExecutionStream.ts
2127
+ var ToolExecutionStream = class extends PipeableTransformStream {
2128
+ constructor(options) {
2129
+ const toolCallPromises = /* @__PURE__ */ new Map();
2130
+ const toolCallControllers = /* @__PURE__ */ new Map();
2131
+ super((readable) => {
2132
+ const transform = new TransformStream({
2133
+ transform(chunk, controller) {
2134
+ if (chunk.type !== "part-finish" || chunk.meta.type !== "tool-call") {
2135
+ controller.enqueue(chunk);
2136
+ }
2137
+ const type = chunk.type;
2138
+ switch (type) {
2139
+ case "part-start":
2140
+ if (chunk.part.type === "tool-call") {
2141
+ const reader = new ToolCallReaderImpl();
2142
+ toolCallControllers.set(chunk.part.toolCallId, reader);
2143
+ options.streamCall({
2144
+ reader,
2145
+ toolCallId: chunk.part.toolCallId,
2146
+ toolName: chunk.part.toolName
2147
+ });
2148
+ }
2149
+ break;
2150
+ case "text-delta": {
2151
+ if (chunk.meta.type === "tool-call") {
2152
+ const toolCallId = chunk.meta.toolCallId;
2153
+ const controller2 = toolCallControllers.get(toolCallId);
2154
+ if (!controller2)
2155
+ throw new Error("No controller found for tool call");
2156
+ controller2.appendArgsTextDelta(chunk.textDelta);
2157
+ }
2158
+ break;
2159
+ }
2160
+ case "tool-call-args-text-finish": {
2161
+ if (chunk.meta.type !== "tool-call") break;
2162
+ const { toolCallId, toolName } = chunk.meta;
2163
+ const promise = withPromiseOrValue(
2164
+ () => {
2165
+ const controller2 = toolCallControllers.get(toolCallId);
2166
+ if (!controller2) {
2167
+ console.log(
2168
+ "Encountered tool call without controller, this should never happen"
2169
+ );
2170
+ throw new Error(
2171
+ "Encountered tool call without controller, this is unexpected."
2172
+ );
2173
+ }
2174
+ let args;
2175
+ try {
2176
+ args = import_secure_json_parse2.default.parse(controller2.argsText);
2177
+ } catch (e) {
2178
+ throw new Error(
2179
+ `Function parameter parsing failed. ${JSON.stringify(e.message)}`
2180
+ );
2181
+ }
2182
+ return options.execute({
2183
+ toolCallId,
2184
+ toolName,
2185
+ args
2186
+ });
2187
+ },
2188
+ (c) => {
2189
+ if (c === void 0) return;
2190
+ controller.enqueue({
2191
+ type: "result",
2192
+ path: chunk.path,
2193
+ artifact: c.artifact,
2194
+ result: c.result,
2195
+ isError: c.isError
2196
+ });
2197
+ },
2198
+ (e) => {
2199
+ controller.enqueue({
2200
+ type: "result",
2201
+ path: chunk.path,
2202
+ result: String(e),
2203
+ isError: true
2204
+ });
2205
+ }
2206
+ );
2207
+ if (promise) {
2208
+ toolCallPromises.set(toolCallId, promise);
2209
+ }
2210
+ break;
2211
+ }
2212
+ case "part-finish": {
2213
+ if (chunk.meta.type !== "tool-call") break;
2214
+ const { toolCallId } = chunk.meta;
2215
+ const toolCallPromise = toolCallPromises.get(toolCallId);
2216
+ if (toolCallPromise) {
2217
+ toolCallPromise.then(() => {
2218
+ toolCallPromises.delete(toolCallId);
2219
+ toolCallControllers.delete(toolCallId);
2220
+ controller.enqueue(chunk);
2221
+ });
2222
+ } else {
2223
+ controller.enqueue(chunk);
2224
+ }
2225
+ }
2226
+ }
2227
+ },
2228
+ async flush() {
2229
+ await Promise.all(toolCallPromises.values());
2230
+ }
2231
+ });
2232
+ return readable.pipeThrough(new AssistantMetaTransformStream()).pipeThrough(transform);
2233
+ });
2234
+ }
2235
+ };
2236
+
2237
+ // src/core/tool/toolResultStream.ts
2238
+ var isStandardSchemaV1 = (schema) => {
2239
+ return typeof schema === "object" && schema !== null && "~standard" in schema && schema["~standard"].version === 1;
2240
+ };
2241
+ function getToolResponse(tools, abortSignal, toolCall) {
2242
+ const tool = tools?.[toolCall.toolName];
2243
+ if (!tool || !tool.execute) return void 0;
2244
+ const getResult = async (toolExecute) => {
2245
+ let executeFn = toolExecute;
2246
+ if (isStandardSchemaV1(tool.parameters)) {
2247
+ let result2 = tool.parameters["~standard"].validate(toolCall.args);
2248
+ if (result2 instanceof Promise) result2 = await result2;
2249
+ if (result2.issues) {
2250
+ executeFn = tool.experimental_onSchemaValidationError ?? (() => {
2251
+ throw new Error(
2252
+ `Function parameter validation failed. ${JSON.stringify(result2.issues)}`
2253
+ );
2254
+ });
2255
+ }
2256
+ }
2257
+ const result = await executeFn(toolCall.args, {
2258
+ toolCallId: toolCall.toolCallId,
2259
+ abortSignal
2260
+ });
2261
+ if (result instanceof ToolResponse) return result;
2262
+ return new ToolResponse({
2263
+ result: result === void 0 ? "<no result>" : result
2264
+ });
2265
+ };
2266
+ return getResult(tool.execute);
2267
+ }
2268
+ function getToolStreamResponse(tools, abortSignal, reader, context) {
2269
+ tools?.[context.toolName]?.streamCall?.(reader, {
2270
+ toolCallId: context.toolCallId,
2271
+ abortSignal
2272
+ });
2273
+ }
2274
+ async function unstable_runPendingTools(message, tools, abortSignal) {
2275
+ for (const part of message.parts) {
2276
+ if (part.type === "tool-call") {
2277
+ const promiseOrUndefined = getToolResponse(tools, abortSignal, part);
2278
+ if (promiseOrUndefined) {
2279
+ const result = await promiseOrUndefined;
2280
+ const updatedParts = message.parts.map((p) => {
2281
+ if (p.type === "tool-call" && p.toolCallId === part.toolCallId) {
2282
+ return {
2283
+ ...p,
2284
+ state: "result",
2285
+ artifact: result.artifact,
2286
+ result: result.result,
2287
+ isError: result.isError
2288
+ };
2289
+ }
2290
+ return p;
2291
+ });
2292
+ message = {
2293
+ ...message,
2294
+ parts: updatedParts,
2295
+ content: updatedParts
2296
+ };
2297
+ }
2298
+ }
2299
+ }
2300
+ return message;
2301
+ }
2302
+ function toolResultStream(tools, abortSignal) {
2303
+ return new ToolExecutionStream({
2304
+ execute: (toolCall) => getToolResponse(tools, abortSignal, toolCall),
2305
+ streamCall: ({ reader, ...context }) => getToolStreamResponse(tools, abortSignal, reader, context)
2306
+ });
2307
+ }
1907
2308
  // Annotate the CommonJS export names for ESM import in node:
1908
2309
  0 && (module.exports = {
1909
2310
  AssistantMessageAccumulator,
@@ -1916,6 +2317,8 @@ var ToolResponse = class {
1916
2317
  ToolExecutionStream,
1917
2318
  ToolResponse,
1918
2319
  createAssistantStream,
1919
- createAssistantStreamResponse
2320
+ createAssistantStreamResponse,
2321
+ unstable_runPendingTools,
2322
+ unstable_toolResultStream
1920
2323
  });
1921
2324
  //# sourceMappingURL=index.js.map