assistant-stream 0.1.2 → 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,130 +976,22 @@ 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.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;
1107
986
  let literalStart = null;
987
+ const path = [];
988
+ let currentKey;
989
+ function pushCurrentKeyToPath() {
990
+ if (currentKey !== void 0) {
991
+ path.push(JSON.parse('"' + currentKey + '"'));
992
+ currentKey = void 0;
993
+ }
994
+ }
1108
995
  function processValueStart(char, i, swapState) {
1109
996
  {
1110
997
  switch (char) {
@@ -1113,6 +1000,7 @@ function fixJson(input) {
1113
1000
  stack.pop();
1114
1001
  stack.push(swapState);
1115
1002
  stack.push("INSIDE_STRING");
1003
+ pushCurrentKeyToPath();
1116
1004
  break;
1117
1005
  }
1118
1006
  case "f":
@@ -1129,6 +1017,7 @@ function fixJson(input) {
1129
1017
  stack.pop();
1130
1018
  stack.push(swapState);
1131
1019
  stack.push("INSIDE_NUMBER");
1020
+ pushCurrentKeyToPath();
1132
1021
  break;
1133
1022
  }
1134
1023
  case "0":
@@ -1145,6 +1034,7 @@ function fixJson(input) {
1145
1034
  stack.pop();
1146
1035
  stack.push(swapState);
1147
1036
  stack.push("INSIDE_NUMBER");
1037
+ pushCurrentKeyToPath();
1148
1038
  break;
1149
1039
  }
1150
1040
  case "{": {
@@ -1152,6 +1042,7 @@ function fixJson(input) {
1152
1042
  stack.pop();
1153
1043
  stack.push(swapState);
1154
1044
  stack.push("INSIDE_OBJECT_START");
1045
+ pushCurrentKeyToPath();
1155
1046
  break;
1156
1047
  }
1157
1048
  case "[": {
@@ -1159,6 +1050,7 @@ function fixJson(input) {
1159
1050
  stack.pop();
1160
1051
  stack.push(swapState);
1161
1052
  stack.push("INSIDE_ARRAY_START");
1053
+ pushCurrentKeyToPath();
1162
1054
  break;
1163
1055
  }
1164
1056
  }
@@ -1174,6 +1066,7 @@ function fixJson(input) {
1174
1066
  case "}": {
1175
1067
  lastValidIndex = i;
1176
1068
  stack.pop();
1069
+ currentKey = path.pop();
1177
1070
  break;
1178
1071
  }
1179
1072
  }
@@ -1183,11 +1076,13 @@ function fixJson(input) {
1183
1076
  case ",": {
1184
1077
  stack.pop();
1185
1078
  stack.push("INSIDE_ARRAY_AFTER_COMMA");
1079
+ currentKey = (Number(currentKey) + 1).toString();
1186
1080
  break;
1187
1081
  }
1188
1082
  case "]": {
1189
1083
  lastValidIndex = i;
1190
1084
  stack.pop();
1085
+ currentKey = path.pop();
1191
1086
  break;
1192
1087
  }
1193
1088
  }
@@ -1204,11 +1099,13 @@ function fixJson(input) {
1204
1099
  case '"': {
1205
1100
  stack.pop();
1206
1101
  stack.push("INSIDE_OBJECT_KEY");
1102
+ currentKey = "";
1207
1103
  break;
1208
1104
  }
1209
1105
  case "}": {
1210
1106
  lastValidIndex = i;
1211
1107
  stack.pop();
1108
+ currentKey = path.pop();
1212
1109
  break;
1213
1110
  }
1214
1111
  }
@@ -1219,6 +1116,7 @@ function fixJson(input) {
1219
1116
  case '"': {
1220
1117
  stack.pop();
1221
1118
  stack.push("INSIDE_OBJECT_KEY");
1119
+ currentKey = "";
1222
1120
  break;
1223
1121
  }
1224
1122
  }
@@ -1231,6 +1129,15 @@ function fixJson(input) {
1231
1129
  stack.push("INSIDE_OBJECT_AFTER_KEY");
1232
1130
  break;
1233
1131
  }
1132
+ case "\\": {
1133
+ stack.push("INSIDE_STRING_ESCAPE");
1134
+ currentKey += char;
1135
+ break;
1136
+ }
1137
+ default: {
1138
+ currentKey += char;
1139
+ break;
1140
+ }
1234
1141
  }
1235
1142
  break;
1236
1143
  }
@@ -1257,6 +1164,7 @@ function fixJson(input) {
1257
1164
  case '"': {
1258
1165
  stack.pop();
1259
1166
  lastValidIndex = i;
1167
+ currentKey = path.pop();
1260
1168
  break;
1261
1169
  }
1262
1170
  case "\\": {
@@ -1274,10 +1182,12 @@ function fixJson(input) {
1274
1182
  case "]": {
1275
1183
  lastValidIndex = i;
1276
1184
  stack.pop();
1185
+ currentKey = path.pop();
1277
1186
  break;
1278
1187
  }
1279
1188
  default: {
1280
1189
  lastValidIndex = i;
1190
+ currentKey = "0";
1281
1191
  processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1282
1192
  break;
1283
1193
  }
@@ -1289,11 +1199,13 @@ function fixJson(input) {
1289
1199
  case ",": {
1290
1200
  stack.pop();
1291
1201
  stack.push("INSIDE_ARRAY_AFTER_COMMA");
1202
+ currentKey = (Number(currentKey) + 1).toString();
1292
1203
  break;
1293
1204
  }
1294
1205
  case "]": {
1295
1206
  lastValidIndex = i;
1296
1207
  stack.pop();
1208
+ currentKey = path.pop();
1297
1209
  break;
1298
1210
  }
1299
1211
  default: {
@@ -1309,7 +1221,11 @@ function fixJson(input) {
1309
1221
  }
1310
1222
  case "INSIDE_STRING_ESCAPE": {
1311
1223
  stack.pop();
1312
- lastValidIndex = i;
1224
+ if (stack[stack.length - 1] === "INSIDE_STRING") {
1225
+ lastValidIndex = i;
1226
+ } else if (stack[stack.length - 1] === "INSIDE_OBJECT_KEY") {
1227
+ currentKey += char;
1228
+ }
1313
1229
  break;
1314
1230
  }
1315
1231
  case "INSIDE_NUMBER": {
@@ -1335,6 +1251,7 @@ function fixJson(input) {
1335
1251
  }
1336
1252
  case ",": {
1337
1253
  stack.pop();
1254
+ currentKey = path.pop();
1338
1255
  if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1339
1256
  processAfterArrayValue(char, i);
1340
1257
  }
@@ -1345,6 +1262,7 @@ function fixJson(input) {
1345
1262
  }
1346
1263
  case "}": {
1347
1264
  stack.pop();
1265
+ currentKey = path.pop();
1348
1266
  if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1349
1267
  processAfterObjectValue(char, i);
1350
1268
  }
@@ -1352,6 +1270,7 @@ function fixJson(input) {
1352
1270
  }
1353
1271
  case "]": {
1354
1272
  stack.pop();
1273
+ currentKey = path.pop();
1355
1274
  if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1356
1275
  processAfterArrayValue(char, i);
1357
1276
  }
@@ -1359,6 +1278,7 @@ function fixJson(input) {
1359
1278
  }
1360
1279
  default: {
1361
1280
  stack.pop();
1281
+ currentKey = path.pop();
1362
1282
  break;
1363
1283
  }
1364
1284
  }
@@ -1415,21 +1335,66 @@ function fixJson(input) {
1415
1335
  }
1416
1336
  }
1417
1337
  }
1418
- return result;
1338
+ return [result, path];
1419
1339
  }
1420
1340
 
1421
- // src/core/utils/json/parse-partial-json.ts
1422
- var parsePartialJson = (json) => {
1341
+ // src/utils/json/parse-partial-json-object.ts
1342
+ var PARTIAL_JSON_OBJECT_META_SYMBOL = Symbol(
1343
+ "aui.parse-partial-json-object.meta"
1344
+ );
1345
+ var getPartialJsonObjectMeta = (obj) => {
1346
+ return obj?.[PARTIAL_JSON_OBJECT_META_SYMBOL];
1347
+ };
1348
+ var parsePartialJsonObject = (json) => {
1349
+ if (json.length === 0)
1350
+ return {
1351
+ [PARTIAL_JSON_OBJECT_META_SYMBOL]: { state: "partial", partialPath: [] }
1352
+ };
1423
1353
  try {
1424
- return import_secure_json_parse2.default.parse(json);
1354
+ const res = import_secure_json_parse.default.parse(json);
1355
+ if (typeof res !== "object" || res === null)
1356
+ throw new Error("argsText is expected to be an object");
1357
+ res[PARTIAL_JSON_OBJECT_META_SYMBOL] = {
1358
+ state: "complete",
1359
+ partialPath: []
1360
+ };
1361
+ return res;
1425
1362
  } catch {
1426
1363
  try {
1427
- return import_secure_json_parse2.default.parse(fixJson(json));
1364
+ const [fixedJson, partialPath] = fixJson(json);
1365
+ const res = import_secure_json_parse.default.parse(fixedJson);
1366
+ if (typeof res !== "object" || res === null)
1367
+ throw new Error("argsText is expected to be an object");
1368
+ res[PARTIAL_JSON_OBJECT_META_SYMBOL] = {
1369
+ state: "partial",
1370
+ partialPath
1371
+ };
1372
+ return res;
1428
1373
  } catch {
1429
1374
  return void 0;
1430
1375
  }
1431
1376
  }
1432
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
+ };
1433
1398
 
1434
1399
  // src/core/accumulators/assistant-message-accumulator.ts
1435
1400
  var createInitialMessage = () => ({
@@ -1553,12 +1518,7 @@ var handleTextDelta = (message, chunk) => {
1553
1518
  return { ...part, text: part.text + chunk.textDelta };
1554
1519
  } else if (part.type === "tool-call") {
1555
1520
  const newArgsText = part.argsText + chunk.textDelta;
1556
- let newArgs;
1557
- try {
1558
- newArgs = parsePartialJson(newArgsText);
1559
- } catch (err) {
1560
- newArgs = part.args;
1561
- }
1521
+ const newArgs = parsePartialJsonObject(newArgsText) ?? part.args;
1562
1522
  return { ...part, argsText: newArgsText, args: newArgs };
1563
1523
  } else {
1564
1524
  throw new Error(
@@ -1828,7 +1788,7 @@ var AssistantMessageStream = class _AssistantMessageStream {
1828
1788
  }
1829
1789
  };
1830
1790
 
1831
- // src/core/ToolResponse.ts
1791
+ // src/core/tool/ToolResponse.ts
1832
1792
  var TOOL_RESPONSE_SYMBOL = Symbol.for("aui.tool-response");
1833
1793
  var ToolResponse = class {
1834
1794
  get [TOOL_RESPONSE_SYMBOL]() {
@@ -1846,6 +1806,505 @@ var ToolResponse = class {
1846
1806
  return typeof obj === "object" && obj !== null && TOOL_RESPONSE_SYMBOL in obj;
1847
1807
  }
1848
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
+ }
1849
2308
  // Annotate the CommonJS export names for ESM import in node:
1850
2309
  0 && (module.exports = {
1851
2310
  AssistantMessageAccumulator,
@@ -1858,6 +2317,8 @@ var ToolResponse = class {
1858
2317
  ToolExecutionStream,
1859
2318
  ToolResponse,
1860
2319
  createAssistantStream,
1861
- createAssistantStreamResponse
2320
+ createAssistantStreamResponse,
2321
+ unstable_runPendingTools,
2322
+ unstable_toolResultStream
1862
2323
  });
1863
2324
  //# sourceMappingURL=index.js.map