@kortyx/hooks 0.12.1 → 0.13.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/CHANGELOG.md +7 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +255 -104
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.13.0](https://github.com/kortyx-io/kortyx/compare/hooks-v0.12.1...hooks-v0.13.0) (2026-05-22)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **hooks:** support nested structured streaming ([#109](https://github.com/kortyx-io/kortyx/issues/109)) ([4921043](https://github.com/kortyx-io/kortyx/commit/49210435f5b3365c962aa737093c004e5d17a2f4))
|
|
9
|
+
|
|
3
10
|
## [0.12.1](https://github.com/kortyx-io/kortyx/compare/hooks-v0.12.0...hooks-v0.12.1) (2026-05-22)
|
|
4
11
|
|
|
5
12
|
|
package/dist/index.d.ts
CHANGED
|
@@ -68,15 +68,18 @@ type UseStructuredDataTextDeltaArgs = UseStructuredDataBaseArgs & {
|
|
|
68
68
|
};
|
|
69
69
|
type UseStructuredDataArgs<TData = unknown, TValue = unknown, TItem = unknown> = UseStructuredDataFinalArgs<TData> | UseStructuredDataSetArgs<TValue> | UseStructuredDataAppendArgs<TItem> | UseStructuredDataTextDeltaArgs;
|
|
70
70
|
type UseReasonStructuredConfig = {
|
|
71
|
+
/**
|
|
72
|
+
* Controls incremental field streaming. Set to false to emit only the final
|
|
73
|
+
* structured output chunk after output validation.
|
|
74
|
+
*/
|
|
71
75
|
stream?: boolean | undefined;
|
|
72
76
|
optimistic?: boolean | undefined;
|
|
73
77
|
dataType?: string | undefined;
|
|
74
78
|
schemaId?: string | undefined;
|
|
75
79
|
schemaVersion?: string | undefined;
|
|
76
80
|
/**
|
|
77
|
-
* Incremental extraction
|
|
78
|
-
*
|
|
79
|
-
* useStructuredData(...).
|
|
81
|
+
* Incremental extraction paths for useReason. Dotted paths target nested
|
|
82
|
+
* object fields, and numeric segments target array indexes.
|
|
80
83
|
*/
|
|
81
84
|
fields?: UseReasonStructuredFields | undefined;
|
|
82
85
|
};
|
package/dist/index.js
CHANGED
|
@@ -298,7 +298,8 @@ var emitStructuredData = (args) => {
|
|
|
298
298
|
data: validated
|
|
299
299
|
});
|
|
300
300
|
};
|
|
301
|
-
var shouldEmitStructured = (cfg) => Boolean(cfg)
|
|
301
|
+
var shouldEmitStructured = (cfg) => Boolean(cfg);
|
|
302
|
+
var shouldStreamStructured = (cfg) => Boolean(cfg) && (cfg?.stream ?? true);
|
|
302
303
|
|
|
303
304
|
// src/reason/checkpoint.ts
|
|
304
305
|
var resolveReasonCheckpointKey = (args) => typeof args.id === "string" && args.id.length > 0 ? `__useReason:${args.id}` : `__useReason:auto:${args.autoIndex}`;
|
|
@@ -861,12 +862,12 @@ var withStructuredStreamHints = (input, args) => {
|
|
|
861
862
|
const rules = [];
|
|
862
863
|
for (const path of args.setFieldPaths ?? []) {
|
|
863
864
|
rules.push(
|
|
864
|
-
`- For the
|
|
865
|
+
`- For the field path \`${path}\`, write one stable final value and do not rewrite it after it is complete.`
|
|
865
866
|
);
|
|
866
867
|
}
|
|
867
868
|
for (const path of args.appendFieldPaths ?? []) {
|
|
868
869
|
rules.push(
|
|
869
|
-
`- For the
|
|
870
|
+
`- For the array field path \`${path}\`, write items in final order and finish each item before starting the next.`
|
|
870
871
|
);
|
|
871
872
|
rules.push(
|
|
872
873
|
`- Once an item in \`${path}\` is complete, do not rewrite or reorder earlier items.`
|
|
@@ -874,7 +875,7 @@ var withStructuredStreamHints = (input, args) => {
|
|
|
874
875
|
}
|
|
875
876
|
for (const path of args.textDeltaFieldPaths ?? []) {
|
|
876
877
|
rules.push(
|
|
877
|
-
`- For the
|
|
878
|
+
`- For the string field path \`${path}\`, write the value progressively by appending text to the end.`
|
|
878
879
|
);
|
|
879
880
|
rules.push(
|
|
880
881
|
`- Do not rewrite or replace the earlier prefix of \`${path}\` once emitted.`
|
|
@@ -890,22 +891,12 @@ var withStructuredStreamHints = (input, args) => {
|
|
|
890
891
|
};
|
|
891
892
|
|
|
892
893
|
// src/reason/structured-stream.ts
|
|
893
|
-
var escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
894
|
-
var findTopLevelArrayStart = (text, path) => {
|
|
895
|
-
const match = new RegExp(`"${escapeRegex(path)}"\\s*:\\s*\\[`).exec(text);
|
|
896
|
-
return match ? match.index + match[0].length : -1;
|
|
897
|
-
};
|
|
898
894
|
var resolveAppendFieldPaths = (cfg) => {
|
|
899
895
|
const fields = cfg?.fields;
|
|
900
896
|
if (!fields) return [];
|
|
901
897
|
const appendPaths = Object.entries(fields).filter(([, mode]) => mode === "append").map(([path]) => path);
|
|
902
898
|
for (const path of appendPaths) {
|
|
903
899
|
assertStructuredPath(path, "useReason structured append");
|
|
904
|
-
if (path.includes(".")) {
|
|
905
|
-
throw new Error(
|
|
906
|
-
"useReason structured append streaming requires non-empty top-level array field keys."
|
|
907
|
-
);
|
|
908
|
-
}
|
|
909
900
|
}
|
|
910
901
|
return appendPaths;
|
|
911
902
|
};
|
|
@@ -915,11 +906,6 @@ var resolveSetFieldPaths = (cfg) => {
|
|
|
915
906
|
const setPaths = Object.entries(fields).filter(([, mode]) => mode === "set").map(([path]) => path);
|
|
916
907
|
for (const path of setPaths) {
|
|
917
908
|
assertStructuredPath(path, "useReason structured set");
|
|
918
|
-
if (path.includes(".")) {
|
|
919
|
-
throw new Error(
|
|
920
|
-
"useReason structured set streaming requires non-empty top-level field keys."
|
|
921
|
-
);
|
|
922
|
-
}
|
|
923
909
|
}
|
|
924
910
|
return setPaths;
|
|
925
911
|
};
|
|
@@ -929,22 +915,9 @@ var resolveTextDeltaFieldPaths = (cfg) => {
|
|
|
929
915
|
const textPaths = Object.entries(fields).filter(([, mode]) => mode === "text-delta").map(([path]) => path);
|
|
930
916
|
for (const path of textPaths) {
|
|
931
917
|
assertStructuredPath(path, "useReason structured text-delta");
|
|
932
|
-
if (path.includes(".")) {
|
|
933
|
-
throw new Error(
|
|
934
|
-
"useReason structured text-delta streaming requires non-empty top-level string field keys."
|
|
935
|
-
);
|
|
936
|
-
}
|
|
937
918
|
}
|
|
938
919
|
return textPaths;
|
|
939
920
|
};
|
|
940
|
-
var findTopLevelFieldValueStart = (text, path) => {
|
|
941
|
-
const match = new RegExp(`"${escapeRegex(path)}"\\s*:\\s*`).exec(text);
|
|
942
|
-
return match ? match.index + match[0].length : -1;
|
|
943
|
-
};
|
|
944
|
-
var findTopLevelStringStart = (text, path) => {
|
|
945
|
-
const match = new RegExp(`"${escapeRegex(path)}"\\s*:\\s*"`).exec(text);
|
|
946
|
-
return match ? match.index + match[0].length : -1;
|
|
947
|
-
};
|
|
948
921
|
var extractCompletedStringValueAt = (args) => {
|
|
949
922
|
let value = "";
|
|
950
923
|
for (let i = args.start; i < args.text.length; i += 1) {
|
|
@@ -990,12 +963,49 @@ var extractCompletedStringValueAt = (args) => {
|
|
|
990
963
|
complete: false
|
|
991
964
|
};
|
|
992
965
|
};
|
|
993
|
-
var
|
|
966
|
+
var skipWhitespace = (text, start) => {
|
|
967
|
+
let i = start;
|
|
968
|
+
while (i < text.length && /\s/.test(text[i] ?? "")) i += 1;
|
|
969
|
+
return i;
|
|
970
|
+
};
|
|
971
|
+
var pathEquals = (left, right) => left.length === right.length && left.every((part, index) => part === right[index]);
|
|
972
|
+
var isPathPrefix = (prefix, full) => prefix.length <= full.length && prefix.every((part, index) => part === full[index]);
|
|
973
|
+
var parseStringToken = (text, start) => {
|
|
974
|
+
if (text[start] !== '"') return { complete: false };
|
|
975
|
+
const parsed = extractCompletedStringValueAt({ text, start: start + 1 });
|
|
976
|
+
if (!parsed.complete || parsed.value === void 0)
|
|
977
|
+
return { complete: false };
|
|
978
|
+
let inEscape = false;
|
|
979
|
+
for (let i = start + 1; i < text.length; i += 1) {
|
|
980
|
+
const ch = text[i];
|
|
981
|
+
if (ch === void 0) break;
|
|
982
|
+
if (inEscape) {
|
|
983
|
+
inEscape = false;
|
|
984
|
+
if (ch === "u") i += 4;
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
if (ch === "\\") {
|
|
988
|
+
inEscape = true;
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
if (ch === '"') {
|
|
992
|
+
return {
|
|
993
|
+
complete: true,
|
|
994
|
+
end: i + 1,
|
|
995
|
+
value: parsed.value
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return { complete: false };
|
|
1000
|
+
};
|
|
1001
|
+
var skipNestedValue = (text, start) => {
|
|
1002
|
+
const opener = text[start];
|
|
1003
|
+
const closer = opener === "{" ? "}" : "]";
|
|
994
1004
|
let inString = false;
|
|
995
1005
|
let isEscaped = false;
|
|
996
1006
|
let nesting = 0;
|
|
997
|
-
for (let i =
|
|
998
|
-
const ch =
|
|
1007
|
+
for (let i = start; i < text.length; i += 1) {
|
|
1008
|
+
const ch = text[i];
|
|
999
1009
|
if (ch === void 0) break;
|
|
1000
1010
|
if (inString) {
|
|
1001
1011
|
if (isEscaped) {
|
|
@@ -1015,124 +1025,257 @@ var extractCompletedNestedValueAt = (args) => {
|
|
|
1015
1025
|
inString = true;
|
|
1016
1026
|
continue;
|
|
1017
1027
|
}
|
|
1018
|
-
if (ch ===
|
|
1028
|
+
if (ch === opener) {
|
|
1019
1029
|
nesting += 1;
|
|
1020
1030
|
continue;
|
|
1021
1031
|
}
|
|
1022
|
-
if (ch ===
|
|
1032
|
+
if (ch === closer) {
|
|
1023
1033
|
nesting -= 1;
|
|
1024
1034
|
if (nesting === 0) {
|
|
1025
|
-
|
|
1026
|
-
try {
|
|
1027
|
-
return {
|
|
1028
|
-
complete: true,
|
|
1029
|
-
value: JSON.parse(raw)
|
|
1030
|
-
};
|
|
1031
|
-
} catch {
|
|
1032
|
-
return {
|
|
1033
|
-
complete: false
|
|
1034
|
-
};
|
|
1035
|
-
}
|
|
1035
|
+
return { complete: true, end: i + 1 };
|
|
1036
1036
|
}
|
|
1037
1037
|
}
|
|
1038
1038
|
}
|
|
1039
|
-
return {
|
|
1040
|
-
complete: false
|
|
1041
|
-
};
|
|
1039
|
+
return { complete: false };
|
|
1042
1040
|
};
|
|
1043
|
-
var
|
|
1044
|
-
const
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
};
|
|
1041
|
+
var skipCompleteValue = (text, start) => {
|
|
1042
|
+
const i = skipWhitespace(text, start);
|
|
1043
|
+
const first = text[i];
|
|
1044
|
+
if (!first) return { complete: false };
|
|
1045
|
+
if (first === '"') {
|
|
1046
|
+
const parsed = parseStringToken(text, i);
|
|
1047
|
+
return parsed.complete && parsed.end !== void 0 ? { complete: true, end: parsed.end } : { complete: false };
|
|
1050
1048
|
}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
};
|
|
1049
|
+
if (first === "{" || first === "[") {
|
|
1050
|
+
return skipNestedValue(text, i);
|
|
1051
|
+
}
|
|
1052
|
+
for (let j = i; j < text.length; j += 1) {
|
|
1053
|
+
const ch = text[j];
|
|
1054
|
+
if (ch !== "," && ch !== "}" && ch !== "]") continue;
|
|
1055
|
+
const raw = text.slice(i, j).trim();
|
|
1056
|
+
if (!raw) return { complete: false };
|
|
1057
|
+
try {
|
|
1058
|
+
JSON.parse(raw);
|
|
1059
|
+
return { complete: true, end: j };
|
|
1060
|
+
} catch {
|
|
1061
|
+
return { complete: false };
|
|
1062
|
+
}
|
|
1057
1063
|
}
|
|
1064
|
+
return { complete: false };
|
|
1065
|
+
};
|
|
1066
|
+
var locateValueStart = (args) => {
|
|
1067
|
+
const targetParts = parseStructuredPath(
|
|
1068
|
+
args.path,
|
|
1069
|
+
"useReason structured field"
|
|
1070
|
+
);
|
|
1071
|
+
const visitValue = (start, currentParts) => {
|
|
1072
|
+
const valueStart = skipWhitespace(args.text, start);
|
|
1073
|
+
if (pathEquals(currentParts, targetParts)) {
|
|
1074
|
+
return { found: true, start: valueStart };
|
|
1075
|
+
}
|
|
1076
|
+
if (!isPathPrefix(currentParts, targetParts)) {
|
|
1077
|
+
return { found: false };
|
|
1078
|
+
}
|
|
1079
|
+
const first = args.text[valueStart];
|
|
1080
|
+
if (first === "{") return visitObject(valueStart + 1, currentParts);
|
|
1081
|
+
if (first === "[") return visitArray(valueStart + 1, currentParts);
|
|
1082
|
+
return { found: false };
|
|
1083
|
+
};
|
|
1084
|
+
const visitObject = (start, currentParts) => {
|
|
1085
|
+
let i = skipWhitespace(args.text, start);
|
|
1086
|
+
while (i < args.text.length) {
|
|
1087
|
+
const ch = args.text[i];
|
|
1088
|
+
if (ch === "}") return { found: false };
|
|
1089
|
+
if (ch === ",") {
|
|
1090
|
+
i = skipWhitespace(args.text, i + 1);
|
|
1091
|
+
continue;
|
|
1092
|
+
}
|
|
1093
|
+
if (ch !== '"') return { found: false };
|
|
1094
|
+
const key = parseStringToken(args.text, i);
|
|
1095
|
+
if (!key.complete || key.end === void 0 || key.value === void 0) {
|
|
1096
|
+
return { found: false };
|
|
1097
|
+
}
|
|
1098
|
+
i = skipWhitespace(args.text, key.end);
|
|
1099
|
+
if (args.text[i] !== ":") return { found: false };
|
|
1100
|
+
const valueStart = skipWhitespace(args.text, i + 1);
|
|
1101
|
+
const childParts = [...currentParts, key.value];
|
|
1102
|
+
if (pathEquals(childParts, targetParts)) {
|
|
1103
|
+
return { found: true, start: valueStart };
|
|
1104
|
+
}
|
|
1105
|
+
if (isPathPrefix(childParts, targetParts)) {
|
|
1106
|
+
const nested = visitValue(valueStart, childParts);
|
|
1107
|
+
if (nested.found) return nested;
|
|
1108
|
+
}
|
|
1109
|
+
const skipped = skipCompleteValue(args.text, valueStart);
|
|
1110
|
+
if (!skipped.complete || skipped.end === void 0) {
|
|
1111
|
+
return { found: false };
|
|
1112
|
+
}
|
|
1113
|
+
i = skipWhitespace(args.text, skipped.end);
|
|
1114
|
+
if (args.text[i] === ",") {
|
|
1115
|
+
i = skipWhitespace(args.text, i + 1);
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
if (args.text[i] === "}") return { found: false };
|
|
1119
|
+
return { found: false };
|
|
1120
|
+
}
|
|
1121
|
+
return { found: false };
|
|
1122
|
+
};
|
|
1123
|
+
const visitArray = (start, currentParts) => {
|
|
1124
|
+
let i = skipWhitespace(args.text, start);
|
|
1125
|
+
let index = 0;
|
|
1126
|
+
while (i < args.text.length) {
|
|
1127
|
+
if (args.text[i] === "]") return { found: false };
|
|
1128
|
+
const childParts = [...currentParts, String(index)];
|
|
1129
|
+
if (pathEquals(childParts, targetParts)) {
|
|
1130
|
+
return { found: true, start: i };
|
|
1131
|
+
}
|
|
1132
|
+
if (isPathPrefix(childParts, targetParts)) {
|
|
1133
|
+
const nested = visitValue(i, childParts);
|
|
1134
|
+
if (nested.found) return nested;
|
|
1135
|
+
}
|
|
1136
|
+
const skipped = skipCompleteValue(args.text, i);
|
|
1137
|
+
if (!skipped.complete || skipped.end === void 0) {
|
|
1138
|
+
return { found: false };
|
|
1139
|
+
}
|
|
1140
|
+
i = skipWhitespace(args.text, skipped.end);
|
|
1141
|
+
if (args.text[i] === ",") {
|
|
1142
|
+
index += 1;
|
|
1143
|
+
i = skipWhitespace(args.text, i + 1);
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
if (args.text[i] === "]") return { found: false };
|
|
1147
|
+
return { found: false };
|
|
1148
|
+
}
|
|
1149
|
+
return { found: false };
|
|
1150
|
+
};
|
|
1151
|
+
return visitValue(0, []);
|
|
1152
|
+
};
|
|
1153
|
+
var extractCompletedValueAt = (args) => {
|
|
1154
|
+
const start = skipWhitespace(args.text, args.start);
|
|
1155
|
+
const first = args.text[start];
|
|
1156
|
+
if (!first) return { complete: false };
|
|
1058
1157
|
if (first === '"') {
|
|
1059
1158
|
const parsed = extractCompletedStringValueAt({
|
|
1060
1159
|
text: args.text,
|
|
1061
1160
|
start: start + 1
|
|
1062
1161
|
});
|
|
1063
1162
|
return parsed.complete ? {
|
|
1064
|
-
found: true,
|
|
1065
1163
|
complete: true,
|
|
1066
1164
|
value: parsed.value
|
|
1067
1165
|
} : {
|
|
1068
|
-
found: true,
|
|
1069
1166
|
complete: false
|
|
1070
1167
|
};
|
|
1071
1168
|
}
|
|
1072
1169
|
if (first === "{") {
|
|
1073
|
-
|
|
1170
|
+
return extractCompletedNestedValueAt({
|
|
1074
1171
|
text: args.text,
|
|
1075
1172
|
start,
|
|
1076
1173
|
opener: "{",
|
|
1077
1174
|
closer: "}"
|
|
1078
1175
|
});
|
|
1079
|
-
return parsed.complete ? {
|
|
1080
|
-
found: true,
|
|
1081
|
-
complete: true,
|
|
1082
|
-
value: parsed.value
|
|
1083
|
-
} : {
|
|
1084
|
-
found: true,
|
|
1085
|
-
complete: false
|
|
1086
|
-
};
|
|
1087
1176
|
}
|
|
1088
1177
|
if (first === "[") {
|
|
1089
|
-
|
|
1178
|
+
return extractCompletedNestedValueAt({
|
|
1090
1179
|
text: args.text,
|
|
1091
1180
|
start,
|
|
1092
1181
|
opener: "[",
|
|
1093
1182
|
closer: "]"
|
|
1094
1183
|
});
|
|
1095
|
-
return parsed.complete ? {
|
|
1096
|
-
found: true,
|
|
1097
|
-
complete: true,
|
|
1098
|
-
value: parsed.value
|
|
1099
|
-
} : {
|
|
1100
|
-
found: true,
|
|
1101
|
-
complete: false
|
|
1102
|
-
};
|
|
1103
1184
|
}
|
|
1104
1185
|
for (let i = start; i < args.text.length; i += 1) {
|
|
1105
1186
|
const ch = args.text[i];
|
|
1106
1187
|
if (ch === void 0) break;
|
|
1107
|
-
if (ch !== "," && ch !== "}") continue;
|
|
1188
|
+
if (ch !== "," && ch !== "}" && ch !== "]") continue;
|
|
1108
1189
|
const raw = args.text.slice(start, i).trim();
|
|
1109
|
-
if (!raw) {
|
|
1110
|
-
return {
|
|
1111
|
-
found: true,
|
|
1112
|
-
complete: false
|
|
1113
|
-
};
|
|
1114
|
-
}
|
|
1190
|
+
if (!raw) return { complete: false };
|
|
1115
1191
|
try {
|
|
1116
1192
|
return {
|
|
1117
|
-
found: true,
|
|
1118
1193
|
complete: true,
|
|
1119
1194
|
value: JSON.parse(raw)
|
|
1120
1195
|
};
|
|
1121
1196
|
} catch {
|
|
1122
|
-
return {
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1197
|
+
return { complete: false };
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
return { complete: false };
|
|
1201
|
+
};
|
|
1202
|
+
var extractCompletedNestedValueAt = (args) => {
|
|
1203
|
+
let inString = false;
|
|
1204
|
+
let isEscaped = false;
|
|
1205
|
+
let nesting = 0;
|
|
1206
|
+
for (let i = args.start; i < args.text.length; i += 1) {
|
|
1207
|
+
const ch = args.text[i];
|
|
1208
|
+
if (ch === void 0) break;
|
|
1209
|
+
if (inString) {
|
|
1210
|
+
if (isEscaped) {
|
|
1211
|
+
isEscaped = false;
|
|
1212
|
+
continue;
|
|
1213
|
+
}
|
|
1214
|
+
if (ch === "\\") {
|
|
1215
|
+
isEscaped = true;
|
|
1216
|
+
continue;
|
|
1217
|
+
}
|
|
1218
|
+
if (ch === '"') {
|
|
1219
|
+
inString = false;
|
|
1220
|
+
}
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
if (ch === '"') {
|
|
1224
|
+
inString = true;
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
if (ch === args.opener) {
|
|
1228
|
+
nesting += 1;
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
if (ch === args.closer) {
|
|
1232
|
+
nesting -= 1;
|
|
1233
|
+
if (nesting === 0) {
|
|
1234
|
+
const raw = args.text.slice(args.start, i + 1);
|
|
1235
|
+
try {
|
|
1236
|
+
return {
|
|
1237
|
+
complete: true,
|
|
1238
|
+
value: JSON.parse(raw)
|
|
1239
|
+
};
|
|
1240
|
+
} catch {
|
|
1241
|
+
return {
|
|
1242
|
+
complete: false
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1126
1246
|
}
|
|
1127
1247
|
}
|
|
1128
1248
|
return {
|
|
1249
|
+
complete: false
|
|
1250
|
+
};
|
|
1251
|
+
};
|
|
1252
|
+
var extractCompletedFieldValue = (args) => {
|
|
1253
|
+
const located = locateValueStart(args);
|
|
1254
|
+
if (!located.found || located.start === void 0) {
|
|
1255
|
+
return {
|
|
1256
|
+
found: located.found,
|
|
1257
|
+
complete: false
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
const parsed = extractCompletedValueAt({
|
|
1261
|
+
text: args.text,
|
|
1262
|
+
start: located.start
|
|
1263
|
+
});
|
|
1264
|
+
return parsed.complete ? {
|
|
1265
|
+
found: true,
|
|
1266
|
+
complete: true,
|
|
1267
|
+
value: parsed.value
|
|
1268
|
+
} : {
|
|
1129
1269
|
found: true,
|
|
1130
1270
|
complete: false
|
|
1131
1271
|
};
|
|
1132
1272
|
};
|
|
1133
1273
|
var extractCompletedArrayItems = (args) => {
|
|
1134
|
-
const
|
|
1135
|
-
if (start
|
|
1274
|
+
const located = locateValueStart(args);
|
|
1275
|
+
if (!located.found || located.start === void 0) return [];
|
|
1276
|
+
const arrayStart = skipWhitespace(args.text, located.start);
|
|
1277
|
+
if (args.text[arrayStart] !== "[") return [];
|
|
1278
|
+
const start = arrayStart + 1;
|
|
1136
1279
|
const items = [];
|
|
1137
1280
|
let inString = false;
|
|
1138
1281
|
let isEscaped = false;
|
|
@@ -1196,16 +1339,24 @@ var extractCompletedArrayItems = (args) => {
|
|
|
1196
1339
|
return items;
|
|
1197
1340
|
};
|
|
1198
1341
|
var extractStreamingStringValue = (args) => {
|
|
1199
|
-
const
|
|
1200
|
-
if (start
|
|
1342
|
+
const located = locateValueStart(args);
|
|
1343
|
+
if (!located.found || located.start === void 0) {
|
|
1344
|
+
return {
|
|
1345
|
+
found: located.found,
|
|
1346
|
+
complete: false,
|
|
1347
|
+
value: ""
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
const stringStart = skipWhitespace(args.text, located.start);
|
|
1351
|
+
if (args.text[stringStart] !== '"') {
|
|
1201
1352
|
return {
|
|
1202
|
-
found:
|
|
1353
|
+
found: true,
|
|
1203
1354
|
complete: false,
|
|
1204
1355
|
value: ""
|
|
1205
1356
|
};
|
|
1206
1357
|
}
|
|
1207
1358
|
let value = "";
|
|
1208
|
-
for (let i =
|
|
1359
|
+
for (let i = stringStart + 1; i < args.text.length; i += 1) {
|
|
1209
1360
|
const ch = args.text[i];
|
|
1210
1361
|
if (ch === void 0) break;
|
|
1211
1362
|
if (ch === '"') {
|
|
@@ -1316,7 +1467,7 @@ var emitReasonStructuredOutput = (args) => {
|
|
|
1316
1467
|
streamId: args.opId
|
|
1317
1468
|
});
|
|
1318
1469
|
};
|
|
1319
|
-
var
|
|
1470
|
+
var shouldStreamReasonStructured = (args) => (args.emit ?? true) && shouldStreamStructured(args.structured);
|
|
1320
1471
|
var resolveEffectiveReasoningIncludeThoughts = (args) => args.reasoning?.includeThoughts ?? args.model.options?.reasoning?.includeThoughts ?? false;
|
|
1321
1472
|
var resolveEffectiveResponseFormatType = (args) => args.responseFormat?.type ?? args.model.options?.responseFormat?.type;
|
|
1322
1473
|
var assertReasoningThoughtsCompatibility = (args) => {
|
|
@@ -1366,7 +1517,7 @@ async function useReason(args) {
|
|
|
1366
1517
|
const appendFieldPaths = resolveAppendFieldPaths(args.structured);
|
|
1367
1518
|
const textDeltaFieldPaths = resolveTextDeltaFieldPaths(args.structured);
|
|
1368
1519
|
const useStructuredIncrementalStreaming = Boolean(
|
|
1369
|
-
args.outputSchema && !args.interrupt && (setFieldPaths.length > 0 || appendFieldPaths.length > 0 || textDeltaFieldPaths.length > 0) && args.stream !== false &&
|
|
1520
|
+
args.outputSchema && !args.interrupt && (setFieldPaths.length > 0 || appendFieldPaths.length > 0 || textDeltaFieldPaths.length > 0) && args.stream !== false && shouldStreamReasonStructured(args)
|
|
1370
1521
|
);
|
|
1371
1522
|
let firstText = "";
|
|
1372
1523
|
let firstRaw;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/context.ts","../src/validation.ts","../src/interrupt.ts","../src/structured.ts","../src/structured-path.ts","../src/reason/checkpoint.ts","../src/reason/engine.ts","../src/reason-engine.ts","../src/reason/parsing.ts","../src/reason/prompting.ts","../src/reason/structured-stream.ts","../src/reason/use-reason.ts","../src/hooks.ts"],"sourcesContent":["// release-test: 2026-01-22\n/**\n * @kortyx/hooks\n *\n * Internal hook implementations resolved via async-local context.\n */\n\nexport type { HookRuntimeContext } from \"./context\";\nexport { runWithHookContext } from \"./context\";\nexport type {\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonResult,\n UseStructuredDataArgs,\n} from \"./hooks\";\nexport {\n useInterrupt,\n useNodeState,\n useReason,\n useRuntimeContext,\n useStructuredData,\n useWorkflowState,\n} from \"./hooks\";\nexport type {\n ReasonTraceAdapter,\n ReasonTraceAttributes,\n ReasonTraceSpan,\n ReasonTraceSpanEndArgs,\n ReasonTraceSpanStartArgs,\n} from \"./tracing\";\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n GraphState,\n InterruptInput,\n InterruptResult,\n NodeConfig,\n TokenUsage,\n} from \"@kortyx/core\";\nimport type { KortyxUsage } from \"@kortyx/providers\";\nimport type { ReasonTraceAdapter } from \"./tracing\";\n\ntype NodeStateStore = {\n byIndex: unknown[];\n byKey: Record<string, unknown>;\n};\n\ntype HookRuntimeState = {\n nodeState?: Record<string, unknown>;\n workflowState?: Record<string, unknown>;\n};\n\ntype StoredNodeStateEnvelope = {\n nodeId?: unknown;\n state?: unknown;\n};\n\ntype HookStatePatchedError = {\n __kortyxHookStatePatch?: Record<string, unknown>;\n};\n\nexport type HookNodeRuntimeContext = {\n graph: {\n name: string;\n node: string;\n };\n config: NodeConfig;\n emit: (event: string, payload: unknown) => void;\n awaitInterrupt: (args: InterruptInput) => InterruptResult;\n};\n\nexport type HookRuntimeContext = {\n node: HookNodeRuntimeContext;\n state: GraphState;\n reasonTrace?: ReasonTraceAdapter | undefined;\n};\n\ntype HookInternalContext = HookRuntimeContext & {\n nodeStateIndex: number;\n reasonCallIndex: number;\n currentNodeState: NodeStateStore;\n workflowState: Record<string, unknown>;\n tokenUsage?: TokenUsage | undefined;\n stateDirty: boolean;\n runtimeDirty: boolean;\n};\n\nconst storage = new AsyncLocalStorage<HookInternalContext>();\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nconst normalizeNodeState = (value: unknown): NodeStateStore => {\n if (Array.isArray(value)) {\n return { byIndex: [...value], byKey: {} };\n }\n\n if (isRecord(value)) {\n const byIndex = Array.isArray(value.byIndex) ? [...value.byIndex] : [];\n const byKey = isRecord(value.byKey) ? { ...value.byKey } : {};\n return { byIndex, byKey };\n }\n\n return { byIndex: [], byKey: {} };\n};\n\nconst cloneWorkflowState = (value: unknown): Record<string, unknown> =>\n isRecord(value) ? { ...value } : {};\n\nconst cloneTokenUsage = (value: unknown): TokenUsage | undefined => {\n if (!isRecord(value)) return undefined;\n const input = typeof value.input === \"number\" ? value.input : undefined;\n const output = typeof value.output === \"number\" ? value.output : undefined;\n const total = typeof value.total === \"number\" ? value.total : undefined;\n if (input === undefined && output === undefined && total === undefined) {\n return undefined;\n }\n return {\n input: input ?? 0,\n output: output ?? 0,\n total: total ?? 0,\n };\n};\n\nconst getHookRuntimeState = (state: GraphState): HookRuntimeState => {\n const runtime = (state.runtime ?? {}) as Record<string, unknown>;\n const internal = isRecord(runtime.__kortyx) ? runtime.__kortyx : undefined;\n const result: HookRuntimeState = {};\n if (isRecord(internal?.nodeState)) result.nodeState = internal?.nodeState;\n if (isRecord(internal?.workflowState)) {\n result.workflowState = internal?.workflowState;\n }\n return result;\n};\n\nconst createInternalContext = (\n ctx: HookRuntimeContext,\n): HookInternalContext => {\n const hookRuntimeState = getHookRuntimeState(ctx.state);\n const nodeId = ctx.node.graph.node;\n const storedNodeState = isRecord(hookRuntimeState.nodeState)\n ? (hookRuntimeState.nodeState as StoredNodeStateEnvelope)\n : undefined;\n const storedNodeId =\n typeof storedNodeState?.nodeId === \"string\"\n ? String(storedNodeState.nodeId)\n : \"\";\n const storedState = storedNodeState?.state;\n const currentNodeState =\n storedNodeId && storedNodeId === nodeId\n ? normalizeNodeState(storedState)\n : { byIndex: [], byKey: {} };\n\n return {\n ...ctx,\n nodeStateIndex: 0,\n reasonCallIndex: 0,\n currentNodeState,\n workflowState: cloneWorkflowState(hookRuntimeState.workflowState),\n tokenUsage: cloneTokenUsage(ctx.state.runtime?.tokenUsage),\n stateDirty: false,\n runtimeDirty: false,\n };\n};\n\nconst buildRuntimeStateUpdates = (ctx: HookInternalContext) => {\n const updates: Record<string, unknown> = {};\n\n if (ctx.stateDirty) {\n updates.__kortyx = {\n nodeState: {\n nodeId: ctx.node.graph.node,\n state: ctx.currentNodeState,\n },\n workflowState: ctx.workflowState,\n };\n }\n\n if (ctx.runtimeDirty && ctx.tokenUsage) {\n updates.tokenUsage = ctx.tokenUsage;\n }\n\n return Object.keys(updates).length > 0 ? updates : null;\n};\n\nconst cleanupCompletedReasonCheckpoints = (ctx: HookInternalContext): void => {\n let changed = false;\n\n for (const [key, value] of Object.entries(ctx.currentNodeState.byKey)) {\n if (!key.startsWith(\"__useReason:\")) continue;\n if (!isRecord(value) || value.status !== \"completed\") continue;\n delete ctx.currentNodeState.byKey[key];\n changed = true;\n }\n\n if (changed) ctx.stateDirty = true;\n};\n\nconst toTokenUsageDelta = (\n usage: KortyxUsage | undefined,\n): TokenUsage | undefined => {\n if (!usage) return undefined;\n\n const input = usage.input ?? 0;\n const output = usage.output ?? 0;\n const total = usage.total ?? input + output + (usage.reasoning ?? 0);\n\n if (input === 0 && output === 0 && total === 0) {\n return undefined;\n }\n\n return {\n input,\n output,\n total,\n };\n};\n\nexport function accumulateTokenUsage(usage: KortyxUsage | undefined): void {\n const delta = toTokenUsageDelta(usage);\n if (!delta) return;\n\n const ctx = getHookContext();\n const current = ctx.tokenUsage ?? {\n input: 0,\n output: 0,\n total: 0,\n };\n\n ctx.tokenUsage = {\n input: current.input + delta.input,\n output: current.output + delta.output,\n total: current.total + delta.total,\n };\n ctx.runtimeDirty = true;\n}\n\nexport function getReasonTraceAdapter(): ReasonTraceAdapter | undefined {\n return getHookContext().reasonTrace;\n}\n\nexport async function runWithHookContext<T>(\n ctx: HookRuntimeContext,\n fn: () => Promise<T>,\n): Promise<{ result: T; runtimeUpdates: Record<string, unknown> | null }> {\n const internal = createInternalContext(ctx);\n try {\n const result = await storage.run(internal, fn);\n cleanupCompletedReasonCheckpoints(internal);\n return { result, runtimeUpdates: buildRuntimeStateUpdates(internal) };\n } catch (err) {\n const runtimeUpdates = buildRuntimeStateUpdates(internal);\n if (runtimeUpdates) {\n const currentRuntime = isRecord(internal.state.runtime)\n ? (internal.state.runtime as Record<string, unknown>)\n : {};\n internal.state.runtime = {\n ...currentRuntime,\n ...runtimeUpdates,\n } as unknown as GraphState[\"runtime\"];\n if (err && typeof err === \"object\") {\n (err as HookStatePatchedError).__kortyxHookStatePatch = runtimeUpdates;\n }\n }\n throw err;\n }\n}\n\nexport function getHookContext(): HookInternalContext {\n const ctx = storage.getStore();\n if (!ctx) {\n throw new Error(\"Hooks can only be used while a node is executing.\");\n }\n return ctx;\n}\n","import type { SchemaLike } from \"./types\";\n\nexport const parseWithSchema = <T>(\n schema: SchemaLike<T> | undefined,\n value: unknown,\n label: string,\n): T => {\n if (!schema) return value as T;\n\n const parsed = schema.safeParse(value);\n if (parsed.success) return parsed.data;\n\n const parsedError =\n \"error\" in parsed && parsed.error ? parsed.error : undefined;\n const reason =\n typeof parsedError?.message === \"string\" && parsedError.message.length > 0\n ? parsedError.message\n : \"invalid payload\";\n throw new Error(`${label} validation failed: ${reason}`);\n};\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport { getHookContext } from \"./context\";\nimport type { UseInterruptArgs } from \"./types\";\nimport { parseWithSchema } from \"./validation\";\n\nexport const awaitInterruptInternal = <\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseInterruptArgs<TRequest, TResponse>,\n): Promise<TResponse> => {\n const ctx = getHookContext();\n\n const request = parseWithSchema(\n args.requestSchema,\n args.request,\n \"useInterrupt request\",\n );\n\n const enrichedRequest = {\n ...request,\n ...(typeof args.schemaId === \"string\" && args.schemaId.length > 0\n ? { schemaId: args.schemaId }\n : {}),\n ...(typeof args.schemaVersion === \"string\" && args.schemaVersion.length > 0\n ? { schemaVersion: args.schemaVersion }\n : {}),\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n ...(args.meta && typeof args.meta === \"object\" && !Array.isArray(args.meta)\n ? { meta: args.meta }\n : {}),\n } as InterruptInput;\n\n const raw = ctx.node.awaitInterrupt(enrichedRequest);\n const response = parseWithSchema(\n args.responseSchema,\n raw,\n \"useInterrupt response\",\n );\n\n return Promise.resolve(response);\n};\n","import { randomUUID } from \"node:crypto\";\nimport { getHookContext } from \"./context\";\nimport { assertStructuredPath } from \"./structured-path\";\nimport type { UseReasonStructuredConfig, UseStructuredDataArgs } from \"./types\";\nimport { parseWithSchema } from \"./validation\";\n\nconst createStructuredStreamId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nexport const emitStructuredData = <TData = unknown>(\n args: UseStructuredDataArgs<TData>,\n): void => {\n const ctx = getHookContext();\n const streamId =\n typeof args.streamId === \"string\" && args.streamId.length > 0\n ? args.streamId\n : createStructuredStreamId();\n const dataType =\n typeof args.dataType === \"string\" && args.dataType.length > 0\n ? args.dataType\n : \"generic\";\n\n const base = {\n node: ctx.node.graph.node,\n streamId,\n dataType,\n ...(typeof args.schemaId === \"string\" && args.schemaId.length > 0\n ? { schemaId: args.schemaId }\n : {}),\n ...(typeof args.schemaVersion === \"string\" && args.schemaVersion.length > 0\n ? { schemaVersion: args.schemaVersion }\n : {}),\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n };\n\n if (args.kind === \"set\") {\n assertStructuredPath(args.path, \"useStructuredData\");\n const value = parseWithSchema(\n args.valueSchema,\n args.value,\n \"useStructuredData value\",\n );\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"set\",\n path: args.path,\n value,\n });\n return;\n }\n\n if (args.kind === \"append\") {\n assertStructuredPath(args.path, \"useStructuredData\");\n const items = args.items.map((item) =>\n parseWithSchema(args.itemSchema, item, \"useStructuredData append item\"),\n );\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"append\",\n path: args.path,\n items,\n });\n return;\n }\n\n if (args.kind === \"text-delta\") {\n assertStructuredPath(args.path, \"useStructuredData\");\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"text-delta\",\n path: args.path,\n delta: args.delta,\n });\n return;\n }\n\n const validated = parseWithSchema(\n args.dataSchema,\n args.data,\n \"useStructuredData data\",\n );\n\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"final\",\n data: validated,\n });\n};\n\nexport const shouldEmitStructured = (\n cfg: UseReasonStructuredConfig | undefined,\n): boolean => Boolean(cfg) && (cfg?.stream ?? true);\n","export const parseStructuredPath = (path: string, source: string): string[] => {\n if (path.length === 0) {\n throw new Error(`${source} path must be a non-empty dot-separated string.`);\n }\n\n const parts = path.split(\".\");\n if (parts.some((part) => part.length === 0)) {\n throw new Error(\n `${source} path \"${path}\" must not contain empty segments.`,\n );\n }\n\n return parts;\n};\n\nexport const assertStructuredPath = (path: string, source: string): void => {\n parseStructuredPath(path, source);\n};\n","import type { InterruptInput } from \"@kortyx/core\";\nimport type {\n KortyxFinishReason,\n KortyxProviderMetadata,\n KortyxUsage,\n KortyxWarning,\n} from \"@kortyx/providers\";\nimport type { UseReasonResult } from \"../types\";\n\nexport type ReasonInterruptCheckpoint = {\n status: \"awaiting_interrupt\";\n request: InterruptInput;\n firstText: string;\n firstRaw?: unknown;\n firstUsage?: KortyxUsage;\n firstFinishReason?: KortyxFinishReason;\n firstProviderMetadata?: KortyxProviderMetadata;\n firstWarnings?: KortyxWarning[];\n firstOutput?: unknown;\n};\n\nexport type ReasonCompletedCheckpoint = {\n status: \"completed\";\n result: UseReasonResult<unknown, unknown>;\n};\n\nexport const resolveReasonCheckpointKey = (args: {\n id?: string;\n autoIndex: number;\n}): string =>\n typeof args.id === \"string\" && args.id.length > 0\n ? `__useReason:${args.id}`\n : `__useReason:auto:${args.autoIndex}`;\n\nexport const readReasonCheckpoint = (\n raw: unknown,\n): ReasonInterruptCheckpoint | undefined => {\n if (!raw || typeof raw !== \"object\") return undefined;\n const value = raw as Record<string, unknown>;\n if (value.status !== \"awaiting_interrupt\") return undefined;\n if (typeof value.firstText !== \"string\") return undefined;\n if (!value.request || typeof value.request !== \"object\") return undefined;\n return {\n status: \"awaiting_interrupt\",\n request: value.request as InterruptInput,\n firstText: value.firstText,\n ...(Object.hasOwn(value, \"firstRaw\") ? { firstRaw: value.firstRaw } : {}),\n ...(Object.hasOwn(value, \"firstUsage\")\n ? { firstUsage: value.firstUsage as KortyxUsage }\n : {}),\n ...(Object.hasOwn(value, \"firstFinishReason\")\n ? { firstFinishReason: value.firstFinishReason as KortyxFinishReason }\n : {}),\n ...(Object.hasOwn(value, \"firstProviderMetadata\")\n ? {\n firstProviderMetadata:\n value.firstProviderMetadata as KortyxProviderMetadata,\n }\n : {}),\n ...(Object.hasOwn(value, \"firstWarnings\")\n ? { firstWarnings: value.firstWarnings as KortyxWarning[] }\n : {}),\n ...(Object.hasOwn(value, \"firstOutput\")\n ? { firstOutput: value.firstOutput }\n : {}),\n };\n};\n\nexport const readReasonCompletedCheckpoint = (\n raw: unknown,\n): ReasonCompletedCheckpoint | undefined => {\n if (!raw || typeof raw !== \"object\") return undefined;\n const value = raw as Record<string, unknown>;\n if (value.status !== \"completed\") return undefined;\n if (!value.result || typeof value.result !== \"object\") return undefined;\n return {\n status: \"completed\",\n result: value.result as UseReasonResult<unknown, unknown>,\n };\n};\n\nexport const resolveHookStatePatch = (args: {\n nodeId: string;\n currentNodeState: unknown;\n workflowState: Record<string, unknown>;\n}): Record<string, unknown> => ({\n __kortyx: {\n nodeState: {\n nodeId: args.nodeId,\n state: args.currentNodeState,\n },\n workflowState: args.workflowState,\n },\n});\n","import { randomUUID } from \"node:crypto\";\nimport type {\n KortyxReasoningOptions,\n KortyxResponseFormat,\n ProviderModelRef,\n} from \"@kortyx/providers\";\nimport { getHookContext } from \"../context\";\nimport type { RunReasonEngineResult } from \"../reason-engine\";\nimport { runReasonEngine } from \"../reason-engine\";\n\nexport type ReasonEngineInput = {\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n maxOutputTokens?: number | undefined;\n stopSequences?: string[] | undefined;\n abortSignal?: AbortSignal | undefined;\n reasoning?: KortyxReasoningOptions | undefined;\n responseFormat?: KortyxResponseFormat | undefined;\n providerOptions?: Record<string, unknown> | undefined;\n emit?: boolean | undefined;\n stream?: boolean | undefined;\n onTextChunk?: ((text: string) => void) | undefined;\n};\n\nexport const createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nexport async function reasonEngine(\n args: ReasonEngineInput,\n meta: { id?: string; opId: string },\n inputOverride?: string,\n): Promise<RunReasonEngineResult> {\n const ctx = getHookContext();\n\n return runReasonEngine({\n model: args.model,\n input: inputOverride ?? args.input,\n system: args.system,\n temperature: args.temperature,\n maxOutputTokens: args.maxOutputTokens,\n stopSequences: args.stopSequences,\n abortSignal: args.abortSignal,\n reasoning: args.reasoning,\n responseFormat: args.responseFormat,\n providerOptions: args.providerOptions,\n defaultTemperature: ctx.node.config?.model?.temperature,\n stream: args.stream,\n emit: args.emit,\n onTextChunk: args.onTextChunk,\n nodeId: ctx.node.graph.node,\n emitEvent: ctx.node.emit,\n reasonTrace: ctx.reasonTrace,\n id: meta.id,\n opId: meta.opId,\n });\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n KortyxFinishReason,\n KortyxPromptMessage,\n KortyxProviderMetadata,\n KortyxReasoningOptions,\n KortyxResponseFormat,\n KortyxUsage,\n KortyxWarning,\n ProviderModelRef,\n} from \"@kortyx/providers\";\nimport type { ReasonTraceAdapter, ReasonTraceSpan } from \"./tracing\";\n\nexport interface RunReasonEngineArgs {\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n maxOutputTokens?: number | undefined;\n stopSequences?: string[] | undefined;\n abortSignal?: AbortSignal | undefined;\n reasoning?: KortyxReasoningOptions | undefined;\n responseFormat?: KortyxResponseFormat | undefined;\n providerOptions?: Record<string, unknown> | undefined;\n defaultTemperature?: number | undefined;\n stream?: boolean | undefined;\n emit?: boolean | undefined;\n nodeId?: string | undefined;\n emitEvent?: ((event: string, payload: unknown) => void) | undefined;\n onTextChunk?: ((text: string) => void) | undefined;\n id?: string | undefined;\n opId?: string | undefined;\n segmentId?: string | undefined;\n reasonTrace?: ReasonTraceAdapter | undefined;\n}\n\nexport interface RunReasonEngineResult {\n text: string;\n raw?: unknown;\n usage?: KortyxUsage;\n finishReason?: KortyxFinishReason;\n providerMetadata?: KortyxProviderMetadata;\n warnings?: KortyxWarning[];\n}\n\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\nconst createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nconst emitNodeEvent = (\n emitEvent: RunReasonEngineArgs[\"emitEvent\"],\n nodeId: string | undefined,\n event: string,\n payload: Record<string, unknown>,\n): void => {\n if (!emitEvent) return;\n emitEvent(event, {\n ...payload,\n ...(typeof nodeId === \"string\" && nodeId.length > 0\n ? { node: nodeId }\n : {}),\n });\n};\n\nexport async function runReasonEngine(\n args: RunReasonEngineArgs,\n): Promise<RunReasonEngineResult> {\n const stream = args.stream ?? args.model.options?.streaming ?? true;\n const emit = args.emit ?? true;\n const temperature =\n args.temperature ??\n args.model.options?.temperature ??\n args.defaultTemperature;\n const maxOutputTokens =\n args.maxOutputTokens ?? args.model.options?.maxOutputTokens;\n const stopSequences = args.stopSequences ?? args.model.options?.stopSequences;\n const abortSignal = args.abortSignal ?? args.model.options?.abortSignal;\n const reasoning = args.reasoning ?? args.model.options?.reasoning;\n const responseFormat =\n args.responseFormat ?? args.model.options?.responseFormat;\n const providerOptions =\n args.providerOptions ?? args.model.options?.providerOptions;\n\n const model = args.model.provider.getModel(args.model.modelId, {\n ...(temperature !== undefined ? { temperature } : {}),\n streaming: stream,\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(stopSequences !== undefined ? { stopSequences } : {}),\n ...(abortSignal !== undefined ? { abortSignal } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(responseFormat !== undefined ? { responseFormat } : {}),\n ...(providerOptions !== undefined ? { providerOptions } : {}),\n });\n\n const messages: KortyxPromptMessage[] = [];\n if (typeof args.system === \"string\" && args.system.length > 0) {\n messages.push({ role: \"system\", content: args.system });\n }\n messages.push({ role: \"user\", content: String(args.input ?? \"\") });\n\n const opId =\n typeof args.opId === \"string\" && args.opId.length > 0\n ? args.opId\n : createRuntimeId();\n const segmentId =\n typeof args.segmentId === \"string\" && args.segmentId.length > 0\n ? args.segmentId\n : createRuntimeId();\n\n const commonMeta: Record<string, unknown> = {\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n opId,\n segmentId,\n };\n const traceSpan = args.reasonTrace?.startSpan({\n name: \"runReasonEngine\",\n attributes: {\n ...commonMeta,\n providerId: args.model.provider.id,\n modelId: args.model.modelId,\n stream,\n emit,\n ...(typeof args.nodeId === \"string\" && args.nodeId.length > 0\n ? { nodeId: args.nodeId }\n : {}),\n },\n });\n\n const endTrace = (\n span: ReasonTraceSpan | undefined,\n result: RunReasonEngineResult,\n ): void => {\n span?.end?.({\n ...(result.usage !== undefined ? { usage: result.usage } : {}),\n ...(result.finishReason !== undefined\n ? { finishReason: result.finishReason }\n : {}),\n ...(result.providerMetadata !== undefined\n ? { providerMetadata: result.providerMetadata }\n : {}),\n ...(result.warnings !== undefined ? { warnings: result.warnings } : {}),\n attributes: {\n textLength: result.text.length,\n },\n });\n };\n\n const failTrace = (\n span: ReasonTraceSpan | undefined,\n error: unknown,\n ): void => {\n span?.fail?.(error, {\n attributes: {\n providerId: args.model.provider.id,\n modelId: args.model.modelId,\n },\n });\n };\n\n try {\n if (stream) {\n let final = \"\";\n let raw: unknown;\n let usage: KortyxUsage | undefined;\n let finishReason: KortyxFinishReason | undefined;\n let providerMetadata: KortyxProviderMetadata | undefined;\n let warnings: KortyxWarning[] | undefined;\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n }\n\n const response = await model.stream(messages);\n for await (const chunk of response) {\n switch (chunk.type) {\n case \"text-delta\": {\n if (chunk.delta.length === 0) break;\n final += chunk.delta;\n args.onTextChunk?.(chunk.delta);\n if (chunk.raw !== undefined) {\n raw = chunk.raw;\n }\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: chunk.delta,\n });\n }\n break;\n }\n case \"finish\": {\n if (chunk.raw !== undefined) {\n raw = chunk.raw;\n }\n if (chunk.usage !== undefined) {\n usage = chunk.usage;\n }\n if (chunk.finishReason !== undefined) {\n finishReason = chunk.finishReason;\n }\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n if (chunk.warnings !== undefined) {\n warnings = chunk.warnings;\n }\n break;\n }\n case \"raw\": {\n raw = chunk.raw;\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n break;\n }\n case \"error\": {\n if (chunk.raw !== undefined) {\n raw = chunk.raw;\n }\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n if (chunk.warnings !== undefined) {\n warnings = chunk.warnings;\n }\n throw toError(chunk.error);\n }\n }\n }\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n const result = {\n text: final,\n ...(raw !== undefined ? { raw } : {}),\n ...(usage !== undefined ? { usage } : {}),\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(providerMetadata !== undefined ? { providerMetadata } : {}),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n endTrace(traceSpan, result);\n return result;\n }\n\n const response = await model.invoke(messages);\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n if (response.content) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: response.content,\n });\n }\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n const result = {\n text: response.content,\n ...(response.raw !== undefined ? { raw: response.raw } : {}),\n ...(response.usage !== undefined ? { usage: response.usage } : {}),\n ...(response.finishReason !== undefined\n ? { finishReason: response.finishReason }\n : {}),\n ...(response.providerMetadata !== undefined\n ? { providerMetadata: response.providerMetadata }\n : {}),\n ...(response.warnings !== undefined\n ? { warnings: response.warnings }\n : {}),\n };\n endTrace(traceSpan, result);\n return result;\n } catch (error) {\n failTrace(traceSpan, error);\n throw error;\n }\n}\n","import type { InterruptInput } from \"@kortyx/core\";\nimport type { KortyxFinishReason } from \"@kortyx/providers\";\nimport type { SchemaLike } from \"../types\";\nimport { parseWithSchema } from \"../validation\";\n\nconst tryJsonParse = (\n value: string,\n):\n | { ok: true; value: unknown; error?: never }\n | { ok: false; error: string } => {\n try {\n return { ok: true, value: JSON.parse(value) };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n};\n\nconst extractJsonCodeBlock = (value: string): string | null => {\n const match = value.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n if (!match || typeof match[1] !== \"string\") return null;\n const inner = match[1].trim();\n return inner.length > 0 ? inner : null;\n};\n\nconst tryStringify = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nexport const resolveOutputCandidate = (text: string): unknown => {\n const trimmed = text.trim();\n if (!trimmed) return text;\n\n const direct = tryJsonParse(trimmed);\n if (direct.ok) return direct.value;\n\n const block = extractJsonCodeBlock(trimmed);\n if (block) {\n const parsedBlock = tryJsonParse(block);\n if (parsedBlock.ok) return parsedBlock.value;\n }\n\n return text;\n};\n\nconst looksLikeStructuredJsonAttempt = (value: string): boolean => {\n const trimmed = value.trim();\n if (!trimmed) return false;\n\n return (\n trimmed.startsWith(\"{\") ||\n trimmed.startsWith(\"[\") ||\n /^```(?:json)?/i.test(trimmed)\n );\n};\n\nconst isLikelyTruncatedStructuredOutput = (text: string): boolean => {\n const trimmed = text.trim();\n if (!looksLikeStructuredJsonAttempt(trimmed)) return false;\n\n const direct = tryJsonParse(trimmed);\n if (!direct.ok && direct.error) return true;\n\n const block = extractJsonCodeBlock(trimmed);\n if (!block) return false;\n\n const parsedBlock = tryJsonParse(block);\n return !parsedBlock.ok && Boolean(parsedBlock.error);\n};\n\nconst createTruncatedStructuredOutputError = (label: string): Error =>\n new Error(\n `${label} was truncated before producing valid structured output. The model stopped due to output length. Increase maxOutputTokens or simplify the requested output.`,\n );\n\nconst createInvalidStructuredOutputError = (label: string): Error =>\n new Error(\n `${label} did not produce valid structured output. The model returned text instead of the expected JSON payload. This often happens when output is truncated or the provider does not follow JSON mode. Increase maxOutputTokens or simplify the requested output.`,\n );\n\nexport const parseReasonOutputWithSchema = <TOutput>(args: {\n text: string;\n schema: SchemaLike<TOutput>;\n finishReason?: KortyxFinishReason;\n label: string;\n}): TOutput => {\n const candidate = resolveOutputCandidate(args.text);\n\n try {\n return parseWithSchema(args.schema, candidate, args.label);\n } catch (error) {\n if (\n args.finishReason?.unified === \"length\" ||\n isLikelyTruncatedStructuredOutput(args.text)\n ) {\n throw createTruncatedStructuredOutputError(args.label);\n }\n if (typeof candidate === \"string\" && candidate.trim().length > 0) {\n throw createInvalidStructuredOutputError(args.label);\n }\n throw error;\n }\n};\n\nexport const parseInterruptFirstPassResult = <\n TRequest extends InterruptInput = InterruptInput,\n TOutput = unknown,\n>(args: {\n text: string;\n requestSchema: SchemaLike<TRequest>;\n outputSchema?: SchemaLike<TOutput>;\n finishReason?: KortyxFinishReason;\n mode?: \"required\" | \"optional\" | undefined;\n}):\n | {\n draftText: string;\n interruptRequired: boolean;\n request: TRequest;\n output?: TOutput;\n }\n | {\n draftText: string;\n interruptRequired: false;\n request?: undefined;\n output?: TOutput;\n } => {\n const candidate = resolveOutputCandidate(args.text);\n if (!isRecord(candidate)) {\n if (\n args.finishReason?.unified === \"length\" ||\n isLikelyTruncatedStructuredOutput(args.text)\n ) {\n throw createTruncatedStructuredOutputError(\"useReason output\");\n }\n if (typeof candidate === \"string\" && candidate.trim().length > 0) {\n throw createInvalidStructuredOutputError(\"useReason output\");\n }\n throw new Error(\n \"useReason first pass with interrupt must return a JSON object.\",\n );\n }\n\n const mode = args.mode ?? \"required\";\n let interruptRequired = true;\n if (mode === \"optional\") {\n if (\n candidate.decision !== \"continue\" &&\n candidate.decision !== \"interrupt\"\n ) {\n throw new Error(\n 'useReason optional interrupt first pass must include decision \"continue\" or \"interrupt\".',\n );\n }\n interruptRequired = candidate.decision === \"interrupt\";\n\n if (!interruptRequired) {\n const hasUnexpectedRequest = [\n candidate.interruptRequest,\n candidate.request,\n candidate.interrupt,\n ].some((value) => value !== null && value !== undefined);\n\n if (hasUnexpectedRequest) {\n throw new Error(\n 'useReason optional interrupt first pass with decision \"continue\" must not include an interrupt request.',\n );\n }\n }\n }\n\n let request: TRequest | undefined;\n if (interruptRequired) {\n const requestCandidates: unknown[] = [\n candidate.interruptRequest,\n candidate.request,\n candidate.interrupt,\n mode === \"required\" ? candidate : undefined,\n ];\n const requestPayload = requestCandidates.find(\n (value) => value !== null && value !== undefined,\n );\n\n request = parseWithSchema(\n args.requestSchema,\n requestPayload,\n \"useReason interrupt.request\",\n );\n }\n\n let output: TOutput | undefined;\n if (args.outputSchema) {\n const outputPayload = Object.hasOwn(candidate, \"output\")\n ? candidate.output\n : candidate;\n try {\n output = parseWithSchema(\n args.outputSchema,\n outputPayload,\n \"useReason output\",\n );\n } catch (error) {\n if (\n args.finishReason?.unified === \"length\" ||\n isLikelyTruncatedStructuredOutput(args.text)\n ) {\n throw createTruncatedStructuredOutputError(\"useReason output\");\n }\n if (\n typeof outputPayload === \"string\" &&\n outputPayload.trim().length > 0\n ) {\n throw createInvalidStructuredOutputError(\"useReason output\");\n }\n throw error;\n }\n }\n\n const explicitDraft =\n typeof candidate.draftText === \"string\" && candidate.draftText.length > 0\n ? candidate.draftText\n : typeof candidate.text === \"string\" && candidate.text.length > 0\n ? candidate.text\n : undefined;\n\n if (!args.outputSchema && !explicitDraft) {\n throw new Error(\n \"useReason first pass with interrupt requires `draftText` when outputSchema is not provided.\",\n );\n }\n\n const draftText =\n explicitDraft ??\n (output !== undefined ? tryStringify(output) : String(args.text ?? \"\"));\n\n if (!interruptRequired) {\n return {\n draftText,\n interruptRequired: false,\n ...(output !== undefined ? { output } : {}),\n };\n }\n\n return {\n draftText,\n interruptRequired: true,\n request: request as TRequest,\n ...(output !== undefined ? { output } : {}),\n };\n};\n","import type { InterruptInput } from \"@kortyx/core\";\nimport { toJSONSchema } from \"zod\";\nimport type { SchemaLike } from \"../types\";\n\nconst tryStringify = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n};\n\nconst tryGetSchemaHint = (schema: unknown): string | undefined => {\n try {\n const hint = toJSONSchema(schema as never);\n return JSON.stringify(hint, null, 2);\n } catch {\n return undefined;\n }\n};\n\nconst withSchemaHint = (\n input: string,\n label: string,\n schema: unknown,\n): string => {\n const hint = tryGetSchemaHint(schema);\n if (!hint) return input;\n return `${input}\\n\\n${label}:\\n${hint}`;\n};\n\nexport const defaultInterruptFirstPassInput = (args: {\n input: string;\n requestSchema: SchemaLike<unknown>;\n outputSchema?: SchemaLike<unknown>;\n mode?: \"required\" | \"optional\" | undefined;\n}): string => {\n const mode = args.mode ?? \"required\";\n const base =\n mode === \"optional\"\n ? args.outputSchema\n ? [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: decision, output, interruptRequest, draftText.\",\n '- decision must be either \"continue\" or \"interrupt\".',\n '- Use decision \"continue\" when you can produce the final output without asking the user.',\n '- Use decision \"interrupt\" only when user input is needed before finalizing.',\n \"- output must match the expected output JSON schema.\",\n '- When decision is \"interrupt\", interruptRequest must match the expected interrupt request JSON schema and must be a non-null object.',\n '- When decision is \"continue\", interruptRequest must be null.',\n \"- draftText should be a concise plain-language summary of output.\",\n ].join(\"\\n\\n\")\n : [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: decision, draftText, interruptRequest.\",\n '- decision must be either \"continue\" or \"interrupt\".',\n '- Use decision \"continue\" when you can produce the final answer without asking the user.',\n '- Use decision \"interrupt\" only when user input is needed before finalizing.',\n \"- draftText should be the current answer text.\",\n '- When decision is \"interrupt\", interruptRequest must match the expected interrupt request JSON schema and must be a non-null object.',\n '- When decision is \"continue\", interruptRequest must be null.',\n ].join(\"\\n\\n\")\n : args.outputSchema\n ? [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: output, interruptRequest, draftText.\",\n \"- output must match the expected output JSON schema.\",\n \"- interruptRequest must match the expected interrupt request JSON schema.\",\n \"- interruptRequest must be a non-null object.\",\n \"- draftText should be a concise plain-language summary of output.\",\n \"- If uncertain, still return a valid interruptRequest with safe default options.\",\n ].join(\"\\n\\n\")\n : [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: draftText, interruptRequest.\",\n \"- draftText should be the current draft answer text.\",\n \"- interruptRequest must match the expected interrupt request JSON schema.\",\n \"- interruptRequest must be a non-null object.\",\n \"- If uncertain, still return a valid interruptRequest with safe default options.\",\n ].join(\"\\n\\n\");\n\n const withInterruptSchema = withSchemaHint(\n base,\n \"Expected interrupt request JSON schema (for `interruptRequest`)\",\n args.requestSchema,\n );\n\n if (!args.outputSchema) return withInterruptSchema;\n const withOutputSchema = withSchemaHint(\n withInterruptSchema,\n \"Expected output JSON schema (for `output`)\",\n args.outputSchema,\n );\n return [\n withOutputSchema,\n \"JSON template:\",\n mode === \"optional\"\n ? '{ \"decision\": \"continue\", \"output\": { ... }, \"interruptRequest\": null, \"draftText\": \"...\" }'\n : '{ \"output\": { ... }, \"interruptRequest\": { ... }, \"draftText\": \"...\" }',\n ].join(\"\\n\\n\");\n};\n\nexport const defaultContinuationInput = (args: {\n input: string;\n draftText: string;\n draftOutput?: unknown;\n request: InterruptInput;\n response: unknown;\n}): string =>\n [\n \"You are continuing a paused reasoning task after user input.\",\n \"Update the previous result using the user response and return the final answer only.\",\n \"If the previous output was JSON, return JSON in the same schema.\",\n \"\",\n `Original request:\\n${args.input}`,\n `Draft answer text:\\n${args.draftText}`,\n `Draft output object:\\n${tryStringify(args.draftOutput ?? args.draftText)}`,\n `Interrupt request shown to user:\\n${tryStringify(args.request)}`,\n `User response:\\n${tryStringify(args.response)}`,\n ].join(\"\\n\\n\");\n\nexport const withOutputGuardrails = (\n input: string,\n schema?: SchemaLike<unknown>,\n): string => {\n const base = [\n input,\n \"Output rules:\",\n \"- Return only JSON, no markdown fences.\",\n \"- Ensure the response conforms to the expected output schema.\",\n \"- Do not include explanatory text outside the JSON object.\",\n ].join(\"\\n\\n\");\n return withSchemaHint(base, \"Expected output JSON schema\", schema);\n};\n\nexport const withStructuredStreamHints = (\n input: string,\n args: {\n setFieldPaths?: string[];\n appendFieldPaths?: string[];\n textDeltaFieldPaths?: string[];\n },\n): string => {\n const rules: string[] = [];\n\n for (const path of args.setFieldPaths ?? []) {\n rules.push(\n `- For the top-level field \\`${path}\\`, write one stable final value and do not rewrite it after it is complete.`,\n );\n }\n\n for (const path of args.appendFieldPaths ?? []) {\n rules.push(\n `- For the top-level array field \\`${path}\\`, write items in final order and finish each item before starting the next.`,\n );\n rules.push(\n `- Once an item in \\`${path}\\` is complete, do not rewrite or reorder earlier items.`,\n );\n }\n\n for (const path of args.textDeltaFieldPaths ?? []) {\n rules.push(\n `- For the top-level string field \\`${path}\\`, write the value progressively by appending text to the end.`,\n );\n rules.push(\n `- Do not rewrite or replace the earlier prefix of \\`${path}\\` once emitted.`,\n );\n }\n\n if (rules.length === 0) return input;\n\n return [\n input,\n \"Streaming rules:\",\n ...rules,\n \"- Keep the overall response as valid JSON.\",\n ].join(\"\\n\\n\");\n};\n","import { assertStructuredPath } from \"../structured-path\";\nimport type { UseReasonStructuredConfig } from \"../types\";\n\nconst escapeRegex = (value: string): string =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nconst findTopLevelArrayStart = (text: string, path: string): number => {\n const match = new RegExp(`\"${escapeRegex(path)}\"\\\\s*:\\\\s*\\\\[`).exec(text);\n return match ? match.index + match[0].length : -1;\n};\n\nexport const resolveAppendFieldPaths = (\n cfg: UseReasonStructuredConfig | undefined,\n): string[] => {\n const fields = cfg?.fields;\n if (!fields) return [];\n\n const appendPaths = Object.entries(fields)\n .filter(([, mode]) => mode === \"append\")\n .map(([path]) => path);\n\n for (const path of appendPaths) {\n assertStructuredPath(path, \"useReason structured append\");\n if (path.includes(\".\")) {\n throw new Error(\n \"useReason structured append streaming requires non-empty top-level array field keys.\",\n );\n }\n }\n\n return appendPaths;\n};\n\nexport const resolveSetFieldPaths = (\n cfg: UseReasonStructuredConfig | undefined,\n): string[] => {\n const fields = cfg?.fields;\n if (!fields) return [];\n\n const setPaths = Object.entries(fields)\n .filter(([, mode]) => mode === \"set\")\n .map(([path]) => path);\n\n for (const path of setPaths) {\n assertStructuredPath(path, \"useReason structured set\");\n if (path.includes(\".\")) {\n throw new Error(\n \"useReason structured set streaming requires non-empty top-level field keys.\",\n );\n }\n }\n\n return setPaths;\n};\n\nexport const resolveTextDeltaFieldPaths = (\n cfg: UseReasonStructuredConfig | undefined,\n): string[] => {\n const fields = cfg?.fields;\n if (!fields) return [];\n\n const textPaths = Object.entries(fields)\n .filter(([, mode]) => mode === \"text-delta\")\n .map(([path]) => path);\n\n for (const path of textPaths) {\n assertStructuredPath(path, \"useReason structured text-delta\");\n if (path.includes(\".\")) {\n throw new Error(\n \"useReason structured text-delta streaming requires non-empty top-level string field keys.\",\n );\n }\n }\n\n return textPaths;\n};\n\nconst findTopLevelFieldValueStart = (text: string, path: string): number => {\n const match = new RegExp(`\"${escapeRegex(path)}\"\\\\s*:\\\\s*`).exec(text);\n return match ? match.index + match[0].length : -1;\n};\n\nconst findTopLevelStringStart = (text: string, path: string): number => {\n const match = new RegExp(`\"${escapeRegex(path)}\"\\\\s*:\\\\s*\"`).exec(text);\n return match ? match.index + match[0].length : -1;\n};\n\nconst extractCompletedStringValueAt = (args: {\n text: string;\n start: number;\n}): { complete: boolean; value?: string } => {\n let value = \"\";\n\n for (let i = args.start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (ch === '\"') {\n return {\n complete: true,\n value,\n };\n }\n\n if (ch !== \"\\\\\") {\n value += ch;\n continue;\n }\n\n const next = args.text[i + 1];\n if (!next) {\n return {\n complete: false,\n };\n }\n\n if (\n next === '\"' ||\n next === \"\\\\\" ||\n next === \"/\" ||\n next === \"b\" ||\n next === \"f\" ||\n next === \"n\" ||\n next === \"r\" ||\n next === \"t\"\n ) {\n value +=\n next === \"b\"\n ? \"\\b\"\n : next === \"f\"\n ? \"\\f\"\n : next === \"n\"\n ? \"\\n\"\n : next === \"r\"\n ? \"\\r\"\n : next === \"t\"\n ? \"\\t\"\n : next;\n i += 1;\n continue;\n }\n\n if (next === \"u\") {\n const hex = args.text.slice(i + 2, i + 6);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) {\n return {\n complete: false,\n };\n }\n value += String.fromCharCode(Number.parseInt(hex, 16));\n i += 5;\n continue;\n }\n\n return {\n complete: false,\n };\n }\n\n return {\n complete: false,\n };\n};\n\nconst extractCompletedNestedValueAt = (args: {\n text: string;\n start: number;\n opener: \"{\" | \"[\";\n closer: \"}\" | \"]\";\n}): { complete: boolean; value?: unknown } => {\n let inString = false;\n let isEscaped = false;\n let nesting = 0;\n\n for (let i = args.start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\") {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n\n if (ch === '\"') {\n inString = true;\n continue;\n }\n\n if (ch === args.opener) {\n nesting += 1;\n continue;\n }\n\n if (ch === args.closer) {\n nesting -= 1;\n if (nesting === 0) {\n const raw = args.text.slice(args.start, i + 1);\n try {\n return {\n complete: true,\n value: JSON.parse(raw),\n };\n } catch {\n return {\n complete: false,\n };\n }\n }\n }\n }\n\n return {\n complete: false,\n };\n};\n\nexport const extractCompletedFieldValue = (args: {\n text: string;\n path: string;\n}): { found: boolean; complete: boolean; value?: unknown } => {\n const start = findTopLevelFieldValueStart(args.text, args.path);\n if (start < 0) {\n return {\n found: false,\n complete: false,\n };\n }\n\n const first = args.text[start];\n if (!first) {\n return {\n found: true,\n complete: false,\n };\n }\n\n if (first === '\"') {\n const parsed = extractCompletedStringValueAt({\n text: args.text,\n start: start + 1,\n });\n return parsed.complete\n ? {\n found: true,\n complete: true,\n value: parsed.value,\n }\n : {\n found: true,\n complete: false,\n };\n }\n\n if (first === \"{\") {\n const parsed = extractCompletedNestedValueAt({\n text: args.text,\n start,\n opener: \"{\",\n closer: \"}\",\n });\n return parsed.complete\n ? {\n found: true,\n complete: true,\n value: parsed.value,\n }\n : {\n found: true,\n complete: false,\n };\n }\n\n if (first === \"[\") {\n const parsed = extractCompletedNestedValueAt({\n text: args.text,\n start,\n opener: \"[\",\n closer: \"]\",\n });\n return parsed.complete\n ? {\n found: true,\n complete: true,\n value: parsed.value,\n }\n : {\n found: true,\n complete: false,\n };\n }\n\n for (let i = start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n if (ch !== \",\" && ch !== \"}\") continue;\n\n const raw = args.text.slice(start, i).trim();\n if (!raw) {\n return {\n found: true,\n complete: false,\n };\n }\n\n try {\n return {\n found: true,\n complete: true,\n value: JSON.parse(raw),\n };\n } catch {\n return {\n found: true,\n complete: false,\n };\n }\n }\n\n return {\n found: true,\n complete: false,\n };\n};\n\nexport const extractCompletedArrayItems = (args: {\n text: string;\n path: string;\n}): unknown[] => {\n const start = findTopLevelArrayStart(args.text, args.path);\n if (start < 0) return [];\n\n const items: unknown[] = [];\n let inString = false;\n let isEscaped = false;\n let nesting = 0;\n let itemStart = -1;\n\n for (let i = start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\") {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n\n if (ch === '\"') {\n inString = true;\n if (itemStart < 0) itemStart = i;\n continue;\n }\n\n if (itemStart < 0) {\n if (/\\s/.test(ch) || ch === \",\") continue;\n if (ch === \"]\") break;\n itemStart = i;\n if (ch === \"{\" || ch === \"[\") {\n nesting = 1;\n } else {\n nesting = 0;\n }\n continue;\n }\n\n if (ch === \"{\" || ch === \"[\") {\n nesting += 1;\n continue;\n }\n\n if (ch === \"}\" || ch === \"]\") {\n if (nesting > 0) {\n nesting -= 1;\n continue;\n }\n }\n\n if (nesting === 0 && (ch === \",\" || ch === \"]\")) {\n const raw = args.text.slice(itemStart, i).trim();\n if (raw) {\n try {\n items.push(JSON.parse(raw));\n } catch {}\n }\n itemStart = -1;\n if (ch === \"]\") break;\n }\n }\n\n return items;\n};\n\nexport const extractStreamingStringValue = (args: {\n text: string;\n path: string;\n}): { found: boolean; complete: boolean; value: string } => {\n const start = findTopLevelStringStart(args.text, args.path);\n if (start < 0) {\n return {\n found: false,\n complete: false,\n value: \"\",\n };\n }\n\n let value = \"\";\n\n for (let i = start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (ch === '\"') {\n return {\n found: true,\n complete: true,\n value,\n };\n }\n\n if (ch !== \"\\\\\") {\n value += ch;\n continue;\n }\n\n const next = args.text[i + 1];\n if (!next) {\n return {\n found: true,\n complete: false,\n value,\n };\n }\n\n if (\n next === '\"' ||\n next === \"\\\\\" ||\n next === \"/\" ||\n next === \"b\" ||\n next === \"f\" ||\n next === \"n\" ||\n next === \"r\" ||\n next === \"t\"\n ) {\n value +=\n next === \"b\"\n ? \"\\b\"\n : next === \"f\"\n ? \"\\f\"\n : next === \"n\"\n ? \"\\n\"\n : next === \"r\"\n ? \"\\r\"\n : next === \"t\"\n ? \"\\t\"\n : next;\n i += 1;\n continue;\n }\n\n if (next === \"u\") {\n const hex = args.text.slice(i + 2, i + 6);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) {\n return {\n found: true,\n complete: false,\n value,\n };\n }\n value += String.fromCharCode(Number.parseInt(hex, 16));\n i += 5;\n continue;\n }\n\n return {\n found: true,\n complete: false,\n value,\n };\n }\n\n return {\n found: true,\n complete: false,\n value,\n };\n};\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport type {\n KortyxFinishReason,\n KortyxProviderMetadata,\n KortyxUsage,\n KortyxWarning,\n} from \"@kortyx/providers\";\nimport {\n accumulateTokenUsage,\n getHookContext,\n getReasonTraceAdapter,\n} from \"../context\";\nimport { awaitInterruptInternal } from \"../interrupt\";\nimport { emitStructuredData, shouldEmitStructured } from \"../structured\";\nimport type { ReasonTraceSpan } from \"../tracing\";\nimport type { SchemaLike, UseReasonArgs, UseReasonResult } from \"../types\";\nimport { parseWithSchema } from \"../validation\";\nimport {\n type ReasonInterruptCheckpoint,\n readReasonCheckpoint,\n readReasonCompletedCheckpoint,\n resolveHookStatePatch,\n resolveReasonCheckpointKey,\n} from \"./checkpoint\";\nimport { createRuntimeId, reasonEngine } from \"./engine\";\nimport {\n parseInterruptFirstPassResult,\n parseReasonOutputWithSchema,\n} from \"./parsing\";\nimport {\n defaultContinuationInput,\n defaultInterruptFirstPassInput,\n withOutputGuardrails,\n withStructuredStreamHints,\n} from \"./prompting\";\nimport {\n extractCompletedArrayItems,\n extractCompletedFieldValue,\n extractStreamingStringValue,\n resolveAppendFieldPaths,\n resolveSetFieldPaths,\n resolveTextDeltaFieldPaths,\n} from \"./structured-stream\";\n\nconst mergeUsage = (\n left: KortyxUsage | undefined,\n right: KortyxUsage | undefined,\n): KortyxUsage | undefined => {\n if (!left) return right;\n if (!right) return left;\n\n const sum = (\n a: number | undefined,\n b: number | undefined,\n ): number | undefined =>\n a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n\n const raw =\n left.raw || right.raw\n ? {\n ...(left.raw ?? {}),\n ...(right.raw ?? {}),\n }\n : undefined;\n const input = sum(left.input, right.input);\n const output = sum(left.output, right.output);\n const total = sum(left.total, right.total);\n const reasoning = sum(left.reasoning, right.reasoning);\n const cacheRead = sum(left.cacheRead, right.cacheRead);\n const cacheWrite = sum(left.cacheWrite, right.cacheWrite);\n const merged: KortyxUsage = {};\n\n if (input !== undefined) merged.input = input;\n if (output !== undefined) merged.output = output;\n if (total !== undefined) merged.total = total;\n if (reasoning !== undefined) merged.reasoning = reasoning;\n if (cacheRead !== undefined) merged.cacheRead = cacheRead;\n if (cacheWrite !== undefined) merged.cacheWrite = cacheWrite;\n if (raw) merged.raw = raw;\n\n return merged;\n};\n\nconst mergeWarnings = (\n left: KortyxWarning[] | undefined,\n right: KortyxWarning[] | undefined,\n): KortyxWarning[] | undefined => {\n if (!left?.length) return right;\n if (!right?.length) return left;\n\n const seen = new Set<string>();\n const merged: KortyxWarning[] = [];\n for (const warning of [...left, ...right]) {\n const key = JSON.stringify(warning);\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(warning);\n }\n return merged;\n};\n\nconst mergeProviderMetadata = (\n left: KortyxProviderMetadata | undefined,\n right: KortyxProviderMetadata | undefined,\n): KortyxProviderMetadata | undefined => {\n if (!left) return right;\n if (!right) return left;\n return {\n ...left,\n ...right,\n };\n};\n\nconst emitReasonStructuredOutput = <TOutput>(args: {\n id?: string;\n opId: string;\n output: TOutput;\n structured: UseReasonArgs<TOutput>[\"structured\"];\n emit: boolean;\n}): void => {\n if (!args.emit || !shouldEmitStructured(args.structured)) return;\n\n emitStructuredData<TOutput>({\n dataType: args.structured?.dataType ?? \"reason-output\",\n data: args.output,\n kind: \"final\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(args.id ? { id: args.id } : {}),\n streamId: args.opId,\n });\n};\n\nconst shouldEmitReasonStructured = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): boolean => (args.emit ?? true) && shouldEmitStructured(args.structured);\n\nconst resolveEffectiveReasoningIncludeThoughts = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): boolean =>\n args.reasoning?.includeThoughts ??\n args.model.options?.reasoning?.includeThoughts ??\n false;\n\nconst resolveEffectiveResponseFormatType = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): \"text\" | \"json\" | undefined =>\n args.responseFormat?.type ?? args.model.options?.responseFormat?.type;\n\nconst assertReasoningThoughtsCompatibility = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): void => {\n if (!resolveEffectiveReasoningIncludeThoughts(args)) return;\n\n const usesStructuredOutput =\n Boolean(args.outputSchema) ||\n Boolean(args.interrupt) ||\n Boolean(args.structured) ||\n resolveEffectiveResponseFormatType(args) === \"json\";\n\n if (!usesStructuredOutput) return;\n\n throw new Error(\n \"useReason does not support reasoning.includeThoughts with structured output, interrupt mode, or JSON responseFormat. Disable includeThoughts for this call.\",\n );\n};\n\nexport async function useReason<\n TOutput = unknown,\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): Promise<UseReasonResult<TOutput, TResponse>> {\n assertReasoningThoughtsCompatibility(args);\n const ctx = getHookContext();\n const id =\n typeof args.id === \"string\" && args.id.length > 0 ? args.id : undefined;\n const opId = createRuntimeId();\n const checkpointKey = resolveReasonCheckpointKey({\n ...(id ? { id } : {}),\n autoIndex: ctx.reasonCallIndex++,\n });\n const existingCompleted = readReasonCompletedCheckpoint(\n ctx.currentNodeState.byKey[checkpointKey],\n );\n\n if (existingCompleted) {\n return existingCompleted.result as UseReasonResult<TOutput, TResponse>;\n }\n\n const existingCheckpoint = readReasonCheckpoint(\n ctx.currentNodeState.byKey[checkpointKey],\n );\n\n const reasonMeta =\n typeof id === \"string\" ? ({ id, opId } as const) : ({ opId } as const);\n const traceSpan: ReasonTraceSpan | undefined =\n getReasonTraceAdapter()?.startSpan({\n name: \"useReason\",\n attributes: {\n ...(id ? { id } : {}),\n opId,\n nodeId: ctx.node.graph.node,\n providerId: args.model.provider.id,\n modelId: args.model.modelId,\n stream: args.stream ?? args.model.options?.streaming ?? true,\n emit: args.emit ?? true,\n hasOutputSchema: Boolean(args.outputSchema),\n hasInterrupt: Boolean(args.interrupt),\n hasStructured: Boolean(args.structured),\n },\n });\n const suppressTextStream = Boolean(args.outputSchema || args.interrupt);\n const setFieldPaths = resolveSetFieldPaths(args.structured);\n const appendFieldPaths = resolveAppendFieldPaths(args.structured);\n const textDeltaFieldPaths = resolveTextDeltaFieldPaths(args.structured);\n const useStructuredIncrementalStreaming = Boolean(\n args.outputSchema &&\n !args.interrupt &&\n (setFieldPaths.length > 0 ||\n appendFieldPaths.length > 0 ||\n textDeltaFieldPaths.length > 0) &&\n args.stream !== false &&\n shouldEmitReasonStructured(args),\n );\n\n let firstText = \"\";\n let firstRaw: unknown;\n let firstOutput: TOutput | undefined;\n let firstInterruptRequest: TRequest | undefined;\n let firstInterruptRequired = false;\n\n let finalText = \"\";\n let finalRaw: unknown;\n let finalOutput: TOutput | undefined;\n let aggregatedUsage: KortyxUsage | undefined;\n let finalFinishReason: KortyxFinishReason | undefined;\n let aggregatedProviderMetadata: KortyxProviderMetadata | undefined;\n let aggregatedWarnings: KortyxWarning[] | undefined;\n const emittedSetValues = new Map<string, string>();\n const emittedAppendCounts = new Map<string, number>();\n const emittedTextValues = new Map<string, string>();\n\n if (existingCheckpoint) {\n firstText = existingCheckpoint.firstText;\n firstRaw = existingCheckpoint.firstRaw;\n firstOutput = existingCheckpoint.firstOutput as TOutput | undefined;\n finalText = firstText;\n finalRaw = firstRaw;\n finalOutput = firstOutput;\n aggregatedUsage = existingCheckpoint.firstUsage;\n finalFinishReason = existingCheckpoint.firstFinishReason;\n aggregatedProviderMetadata = existingCheckpoint.firstProviderMetadata;\n aggregatedWarnings = existingCheckpoint.firstWarnings;\n traceSpan?.addEvent?.(\"useReason.resume\", {\n checkpointKey,\n });\n } else {\n const first = await reasonEngine(\n {\n ...args,\n emit: suppressTextStream ? false : args.emit,\n stream: useStructuredIncrementalStreaming\n ? true\n : suppressTextStream\n ? false\n : args.stream,\n ...(useStructuredIncrementalStreaming\n ? {\n onTextChunk: (delta: string) => {\n firstText += delta;\n finalText = firstText;\n\n for (const path of setFieldPaths) {\n const current = extractCompletedFieldValue({\n text: firstText,\n path,\n });\n if (!current.found || !current.complete) continue;\n\n const nextSerialized = JSON.stringify(current.value);\n if (emittedSetValues.get(path) === nextSerialized) continue;\n\n emittedSetValues.set(path, nextSerialized);\n emitStructuredData({\n kind: \"set\",\n path,\n value: current.value,\n dataType: args.structured?.dataType ?? \"reason-output\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n streamId: opId,\n });\n }\n\n for (const path of appendFieldPaths) {\n const items = extractCompletedArrayItems({\n text: firstText,\n path,\n });\n const emittedAppendCount = emittedAppendCounts.get(path) ?? 0;\n if (items.length <= emittedAppendCount) continue;\n\n const nextItems = items.slice(emittedAppendCount);\n emittedAppendCounts.set(path, items.length);\n emitStructuredData({\n kind: \"append\",\n path,\n items: nextItems,\n dataType: args.structured?.dataType ?? \"reason-output\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n streamId: opId,\n });\n }\n\n for (const path of textDeltaFieldPaths) {\n const current = extractStreamingStringValue({\n text: firstText,\n path,\n });\n const emittedTextValue = emittedTextValues.get(path) ?? \"\";\n if (\n !current.found ||\n current.value.length <= emittedTextValue.length ||\n !current.value.startsWith(emittedTextValue)\n ) {\n continue;\n }\n\n const nextDelta = current.value.slice(\n emittedTextValue.length,\n );\n emittedTextValues.set(path, current.value);\n if (nextDelta.length === 0) continue;\n\n emitStructuredData({\n kind: \"text-delta\",\n path,\n delta: nextDelta,\n dataType: args.structured?.dataType ?? \"reason-output\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n streamId: opId,\n });\n }\n },\n }\n : {}),\n },\n reasonMeta,\n args.interrupt\n ? defaultInterruptFirstPassInput({\n input: args.input,\n requestSchema: args.interrupt.requestSchema,\n mode: args.interrupt.mode ?? \"required\",\n ...(args.outputSchema\n ? { outputSchema: args.outputSchema as SchemaLike<unknown> }\n : {}),\n })\n : args.outputSchema\n ? withOutputGuardrails(\n withStructuredStreamHints(args.input, {\n ...(setFieldPaths.length > 0 ? { setFieldPaths } : {}),\n ...(appendFieldPaths.length > 0 ? { appendFieldPaths } : {}),\n ...(textDeltaFieldPaths.length > 0\n ? { textDeltaFieldPaths }\n : {}),\n }),\n args.outputSchema as SchemaLike<unknown>,\n )\n : undefined,\n );\n firstRaw = first.raw;\n finalRaw = first.raw;\n accumulateTokenUsage(first.usage);\n aggregatedUsage = mergeUsage(aggregatedUsage, first.usage);\n finalFinishReason = first.finishReason;\n aggregatedProviderMetadata = mergeProviderMetadata(\n aggregatedProviderMetadata,\n first.providerMetadata,\n );\n aggregatedWarnings = mergeWarnings(aggregatedWarnings, first.warnings);\n traceSpan?.addEvent?.(\"useReason.first-pass.complete\", {\n textLength: first.text.length,\n hasInterrupt: Boolean(args.interrupt),\n });\n\n if (args.interrupt) {\n const firstPass = parseInterruptFirstPassResult<TRequest, TOutput>({\n text: first.text,\n requestSchema: args.interrupt.requestSchema,\n ...(first.finishReason ? { finishReason: first.finishReason } : {}),\n ...(args.outputSchema\n ? { outputSchema: args.outputSchema as SchemaLike<TOutput> }\n : {}),\n mode: args.interrupt.mode ?? \"required\",\n });\n firstText = firstPass.draftText;\n finalText = firstPass.draftText;\n firstInterruptRequired = firstPass.interruptRequired;\n firstInterruptRequest = firstPass.request;\n firstOutput = firstPass.output;\n finalOutput = firstPass.output;\n } else {\n firstText = first.text;\n finalText = first.text;\n if (args.outputSchema) {\n firstOutput = parseReasonOutputWithSchema({\n text: first.text,\n schema: args.outputSchema,\n ...(first.finishReason ? { finishReason: first.finishReason } : {}),\n label: \"useReason output\",\n });\n }\n finalOutput = firstOutput;\n }\n }\n\n let interruptResponse: TResponse | undefined;\n\n if (args.interrupt && (existingCheckpoint || firstInterruptRequired)) {\n const requestSchema = args.interrupt.requestSchema;\n\n const interruptRequest = existingCheckpoint\n ? parseWithSchema(\n requestSchema,\n existingCheckpoint.request,\n \"useReason interrupt.request\",\n )\n : firstInterruptRequest;\n\n if (!interruptRequest) {\n throw new Error(\n \"useReason interrupt request is missing; first pass did not produce a valid interrupt payload.\",\n );\n }\n\n if (!existingCheckpoint) {\n ctx.currentNodeState.byKey[checkpointKey] = {\n status: \"awaiting_interrupt\",\n request: interruptRequest,\n firstText,\n ...(firstRaw !== undefined ? { firstRaw } : {}),\n ...(aggregatedUsage !== undefined\n ? { firstUsage: aggregatedUsage }\n : {}),\n ...(finalFinishReason !== undefined\n ? { firstFinishReason: finalFinishReason }\n : {}),\n ...(aggregatedProviderMetadata !== undefined\n ? { firstProviderMetadata: aggregatedProviderMetadata }\n : {}),\n ...(aggregatedWarnings !== undefined\n ? { firstWarnings: aggregatedWarnings }\n : {}),\n ...(firstOutput !== undefined ? { firstOutput } : {}),\n } satisfies ReasonInterruptCheckpoint;\n ctx.stateDirty = true;\n }\n\n const resumeStatePatch = resolveHookStatePatch({\n nodeId: ctx.node.graph.node,\n currentNodeState: ctx.currentNodeState,\n workflowState: ctx.workflowState,\n });\n\n interruptResponse = await awaitInterruptInternal<TRequest, TResponse>({\n request: interruptRequest,\n requestSchema,\n responseSchema: args.interrupt.responseSchema,\n ...(args.interrupt.schemaId ? { schemaId: args.interrupt.schemaId } : {}),\n ...(args.interrupt.schemaVersion\n ? { schemaVersion: args.interrupt.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n meta: {\n __kortyxResumeStatePatch: resumeStatePatch,\n },\n });\n traceSpan?.addEvent?.(\"useReason.interrupt.resolved\", {\n checkpointKey,\n });\n\n if (Object.hasOwn(ctx.currentNodeState.byKey, checkpointKey)) {\n delete ctx.currentNodeState.byKey[checkpointKey];\n ctx.stateDirty = true;\n }\n\n const continuationInput = defaultContinuationInput({\n input: args.input,\n draftText: firstText,\n ...(firstOutput !== undefined ? { draftOutput: firstOutput } : {}),\n request: interruptRequest,\n response: interruptResponse,\n });\n\n const second = await reasonEngine(\n {\n ...args,\n emit: suppressTextStream ? false : args.emit,\n stream: suppressTextStream ? false : args.stream,\n },\n reasonMeta,\n args.outputSchema\n ? withOutputGuardrails(\n continuationInput,\n args.outputSchema as SchemaLike<unknown>,\n )\n : continuationInput,\n );\n finalText = second.text;\n finalRaw = second.raw;\n accumulateTokenUsage(second.usage);\n aggregatedUsage = mergeUsage(aggregatedUsage, second.usage);\n finalFinishReason = second.finishReason;\n aggregatedProviderMetadata = mergeProviderMetadata(\n aggregatedProviderMetadata,\n second.providerMetadata,\n );\n aggregatedWarnings = mergeWarnings(aggregatedWarnings, second.warnings);\n traceSpan?.addEvent?.(\"useReason.continuation.complete\", {\n textLength: second.text.length,\n });\n\n if (args.outputSchema) {\n finalOutput = parseReasonOutputWithSchema({\n text: finalText,\n schema: args.outputSchema,\n ...(second.finishReason ? { finishReason: second.finishReason } : {}),\n label: \"useReason output\",\n });\n }\n }\n\n if (finalOutput !== undefined) {\n emitReasonStructuredOutput<TOutput>({\n ...(id ? { id } : {}),\n opId,\n output: finalOutput,\n structured: args.structured,\n emit: args.emit ?? true,\n });\n }\n\n const result = {\n ...(id ? { id } : {}),\n opId,\n text: finalText,\n ...(finalRaw !== undefined ? { raw: finalRaw } : {}),\n ...(aggregatedUsage !== undefined ? { usage: aggregatedUsage } : {}),\n ...(finalFinishReason !== undefined\n ? { finishReason: finalFinishReason }\n : {}),\n ...(aggregatedProviderMetadata !== undefined\n ? { providerMetadata: aggregatedProviderMetadata }\n : {}),\n ...(aggregatedWarnings !== undefined\n ? { warnings: aggregatedWarnings }\n : {}),\n ...(finalOutput !== undefined ? { output: finalOutput } : {}),\n ...(interruptResponse !== undefined ? { interruptResponse } : {}),\n };\n\n if (args.interrupt) {\n ctx.currentNodeState.byKey[checkpointKey] = {\n status: \"completed\",\n result,\n };\n ctx.stateDirty = true;\n }\n\n traceSpan?.end?.({\n ...(aggregatedUsage !== undefined ? { usage: aggregatedUsage } : {}),\n ...(finalFinishReason !== undefined\n ? { finishReason: finalFinishReason }\n : {}),\n ...(aggregatedProviderMetadata !== undefined\n ? { providerMetadata: aggregatedProviderMetadata }\n : {}),\n ...(aggregatedWarnings !== undefined\n ? { warnings: aggregatedWarnings }\n : {}),\n attributes: {\n textLength: finalText.length,\n resumedFromCheckpoint: Boolean(existingCheckpoint),\n interrupted: Boolean(interruptResponse !== undefined),\n },\n });\n\n return result;\n}\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport { getHookContext } from \"./context\";\nimport { awaitInterruptInternal } from \"./interrupt\";\nimport { useReason as useReasonInternal } from \"./reason/use-reason\";\nimport { emitStructuredData } from \"./structured\";\nimport type {\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonResult,\n UseStructuredDataArgs,\n} from \"./types\";\n\nexport type {\n SchemaLike,\n StructuredDataKind,\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonInterruptConfig,\n UseReasonResult,\n UseReasonStructuredConfig,\n UseStructuredDataAppendArgs,\n UseStructuredDataArgs,\n UseStructuredDataFinalArgs,\n UseStructuredDataSetArgs,\n UseStructuredDataTextDeltaArgs,\n} from \"./types\";\n\ntype StateSetter<T> = (next: T | ((prev: T) => T)) => void;\n\nexport function useStructuredData<TData = unknown>(\n args: UseStructuredDataArgs<TData>,\n): void {\n emitStructuredData(args);\n}\n\nexport function useReason<\n TOutput = unknown,\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): Promise<UseReasonResult<TOutput, TResponse>> {\n return useReasonInternal(args);\n}\n\nexport function useInterrupt<\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(args: UseInterruptArgs<TRequest, TResponse>): Promise<TResponse> {\n return awaitInterruptInternal(args);\n}\n\nexport function useRuntimeContext<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n>(): TContext {\n const ctx = getHookContext();\n const config = ctx.state.config;\n const context =\n config && typeof config === \"object\" && \"context\" in config\n ? (config as { context?: unknown }).context\n : undefined;\n\n return context && typeof context === \"object\" && !Array.isArray(context)\n ? (context as TContext)\n : ({} as TContext);\n}\n\nexport function useNodeState<T>(initialValue: T): [T, StateSetter<T>] {\n const ctx = getHookContext();\n const nodeState = ctx.currentNodeState;\n\n const index = ctx.nodeStateIndex++;\n if (index >= nodeState.byIndex.length) {\n nodeState.byIndex[index] = initialValue as T;\n ctx.stateDirty = true;\n }\n\n const getValue = () => nodeState.byIndex[index] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n nodeState.byIndex[index] = resolved;\n ctx.stateDirty = true;\n };\n\n return [getValue(), setValue];\n}\n\nexport function useWorkflowState<T>(\n key: string,\n ...rest: [] | [T]\n): [T, StateSetter<T>] {\n const ctx = getHookContext();\n const workflowState = ctx.workflowState;\n const hasInitial = rest.length > 0;\n const initialValue = rest[0];\n\n if (!Object.hasOwn(workflowState, key) && hasInitial) {\n workflowState[key] = initialValue as T;\n ctx.stateDirty = true;\n }\n\n const getValue = () => workflowState[key] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n workflowState[key] = resolved;\n ctx.stateDirty = true;\n };\n\n return [getValue(), setValue];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;AAwDl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AAI,aAAa;AAAA,EACnB;AAEA,SAAO,CAAC,SAAS,GAAG,QAAQ;AAC9B;AAEO,SAAS,iBACd,QACG,MACkB;AACrB,QAAM,MAAM,eAAe;AAC3B,QAAM,gBAAgB,IAAI;AAC1B,QAAM,aAAa,KAAK,SAAS;AACjC,QAAM,eAAe,KAAK,CAAC;AAE3B,MAAI,CAAC,OAAO,OAAO,eAAe,GAAG,KAAK,YAAY;AACpD,kBAAc,GAAG,IAAI;AACrB,QAAI,aAAa;AAAA,EACnB;AAEA,QAAM,WAAW,MAAM,cAAc,GAAG;AACxC,QAAM,WAA2B,CAAC,SAAS;AACzC,UAAM,OAAO,SAAS;AACtB,UAAM,WACJ,OAAO,SAAS,aAAc,KAAqB,IAAI,IAAI;AAC7D,kBAAc,GAAG,IAAI;AACrB,QAAI,aAAa;AAAA,EACnB;AAEA,SAAO,CAAC,SAAS,GAAG,QAAQ;AAC9B;","names":["useReason","import_node_crypto","import_node_crypto","response","result","createRuntimeId","isRecord","tryStringify","createRuntimeId","useReason"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/context.ts","../src/validation.ts","../src/interrupt.ts","../src/structured.ts","../src/structured-path.ts","../src/reason/checkpoint.ts","../src/reason/engine.ts","../src/reason-engine.ts","../src/reason/parsing.ts","../src/reason/prompting.ts","../src/reason/structured-stream.ts","../src/reason/use-reason.ts","../src/hooks.ts"],"sourcesContent":["// release-test: 2026-01-22\n/**\n * @kortyx/hooks\n *\n * Internal hook implementations resolved via async-local context.\n */\n\nexport type { HookRuntimeContext } from \"./context\";\nexport { runWithHookContext } from \"./context\";\nexport type {\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonResult,\n UseStructuredDataArgs,\n} from \"./hooks\";\nexport {\n useInterrupt,\n useNodeState,\n useReason,\n useRuntimeContext,\n useStructuredData,\n useWorkflowState,\n} from \"./hooks\";\nexport type {\n ReasonTraceAdapter,\n ReasonTraceAttributes,\n ReasonTraceSpan,\n ReasonTraceSpanEndArgs,\n ReasonTraceSpanStartArgs,\n} from \"./tracing\";\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n GraphState,\n InterruptInput,\n InterruptResult,\n NodeConfig,\n TokenUsage,\n} from \"@kortyx/core\";\nimport type { KortyxUsage } from \"@kortyx/providers\";\nimport type { ReasonTraceAdapter } from \"./tracing\";\n\ntype NodeStateStore = {\n byIndex: unknown[];\n byKey: Record<string, unknown>;\n};\n\ntype HookRuntimeState = {\n nodeState?: Record<string, unknown>;\n workflowState?: Record<string, unknown>;\n};\n\ntype StoredNodeStateEnvelope = {\n nodeId?: unknown;\n state?: unknown;\n};\n\ntype HookStatePatchedError = {\n __kortyxHookStatePatch?: Record<string, unknown>;\n};\n\nexport type HookNodeRuntimeContext = {\n graph: {\n name: string;\n node: string;\n };\n config: NodeConfig;\n emit: (event: string, payload: unknown) => void;\n awaitInterrupt: (args: InterruptInput) => InterruptResult;\n};\n\nexport type HookRuntimeContext = {\n node: HookNodeRuntimeContext;\n state: GraphState;\n reasonTrace?: ReasonTraceAdapter | undefined;\n};\n\ntype HookInternalContext = HookRuntimeContext & {\n nodeStateIndex: number;\n reasonCallIndex: number;\n currentNodeState: NodeStateStore;\n workflowState: Record<string, unknown>;\n tokenUsage?: TokenUsage | undefined;\n stateDirty: boolean;\n runtimeDirty: boolean;\n};\n\nconst storage = new AsyncLocalStorage<HookInternalContext>();\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nconst normalizeNodeState = (value: unknown): NodeStateStore => {\n if (Array.isArray(value)) {\n return { byIndex: [...value], byKey: {} };\n }\n\n if (isRecord(value)) {\n const byIndex = Array.isArray(value.byIndex) ? [...value.byIndex] : [];\n const byKey = isRecord(value.byKey) ? { ...value.byKey } : {};\n return { byIndex, byKey };\n }\n\n return { byIndex: [], byKey: {} };\n};\n\nconst cloneWorkflowState = (value: unknown): Record<string, unknown> =>\n isRecord(value) ? { ...value } : {};\n\nconst cloneTokenUsage = (value: unknown): TokenUsage | undefined => {\n if (!isRecord(value)) return undefined;\n const input = typeof value.input === \"number\" ? value.input : undefined;\n const output = typeof value.output === \"number\" ? value.output : undefined;\n const total = typeof value.total === \"number\" ? value.total : undefined;\n if (input === undefined && output === undefined && total === undefined) {\n return undefined;\n }\n return {\n input: input ?? 0,\n output: output ?? 0,\n total: total ?? 0,\n };\n};\n\nconst getHookRuntimeState = (state: GraphState): HookRuntimeState => {\n const runtime = (state.runtime ?? {}) as Record<string, unknown>;\n const internal = isRecord(runtime.__kortyx) ? runtime.__kortyx : undefined;\n const result: HookRuntimeState = {};\n if (isRecord(internal?.nodeState)) result.nodeState = internal?.nodeState;\n if (isRecord(internal?.workflowState)) {\n result.workflowState = internal?.workflowState;\n }\n return result;\n};\n\nconst createInternalContext = (\n ctx: HookRuntimeContext,\n): HookInternalContext => {\n const hookRuntimeState = getHookRuntimeState(ctx.state);\n const nodeId = ctx.node.graph.node;\n const storedNodeState = isRecord(hookRuntimeState.nodeState)\n ? (hookRuntimeState.nodeState as StoredNodeStateEnvelope)\n : undefined;\n const storedNodeId =\n typeof storedNodeState?.nodeId === \"string\"\n ? String(storedNodeState.nodeId)\n : \"\";\n const storedState = storedNodeState?.state;\n const currentNodeState =\n storedNodeId && storedNodeId === nodeId\n ? normalizeNodeState(storedState)\n : { byIndex: [], byKey: {} };\n\n return {\n ...ctx,\n nodeStateIndex: 0,\n reasonCallIndex: 0,\n currentNodeState,\n workflowState: cloneWorkflowState(hookRuntimeState.workflowState),\n tokenUsage: cloneTokenUsage(ctx.state.runtime?.tokenUsage),\n stateDirty: false,\n runtimeDirty: false,\n };\n};\n\nconst buildRuntimeStateUpdates = (ctx: HookInternalContext) => {\n const updates: Record<string, unknown> = {};\n\n if (ctx.stateDirty) {\n updates.__kortyx = {\n nodeState: {\n nodeId: ctx.node.graph.node,\n state: ctx.currentNodeState,\n },\n workflowState: ctx.workflowState,\n };\n }\n\n if (ctx.runtimeDirty && ctx.tokenUsage) {\n updates.tokenUsage = ctx.tokenUsage;\n }\n\n return Object.keys(updates).length > 0 ? updates : null;\n};\n\nconst cleanupCompletedReasonCheckpoints = (ctx: HookInternalContext): void => {\n let changed = false;\n\n for (const [key, value] of Object.entries(ctx.currentNodeState.byKey)) {\n if (!key.startsWith(\"__useReason:\")) continue;\n if (!isRecord(value) || value.status !== \"completed\") continue;\n delete ctx.currentNodeState.byKey[key];\n changed = true;\n }\n\n if (changed) ctx.stateDirty = true;\n};\n\nconst toTokenUsageDelta = (\n usage: KortyxUsage | undefined,\n): TokenUsage | undefined => {\n if (!usage) return undefined;\n\n const input = usage.input ?? 0;\n const output = usage.output ?? 0;\n const total = usage.total ?? input + output + (usage.reasoning ?? 0);\n\n if (input === 0 && output === 0 && total === 0) {\n return undefined;\n }\n\n return {\n input,\n output,\n total,\n };\n};\n\nexport function accumulateTokenUsage(usage: KortyxUsage | undefined): void {\n const delta = toTokenUsageDelta(usage);\n if (!delta) return;\n\n const ctx = getHookContext();\n const current = ctx.tokenUsage ?? {\n input: 0,\n output: 0,\n total: 0,\n };\n\n ctx.tokenUsage = {\n input: current.input + delta.input,\n output: current.output + delta.output,\n total: current.total + delta.total,\n };\n ctx.runtimeDirty = true;\n}\n\nexport function getReasonTraceAdapter(): ReasonTraceAdapter | undefined {\n return getHookContext().reasonTrace;\n}\n\nexport async function runWithHookContext<T>(\n ctx: HookRuntimeContext,\n fn: () => Promise<T>,\n): Promise<{ result: T; runtimeUpdates: Record<string, unknown> | null }> {\n const internal = createInternalContext(ctx);\n try {\n const result = await storage.run(internal, fn);\n cleanupCompletedReasonCheckpoints(internal);\n return { result, runtimeUpdates: buildRuntimeStateUpdates(internal) };\n } catch (err) {\n const runtimeUpdates = buildRuntimeStateUpdates(internal);\n if (runtimeUpdates) {\n const currentRuntime = isRecord(internal.state.runtime)\n ? (internal.state.runtime as Record<string, unknown>)\n : {};\n internal.state.runtime = {\n ...currentRuntime,\n ...runtimeUpdates,\n } as unknown as GraphState[\"runtime\"];\n if (err && typeof err === \"object\") {\n (err as HookStatePatchedError).__kortyxHookStatePatch = runtimeUpdates;\n }\n }\n throw err;\n }\n}\n\nexport function getHookContext(): HookInternalContext {\n const ctx = storage.getStore();\n if (!ctx) {\n throw new Error(\"Hooks can only be used while a node is executing.\");\n }\n return ctx;\n}\n","import type { SchemaLike } from \"./types\";\n\nexport const parseWithSchema = <T>(\n schema: SchemaLike<T> | undefined,\n value: unknown,\n label: string,\n): T => {\n if (!schema) return value as T;\n\n const parsed = schema.safeParse(value);\n if (parsed.success) return parsed.data;\n\n const parsedError =\n \"error\" in parsed && parsed.error ? parsed.error : undefined;\n const reason =\n typeof parsedError?.message === \"string\" && parsedError.message.length > 0\n ? parsedError.message\n : \"invalid payload\";\n throw new Error(`${label} validation failed: ${reason}`);\n};\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport { getHookContext } from \"./context\";\nimport type { UseInterruptArgs } from \"./types\";\nimport { parseWithSchema } from \"./validation\";\n\nexport const awaitInterruptInternal = <\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseInterruptArgs<TRequest, TResponse>,\n): Promise<TResponse> => {\n const ctx = getHookContext();\n\n const request = parseWithSchema(\n args.requestSchema,\n args.request,\n \"useInterrupt request\",\n );\n\n const enrichedRequest = {\n ...request,\n ...(typeof args.schemaId === \"string\" && args.schemaId.length > 0\n ? { schemaId: args.schemaId }\n : {}),\n ...(typeof args.schemaVersion === \"string\" && args.schemaVersion.length > 0\n ? { schemaVersion: args.schemaVersion }\n : {}),\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n ...(args.meta && typeof args.meta === \"object\" && !Array.isArray(args.meta)\n ? { meta: args.meta }\n : {}),\n } as InterruptInput;\n\n const raw = ctx.node.awaitInterrupt(enrichedRequest);\n const response = parseWithSchema(\n args.responseSchema,\n raw,\n \"useInterrupt response\",\n );\n\n return Promise.resolve(response);\n};\n","import { randomUUID } from \"node:crypto\";\nimport { getHookContext } from \"./context\";\nimport { assertStructuredPath } from \"./structured-path\";\nimport type { UseReasonStructuredConfig, UseStructuredDataArgs } from \"./types\";\nimport { parseWithSchema } from \"./validation\";\n\nconst createStructuredStreamId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nexport const emitStructuredData = <TData = unknown>(\n args: UseStructuredDataArgs<TData>,\n): void => {\n const ctx = getHookContext();\n const streamId =\n typeof args.streamId === \"string\" && args.streamId.length > 0\n ? args.streamId\n : createStructuredStreamId();\n const dataType =\n typeof args.dataType === \"string\" && args.dataType.length > 0\n ? args.dataType\n : \"generic\";\n\n const base = {\n node: ctx.node.graph.node,\n streamId,\n dataType,\n ...(typeof args.schemaId === \"string\" && args.schemaId.length > 0\n ? { schemaId: args.schemaId }\n : {}),\n ...(typeof args.schemaVersion === \"string\" && args.schemaVersion.length > 0\n ? { schemaVersion: args.schemaVersion }\n : {}),\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n };\n\n if (args.kind === \"set\") {\n assertStructuredPath(args.path, \"useStructuredData\");\n const value = parseWithSchema(\n args.valueSchema,\n args.value,\n \"useStructuredData value\",\n );\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"set\",\n path: args.path,\n value,\n });\n return;\n }\n\n if (args.kind === \"append\") {\n assertStructuredPath(args.path, \"useStructuredData\");\n const items = args.items.map((item) =>\n parseWithSchema(args.itemSchema, item, \"useStructuredData append item\"),\n );\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"append\",\n path: args.path,\n items,\n });\n return;\n }\n\n if (args.kind === \"text-delta\") {\n assertStructuredPath(args.path, \"useStructuredData\");\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"text-delta\",\n path: args.path,\n delta: args.delta,\n });\n return;\n }\n\n const validated = parseWithSchema(\n args.dataSchema,\n args.data,\n \"useStructuredData data\",\n );\n\n ctx.node.emit(\"structured_data\", {\n ...base,\n kind: \"final\",\n data: validated,\n });\n};\n\nexport const shouldEmitStructured = (\n cfg: UseReasonStructuredConfig | undefined,\n): boolean => Boolean(cfg);\n\nexport const shouldStreamStructured = (\n cfg: UseReasonStructuredConfig | undefined,\n): boolean => Boolean(cfg) && (cfg?.stream ?? true);\n","export const parseStructuredPath = (path: string, source: string): string[] => {\n if (path.length === 0) {\n throw new Error(`${source} path must be a non-empty dot-separated string.`);\n }\n\n const parts = path.split(\".\");\n if (parts.some((part) => part.length === 0)) {\n throw new Error(\n `${source} path \"${path}\" must not contain empty segments.`,\n );\n }\n\n return parts;\n};\n\nexport const assertStructuredPath = (path: string, source: string): void => {\n parseStructuredPath(path, source);\n};\n","import type { InterruptInput } from \"@kortyx/core\";\nimport type {\n KortyxFinishReason,\n KortyxProviderMetadata,\n KortyxUsage,\n KortyxWarning,\n} from \"@kortyx/providers\";\nimport type { UseReasonResult } from \"../types\";\n\nexport type ReasonInterruptCheckpoint = {\n status: \"awaiting_interrupt\";\n request: InterruptInput;\n firstText: string;\n firstRaw?: unknown;\n firstUsage?: KortyxUsage;\n firstFinishReason?: KortyxFinishReason;\n firstProviderMetadata?: KortyxProviderMetadata;\n firstWarnings?: KortyxWarning[];\n firstOutput?: unknown;\n};\n\nexport type ReasonCompletedCheckpoint = {\n status: \"completed\";\n result: UseReasonResult<unknown, unknown>;\n};\n\nexport const resolveReasonCheckpointKey = (args: {\n id?: string;\n autoIndex: number;\n}): string =>\n typeof args.id === \"string\" && args.id.length > 0\n ? `__useReason:${args.id}`\n : `__useReason:auto:${args.autoIndex}`;\n\nexport const readReasonCheckpoint = (\n raw: unknown,\n): ReasonInterruptCheckpoint | undefined => {\n if (!raw || typeof raw !== \"object\") return undefined;\n const value = raw as Record<string, unknown>;\n if (value.status !== \"awaiting_interrupt\") return undefined;\n if (typeof value.firstText !== \"string\") return undefined;\n if (!value.request || typeof value.request !== \"object\") return undefined;\n return {\n status: \"awaiting_interrupt\",\n request: value.request as InterruptInput,\n firstText: value.firstText,\n ...(Object.hasOwn(value, \"firstRaw\") ? { firstRaw: value.firstRaw } : {}),\n ...(Object.hasOwn(value, \"firstUsage\")\n ? { firstUsage: value.firstUsage as KortyxUsage }\n : {}),\n ...(Object.hasOwn(value, \"firstFinishReason\")\n ? { firstFinishReason: value.firstFinishReason as KortyxFinishReason }\n : {}),\n ...(Object.hasOwn(value, \"firstProviderMetadata\")\n ? {\n firstProviderMetadata:\n value.firstProviderMetadata as KortyxProviderMetadata,\n }\n : {}),\n ...(Object.hasOwn(value, \"firstWarnings\")\n ? { firstWarnings: value.firstWarnings as KortyxWarning[] }\n : {}),\n ...(Object.hasOwn(value, \"firstOutput\")\n ? { firstOutput: value.firstOutput }\n : {}),\n };\n};\n\nexport const readReasonCompletedCheckpoint = (\n raw: unknown,\n): ReasonCompletedCheckpoint | undefined => {\n if (!raw || typeof raw !== \"object\") return undefined;\n const value = raw as Record<string, unknown>;\n if (value.status !== \"completed\") return undefined;\n if (!value.result || typeof value.result !== \"object\") return undefined;\n return {\n status: \"completed\",\n result: value.result as UseReasonResult<unknown, unknown>,\n };\n};\n\nexport const resolveHookStatePatch = (args: {\n nodeId: string;\n currentNodeState: unknown;\n workflowState: Record<string, unknown>;\n}): Record<string, unknown> => ({\n __kortyx: {\n nodeState: {\n nodeId: args.nodeId,\n state: args.currentNodeState,\n },\n workflowState: args.workflowState,\n },\n});\n","import { randomUUID } from \"node:crypto\";\nimport type {\n KortyxReasoningOptions,\n KortyxResponseFormat,\n ProviderModelRef,\n} from \"@kortyx/providers\";\nimport { getHookContext } from \"../context\";\nimport type { RunReasonEngineResult } from \"../reason-engine\";\nimport { runReasonEngine } from \"../reason-engine\";\n\nexport type ReasonEngineInput = {\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n maxOutputTokens?: number | undefined;\n stopSequences?: string[] | undefined;\n abortSignal?: AbortSignal | undefined;\n reasoning?: KortyxReasoningOptions | undefined;\n responseFormat?: KortyxResponseFormat | undefined;\n providerOptions?: Record<string, unknown> | undefined;\n emit?: boolean | undefined;\n stream?: boolean | undefined;\n onTextChunk?: ((text: string) => void) | undefined;\n};\n\nexport const createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nexport async function reasonEngine(\n args: ReasonEngineInput,\n meta: { id?: string; opId: string },\n inputOverride?: string,\n): Promise<RunReasonEngineResult> {\n const ctx = getHookContext();\n\n return runReasonEngine({\n model: args.model,\n input: inputOverride ?? args.input,\n system: args.system,\n temperature: args.temperature,\n maxOutputTokens: args.maxOutputTokens,\n stopSequences: args.stopSequences,\n abortSignal: args.abortSignal,\n reasoning: args.reasoning,\n responseFormat: args.responseFormat,\n providerOptions: args.providerOptions,\n defaultTemperature: ctx.node.config?.model?.temperature,\n stream: args.stream,\n emit: args.emit,\n onTextChunk: args.onTextChunk,\n nodeId: ctx.node.graph.node,\n emitEvent: ctx.node.emit,\n reasonTrace: ctx.reasonTrace,\n id: meta.id,\n opId: meta.opId,\n });\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n KortyxFinishReason,\n KortyxPromptMessage,\n KortyxProviderMetadata,\n KortyxReasoningOptions,\n KortyxResponseFormat,\n KortyxUsage,\n KortyxWarning,\n ProviderModelRef,\n} from \"@kortyx/providers\";\nimport type { ReasonTraceAdapter, ReasonTraceSpan } from \"./tracing\";\n\nexport interface RunReasonEngineArgs {\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n maxOutputTokens?: number | undefined;\n stopSequences?: string[] | undefined;\n abortSignal?: AbortSignal | undefined;\n reasoning?: KortyxReasoningOptions | undefined;\n responseFormat?: KortyxResponseFormat | undefined;\n providerOptions?: Record<string, unknown> | undefined;\n defaultTemperature?: number | undefined;\n stream?: boolean | undefined;\n emit?: boolean | undefined;\n nodeId?: string | undefined;\n emitEvent?: ((event: string, payload: unknown) => void) | undefined;\n onTextChunk?: ((text: string) => void) | undefined;\n id?: string | undefined;\n opId?: string | undefined;\n segmentId?: string | undefined;\n reasonTrace?: ReasonTraceAdapter | undefined;\n}\n\nexport interface RunReasonEngineResult {\n text: string;\n raw?: unknown;\n usage?: KortyxUsage;\n finishReason?: KortyxFinishReason;\n providerMetadata?: KortyxProviderMetadata;\n warnings?: KortyxWarning[];\n}\n\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\nconst createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nconst emitNodeEvent = (\n emitEvent: RunReasonEngineArgs[\"emitEvent\"],\n nodeId: string | undefined,\n event: string,\n payload: Record<string, unknown>,\n): void => {\n if (!emitEvent) return;\n emitEvent(event, {\n ...payload,\n ...(typeof nodeId === \"string\" && nodeId.length > 0\n ? { node: nodeId }\n : {}),\n });\n};\n\nexport async function runReasonEngine(\n args: RunReasonEngineArgs,\n): Promise<RunReasonEngineResult> {\n const stream = args.stream ?? args.model.options?.streaming ?? true;\n const emit = args.emit ?? true;\n const temperature =\n args.temperature ??\n args.model.options?.temperature ??\n args.defaultTemperature;\n const maxOutputTokens =\n args.maxOutputTokens ?? args.model.options?.maxOutputTokens;\n const stopSequences = args.stopSequences ?? args.model.options?.stopSequences;\n const abortSignal = args.abortSignal ?? args.model.options?.abortSignal;\n const reasoning = args.reasoning ?? args.model.options?.reasoning;\n const responseFormat =\n args.responseFormat ?? args.model.options?.responseFormat;\n const providerOptions =\n args.providerOptions ?? args.model.options?.providerOptions;\n\n const model = args.model.provider.getModel(args.model.modelId, {\n ...(temperature !== undefined ? { temperature } : {}),\n streaming: stream,\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(stopSequences !== undefined ? { stopSequences } : {}),\n ...(abortSignal !== undefined ? { abortSignal } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(responseFormat !== undefined ? { responseFormat } : {}),\n ...(providerOptions !== undefined ? { providerOptions } : {}),\n });\n\n const messages: KortyxPromptMessage[] = [];\n if (typeof args.system === \"string\" && args.system.length > 0) {\n messages.push({ role: \"system\", content: args.system });\n }\n messages.push({ role: \"user\", content: String(args.input ?? \"\") });\n\n const opId =\n typeof args.opId === \"string\" && args.opId.length > 0\n ? args.opId\n : createRuntimeId();\n const segmentId =\n typeof args.segmentId === \"string\" && args.segmentId.length > 0\n ? args.segmentId\n : createRuntimeId();\n\n const commonMeta: Record<string, unknown> = {\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n opId,\n segmentId,\n };\n const traceSpan = args.reasonTrace?.startSpan({\n name: \"runReasonEngine\",\n attributes: {\n ...commonMeta,\n providerId: args.model.provider.id,\n modelId: args.model.modelId,\n stream,\n emit,\n ...(typeof args.nodeId === \"string\" && args.nodeId.length > 0\n ? { nodeId: args.nodeId }\n : {}),\n },\n });\n\n const endTrace = (\n span: ReasonTraceSpan | undefined,\n result: RunReasonEngineResult,\n ): void => {\n span?.end?.({\n ...(result.usage !== undefined ? { usage: result.usage } : {}),\n ...(result.finishReason !== undefined\n ? { finishReason: result.finishReason }\n : {}),\n ...(result.providerMetadata !== undefined\n ? { providerMetadata: result.providerMetadata }\n : {}),\n ...(result.warnings !== undefined ? { warnings: result.warnings } : {}),\n attributes: {\n textLength: result.text.length,\n },\n });\n };\n\n const failTrace = (\n span: ReasonTraceSpan | undefined,\n error: unknown,\n ): void => {\n span?.fail?.(error, {\n attributes: {\n providerId: args.model.provider.id,\n modelId: args.model.modelId,\n },\n });\n };\n\n try {\n if (stream) {\n let final = \"\";\n let raw: unknown;\n let usage: KortyxUsage | undefined;\n let finishReason: KortyxFinishReason | undefined;\n let providerMetadata: KortyxProviderMetadata | undefined;\n let warnings: KortyxWarning[] | undefined;\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n }\n\n const response = await model.stream(messages);\n for await (const chunk of response) {\n switch (chunk.type) {\n case \"text-delta\": {\n if (chunk.delta.length === 0) break;\n final += chunk.delta;\n args.onTextChunk?.(chunk.delta);\n if (chunk.raw !== undefined) {\n raw = chunk.raw;\n }\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: chunk.delta,\n });\n }\n break;\n }\n case \"finish\": {\n if (chunk.raw !== undefined) {\n raw = chunk.raw;\n }\n if (chunk.usage !== undefined) {\n usage = chunk.usage;\n }\n if (chunk.finishReason !== undefined) {\n finishReason = chunk.finishReason;\n }\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n if (chunk.warnings !== undefined) {\n warnings = chunk.warnings;\n }\n break;\n }\n case \"raw\": {\n raw = chunk.raw;\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n break;\n }\n case \"error\": {\n if (chunk.raw !== undefined) {\n raw = chunk.raw;\n }\n if (chunk.providerMetadata !== undefined) {\n providerMetadata = chunk.providerMetadata;\n }\n if (chunk.warnings !== undefined) {\n warnings = chunk.warnings;\n }\n throw toError(chunk.error);\n }\n }\n }\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n const result = {\n text: final,\n ...(raw !== undefined ? { raw } : {}),\n ...(usage !== undefined ? { usage } : {}),\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(providerMetadata !== undefined ? { providerMetadata } : {}),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n endTrace(traceSpan, result);\n return result;\n }\n\n const response = await model.invoke(messages);\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n if (response.content) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: response.content,\n });\n }\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n const result = {\n text: response.content,\n ...(response.raw !== undefined ? { raw: response.raw } : {}),\n ...(response.usage !== undefined ? { usage: response.usage } : {}),\n ...(response.finishReason !== undefined\n ? { finishReason: response.finishReason }\n : {}),\n ...(response.providerMetadata !== undefined\n ? { providerMetadata: response.providerMetadata }\n : {}),\n ...(response.warnings !== undefined\n ? { warnings: response.warnings }\n : {}),\n };\n endTrace(traceSpan, result);\n return result;\n } catch (error) {\n failTrace(traceSpan, error);\n throw error;\n }\n}\n","import type { InterruptInput } from \"@kortyx/core\";\nimport type { KortyxFinishReason } from \"@kortyx/providers\";\nimport type { SchemaLike } from \"../types\";\nimport { parseWithSchema } from \"../validation\";\n\nconst tryJsonParse = (\n value: string,\n):\n | { ok: true; value: unknown; error?: never }\n | { ok: false; error: string } => {\n try {\n return { ok: true, value: JSON.parse(value) };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n};\n\nconst extractJsonCodeBlock = (value: string): string | null => {\n const match = value.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n if (!match || typeof match[1] !== \"string\") return null;\n const inner = match[1].trim();\n return inner.length > 0 ? inner : null;\n};\n\nconst tryStringify = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nexport const resolveOutputCandidate = (text: string): unknown => {\n const trimmed = text.trim();\n if (!trimmed) return text;\n\n const direct = tryJsonParse(trimmed);\n if (direct.ok) return direct.value;\n\n const block = extractJsonCodeBlock(trimmed);\n if (block) {\n const parsedBlock = tryJsonParse(block);\n if (parsedBlock.ok) return parsedBlock.value;\n }\n\n return text;\n};\n\nconst looksLikeStructuredJsonAttempt = (value: string): boolean => {\n const trimmed = value.trim();\n if (!trimmed) return false;\n\n return (\n trimmed.startsWith(\"{\") ||\n trimmed.startsWith(\"[\") ||\n /^```(?:json)?/i.test(trimmed)\n );\n};\n\nconst isLikelyTruncatedStructuredOutput = (text: string): boolean => {\n const trimmed = text.trim();\n if (!looksLikeStructuredJsonAttempt(trimmed)) return false;\n\n const direct = tryJsonParse(trimmed);\n if (!direct.ok && direct.error) return true;\n\n const block = extractJsonCodeBlock(trimmed);\n if (!block) return false;\n\n const parsedBlock = tryJsonParse(block);\n return !parsedBlock.ok && Boolean(parsedBlock.error);\n};\n\nconst createTruncatedStructuredOutputError = (label: string): Error =>\n new Error(\n `${label} was truncated before producing valid structured output. The model stopped due to output length. Increase maxOutputTokens or simplify the requested output.`,\n );\n\nconst createInvalidStructuredOutputError = (label: string): Error =>\n new Error(\n `${label} did not produce valid structured output. The model returned text instead of the expected JSON payload. This often happens when output is truncated or the provider does not follow JSON mode. Increase maxOutputTokens or simplify the requested output.`,\n );\n\nexport const parseReasonOutputWithSchema = <TOutput>(args: {\n text: string;\n schema: SchemaLike<TOutput>;\n finishReason?: KortyxFinishReason;\n label: string;\n}): TOutput => {\n const candidate = resolveOutputCandidate(args.text);\n\n try {\n return parseWithSchema(args.schema, candidate, args.label);\n } catch (error) {\n if (\n args.finishReason?.unified === \"length\" ||\n isLikelyTruncatedStructuredOutput(args.text)\n ) {\n throw createTruncatedStructuredOutputError(args.label);\n }\n if (typeof candidate === \"string\" && candidate.trim().length > 0) {\n throw createInvalidStructuredOutputError(args.label);\n }\n throw error;\n }\n};\n\nexport const parseInterruptFirstPassResult = <\n TRequest extends InterruptInput = InterruptInput,\n TOutput = unknown,\n>(args: {\n text: string;\n requestSchema: SchemaLike<TRequest>;\n outputSchema?: SchemaLike<TOutput>;\n finishReason?: KortyxFinishReason;\n mode?: \"required\" | \"optional\" | undefined;\n}):\n | {\n draftText: string;\n interruptRequired: boolean;\n request: TRequest;\n output?: TOutput;\n }\n | {\n draftText: string;\n interruptRequired: false;\n request?: undefined;\n output?: TOutput;\n } => {\n const candidate = resolveOutputCandidate(args.text);\n if (!isRecord(candidate)) {\n if (\n args.finishReason?.unified === \"length\" ||\n isLikelyTruncatedStructuredOutput(args.text)\n ) {\n throw createTruncatedStructuredOutputError(\"useReason output\");\n }\n if (typeof candidate === \"string\" && candidate.trim().length > 0) {\n throw createInvalidStructuredOutputError(\"useReason output\");\n }\n throw new Error(\n \"useReason first pass with interrupt must return a JSON object.\",\n );\n }\n\n const mode = args.mode ?? \"required\";\n let interruptRequired = true;\n if (mode === \"optional\") {\n if (\n candidate.decision !== \"continue\" &&\n candidate.decision !== \"interrupt\"\n ) {\n throw new Error(\n 'useReason optional interrupt first pass must include decision \"continue\" or \"interrupt\".',\n );\n }\n interruptRequired = candidate.decision === \"interrupt\";\n\n if (!interruptRequired) {\n const hasUnexpectedRequest = [\n candidate.interruptRequest,\n candidate.request,\n candidate.interrupt,\n ].some((value) => value !== null && value !== undefined);\n\n if (hasUnexpectedRequest) {\n throw new Error(\n 'useReason optional interrupt first pass with decision \"continue\" must not include an interrupt request.',\n );\n }\n }\n }\n\n let request: TRequest | undefined;\n if (interruptRequired) {\n const requestCandidates: unknown[] = [\n candidate.interruptRequest,\n candidate.request,\n candidate.interrupt,\n mode === \"required\" ? candidate : undefined,\n ];\n const requestPayload = requestCandidates.find(\n (value) => value !== null && value !== undefined,\n );\n\n request = parseWithSchema(\n args.requestSchema,\n requestPayload,\n \"useReason interrupt.request\",\n );\n }\n\n let output: TOutput | undefined;\n if (args.outputSchema) {\n const outputPayload = Object.hasOwn(candidate, \"output\")\n ? candidate.output\n : candidate;\n try {\n output = parseWithSchema(\n args.outputSchema,\n outputPayload,\n \"useReason output\",\n );\n } catch (error) {\n if (\n args.finishReason?.unified === \"length\" ||\n isLikelyTruncatedStructuredOutput(args.text)\n ) {\n throw createTruncatedStructuredOutputError(\"useReason output\");\n }\n if (\n typeof outputPayload === \"string\" &&\n outputPayload.trim().length > 0\n ) {\n throw createInvalidStructuredOutputError(\"useReason output\");\n }\n throw error;\n }\n }\n\n const explicitDraft =\n typeof candidate.draftText === \"string\" && candidate.draftText.length > 0\n ? candidate.draftText\n : typeof candidate.text === \"string\" && candidate.text.length > 0\n ? candidate.text\n : undefined;\n\n if (!args.outputSchema && !explicitDraft) {\n throw new Error(\n \"useReason first pass with interrupt requires `draftText` when outputSchema is not provided.\",\n );\n }\n\n const draftText =\n explicitDraft ??\n (output !== undefined ? tryStringify(output) : String(args.text ?? \"\"));\n\n if (!interruptRequired) {\n return {\n draftText,\n interruptRequired: false,\n ...(output !== undefined ? { output } : {}),\n };\n }\n\n return {\n draftText,\n interruptRequired: true,\n request: request as TRequest,\n ...(output !== undefined ? { output } : {}),\n };\n};\n","import type { InterruptInput } from \"@kortyx/core\";\nimport { toJSONSchema } from \"zod\";\nimport type { SchemaLike } from \"../types\";\n\nconst tryStringify = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n};\n\nconst tryGetSchemaHint = (schema: unknown): string | undefined => {\n try {\n const hint = toJSONSchema(schema as never);\n return JSON.stringify(hint, null, 2);\n } catch {\n return undefined;\n }\n};\n\nconst withSchemaHint = (\n input: string,\n label: string,\n schema: unknown,\n): string => {\n const hint = tryGetSchemaHint(schema);\n if (!hint) return input;\n return `${input}\\n\\n${label}:\\n${hint}`;\n};\n\nexport const defaultInterruptFirstPassInput = (args: {\n input: string;\n requestSchema: SchemaLike<unknown>;\n outputSchema?: SchemaLike<unknown>;\n mode?: \"required\" | \"optional\" | undefined;\n}): string => {\n const mode = args.mode ?? \"required\";\n const base =\n mode === \"optional\"\n ? args.outputSchema\n ? [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: decision, output, interruptRequest, draftText.\",\n '- decision must be either \"continue\" or \"interrupt\".',\n '- Use decision \"continue\" when you can produce the final output without asking the user.',\n '- Use decision \"interrupt\" only when user input is needed before finalizing.',\n \"- output must match the expected output JSON schema.\",\n '- When decision is \"interrupt\", interruptRequest must match the expected interrupt request JSON schema and must be a non-null object.',\n '- When decision is \"continue\", interruptRequest must be null.',\n \"- draftText should be a concise plain-language summary of output.\",\n ].join(\"\\n\\n\")\n : [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: decision, draftText, interruptRequest.\",\n '- decision must be either \"continue\" or \"interrupt\".',\n '- Use decision \"continue\" when you can produce the final answer without asking the user.',\n '- Use decision \"interrupt\" only when user input is needed before finalizing.',\n \"- draftText should be the current answer text.\",\n '- When decision is \"interrupt\", interruptRequest must match the expected interrupt request JSON schema and must be a non-null object.',\n '- When decision is \"continue\", interruptRequest must be null.',\n ].join(\"\\n\\n\")\n : args.outputSchema\n ? [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: output, interruptRequest, draftText.\",\n \"- output must match the expected output JSON schema.\",\n \"- interruptRequest must match the expected interrupt request JSON schema.\",\n \"- interruptRequest must be a non-null object.\",\n \"- draftText should be a concise plain-language summary of output.\",\n \"- If uncertain, still return a valid interruptRequest with safe default options.\",\n ].join(\"\\n\\n\")\n : [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: draftText, interruptRequest.\",\n \"- draftText should be the current draft answer text.\",\n \"- interruptRequest must match the expected interrupt request JSON schema.\",\n \"- interruptRequest must be a non-null object.\",\n \"- If uncertain, still return a valid interruptRequest with safe default options.\",\n ].join(\"\\n\\n\");\n\n const withInterruptSchema = withSchemaHint(\n base,\n \"Expected interrupt request JSON schema (for `interruptRequest`)\",\n args.requestSchema,\n );\n\n if (!args.outputSchema) return withInterruptSchema;\n const withOutputSchema = withSchemaHint(\n withInterruptSchema,\n \"Expected output JSON schema (for `output`)\",\n args.outputSchema,\n );\n return [\n withOutputSchema,\n \"JSON template:\",\n mode === \"optional\"\n ? '{ \"decision\": \"continue\", \"output\": { ... }, \"interruptRequest\": null, \"draftText\": \"...\" }'\n : '{ \"output\": { ... }, \"interruptRequest\": { ... }, \"draftText\": \"...\" }',\n ].join(\"\\n\\n\");\n};\n\nexport const defaultContinuationInput = (args: {\n input: string;\n draftText: string;\n draftOutput?: unknown;\n request: InterruptInput;\n response: unknown;\n}): string =>\n [\n \"You are continuing a paused reasoning task after user input.\",\n \"Update the previous result using the user response and return the final answer only.\",\n \"If the previous output was JSON, return JSON in the same schema.\",\n \"\",\n `Original request:\\n${args.input}`,\n `Draft answer text:\\n${args.draftText}`,\n `Draft output object:\\n${tryStringify(args.draftOutput ?? args.draftText)}`,\n `Interrupt request shown to user:\\n${tryStringify(args.request)}`,\n `User response:\\n${tryStringify(args.response)}`,\n ].join(\"\\n\\n\");\n\nexport const withOutputGuardrails = (\n input: string,\n schema?: SchemaLike<unknown>,\n): string => {\n const base = [\n input,\n \"Output rules:\",\n \"- Return only JSON, no markdown fences.\",\n \"- Ensure the response conforms to the expected output schema.\",\n \"- Do not include explanatory text outside the JSON object.\",\n ].join(\"\\n\\n\");\n return withSchemaHint(base, \"Expected output JSON schema\", schema);\n};\n\nexport const withStructuredStreamHints = (\n input: string,\n args: {\n setFieldPaths?: string[];\n appendFieldPaths?: string[];\n textDeltaFieldPaths?: string[];\n },\n): string => {\n const rules: string[] = [];\n\n for (const path of args.setFieldPaths ?? []) {\n rules.push(\n `- For the field path \\`${path}\\`, write one stable final value and do not rewrite it after it is complete.`,\n );\n }\n\n for (const path of args.appendFieldPaths ?? []) {\n rules.push(\n `- For the array field path \\`${path}\\`, write items in final order and finish each item before starting the next.`,\n );\n rules.push(\n `- Once an item in \\`${path}\\` is complete, do not rewrite or reorder earlier items.`,\n );\n }\n\n for (const path of args.textDeltaFieldPaths ?? []) {\n rules.push(\n `- For the string field path \\`${path}\\`, write the value progressively by appending text to the end.`,\n );\n rules.push(\n `- Do not rewrite or replace the earlier prefix of \\`${path}\\` once emitted.`,\n );\n }\n\n if (rules.length === 0) return input;\n\n return [\n input,\n \"Streaming rules:\",\n ...rules,\n \"- Keep the overall response as valid JSON.\",\n ].join(\"\\n\\n\");\n};\n","import { assertStructuredPath, parseStructuredPath } from \"../structured-path\";\nimport type { UseReasonStructuredConfig } from \"../types\";\n\nexport const resolveAppendFieldPaths = (\n cfg: UseReasonStructuredConfig | undefined,\n): string[] => {\n const fields = cfg?.fields;\n if (!fields) return [];\n\n const appendPaths = Object.entries(fields)\n .filter(([, mode]) => mode === \"append\")\n .map(([path]) => path);\n\n for (const path of appendPaths) {\n assertStructuredPath(path, \"useReason structured append\");\n }\n\n return appendPaths;\n};\n\nexport const resolveSetFieldPaths = (\n cfg: UseReasonStructuredConfig | undefined,\n): string[] => {\n const fields = cfg?.fields;\n if (!fields) return [];\n\n const setPaths = Object.entries(fields)\n .filter(([, mode]) => mode === \"set\")\n .map(([path]) => path);\n\n for (const path of setPaths) {\n assertStructuredPath(path, \"useReason structured set\");\n }\n\n return setPaths;\n};\n\nexport const resolveTextDeltaFieldPaths = (\n cfg: UseReasonStructuredConfig | undefined,\n): string[] => {\n const fields = cfg?.fields;\n if (!fields) return [];\n\n const textPaths = Object.entries(fields)\n .filter(([, mode]) => mode === \"text-delta\")\n .map(([path]) => path);\n\n for (const path of textPaths) {\n assertStructuredPath(path, \"useReason structured text-delta\");\n }\n\n return textPaths;\n};\n\nconst extractCompletedStringValueAt = (args: {\n text: string;\n start: number;\n}): { complete: boolean; value?: string } => {\n let value = \"\";\n\n for (let i = args.start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (ch === '\"') {\n return {\n complete: true,\n value,\n };\n }\n\n if (ch !== \"\\\\\") {\n value += ch;\n continue;\n }\n\n const next = args.text[i + 1];\n if (!next) {\n return {\n complete: false,\n };\n }\n\n if (\n next === '\"' ||\n next === \"\\\\\" ||\n next === \"/\" ||\n next === \"b\" ||\n next === \"f\" ||\n next === \"n\" ||\n next === \"r\" ||\n next === \"t\"\n ) {\n value +=\n next === \"b\"\n ? \"\\b\"\n : next === \"f\"\n ? \"\\f\"\n : next === \"n\"\n ? \"\\n\"\n : next === \"r\"\n ? \"\\r\"\n : next === \"t\"\n ? \"\\t\"\n : next;\n i += 1;\n continue;\n }\n\n if (next === \"u\") {\n const hex = args.text.slice(i + 2, i + 6);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) {\n return {\n complete: false,\n };\n }\n value += String.fromCharCode(Number.parseInt(hex, 16));\n i += 5;\n continue;\n }\n\n return {\n complete: false,\n };\n }\n\n return {\n complete: false,\n };\n};\n\nconst skipWhitespace = (text: string, start: number): number => {\n let i = start;\n while (i < text.length && /\\s/.test(text[i] ?? \"\")) i += 1;\n return i;\n};\n\nconst pathEquals = (left: string[], right: string[]): boolean =>\n left.length === right.length &&\n left.every((part, index) => part === right[index]);\n\nconst isPathPrefix = (prefix: string[], full: string[]): boolean =>\n prefix.length <= full.length &&\n prefix.every((part, index) => part === full[index]);\n\nconst parseStringToken = (\n text: string,\n start: number,\n): { complete: boolean; end?: number; value?: string } => {\n if (text[start] !== '\"') return { complete: false };\n\n const parsed = extractCompletedStringValueAt({ text, start: start + 1 });\n if (!parsed.complete || parsed.value === undefined)\n return { complete: false };\n\n let inEscape = false;\n for (let i = start + 1; i < text.length; i += 1) {\n const ch = text[i];\n if (ch === undefined) break;\n\n if (inEscape) {\n inEscape = false;\n if (ch === \"u\") i += 4;\n continue;\n }\n\n if (ch === \"\\\\\") {\n inEscape = true;\n continue;\n }\n\n if (ch === '\"') {\n return {\n complete: true,\n end: i + 1,\n value: parsed.value,\n };\n }\n }\n\n return { complete: false };\n};\n\nconst skipNestedValue = (\n text: string,\n start: number,\n): { complete: boolean; end?: number } => {\n const opener = text[start];\n const closer = opener === \"{\" ? \"}\" : \"]\";\n let inString = false;\n let isEscaped = false;\n let nesting = 0;\n\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (ch === undefined) break;\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\") {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n\n if (ch === '\"') {\n inString = true;\n continue;\n }\n\n if (ch === opener) {\n nesting += 1;\n continue;\n }\n\n if (ch === closer) {\n nesting -= 1;\n if (nesting === 0) {\n return { complete: true, end: i + 1 };\n }\n }\n }\n\n return { complete: false };\n};\n\nconst skipCompleteValue = (\n text: string,\n start: number,\n): { complete: boolean; end?: number } => {\n const i = skipWhitespace(text, start);\n const first = text[i];\n if (!first) return { complete: false };\n\n if (first === '\"') {\n const parsed = parseStringToken(text, i);\n return parsed.complete && parsed.end !== undefined\n ? { complete: true, end: parsed.end }\n : { complete: false };\n }\n\n if (first === \"{\" || first === \"[\") {\n return skipNestedValue(text, i);\n }\n\n for (let j = i; j < text.length; j += 1) {\n const ch = text[j];\n if (ch !== \",\" && ch !== \"}\" && ch !== \"]\") continue;\n\n const raw = text.slice(i, j).trim();\n if (!raw) return { complete: false };\n\n try {\n JSON.parse(raw);\n return { complete: true, end: j };\n } catch {\n return { complete: false };\n }\n }\n\n return { complete: false };\n};\n\nconst locateValueStart = (args: {\n text: string;\n path: string;\n}): { found: boolean; start?: number } => {\n const targetParts = parseStructuredPath(\n args.path,\n \"useReason structured field\",\n );\n\n const visitValue = (\n start: number,\n currentParts: string[],\n ): { found: boolean; start?: number } => {\n const valueStart = skipWhitespace(args.text, start);\n if (pathEquals(currentParts, targetParts)) {\n return { found: true, start: valueStart };\n }\n\n if (!isPathPrefix(currentParts, targetParts)) {\n return { found: false };\n }\n\n const first = args.text[valueStart];\n if (first === \"{\") return visitObject(valueStart + 1, currentParts);\n if (first === \"[\") return visitArray(valueStart + 1, currentParts);\n return { found: false };\n };\n\n const visitObject = (\n start: number,\n currentParts: string[],\n ): { found: boolean; start?: number } => {\n let i = skipWhitespace(args.text, start);\n\n while (i < args.text.length) {\n const ch = args.text[i];\n if (ch === \"}\") return { found: false };\n if (ch === \",\") {\n i = skipWhitespace(args.text, i + 1);\n continue;\n }\n if (ch !== '\"') return { found: false };\n\n const key = parseStringToken(args.text, i);\n if (!key.complete || key.end === undefined || key.value === undefined) {\n return { found: false };\n }\n\n i = skipWhitespace(args.text, key.end);\n if (args.text[i] !== \":\") return { found: false };\n\n const valueStart = skipWhitespace(args.text, i + 1);\n const childParts = [...currentParts, key.value];\n if (pathEquals(childParts, targetParts)) {\n return { found: true, start: valueStart };\n }\n\n if (isPathPrefix(childParts, targetParts)) {\n const nested = visitValue(valueStart, childParts);\n if (nested.found) return nested;\n }\n\n const skipped = skipCompleteValue(args.text, valueStart);\n if (!skipped.complete || skipped.end === undefined) {\n return { found: false };\n }\n\n i = skipWhitespace(args.text, skipped.end);\n if (args.text[i] === \",\") {\n i = skipWhitespace(args.text, i + 1);\n continue;\n }\n if (args.text[i] === \"}\") return { found: false };\n return { found: false };\n }\n\n return { found: false };\n };\n\n const visitArray = (\n start: number,\n currentParts: string[],\n ): { found: boolean; start?: number } => {\n let i = skipWhitespace(args.text, start);\n let index = 0;\n\n while (i < args.text.length) {\n if (args.text[i] === \"]\") return { found: false };\n\n const childParts = [...currentParts, String(index)];\n if (pathEquals(childParts, targetParts)) {\n return { found: true, start: i };\n }\n\n if (isPathPrefix(childParts, targetParts)) {\n const nested = visitValue(i, childParts);\n if (nested.found) return nested;\n }\n\n const skipped = skipCompleteValue(args.text, i);\n if (!skipped.complete || skipped.end === undefined) {\n return { found: false };\n }\n\n i = skipWhitespace(args.text, skipped.end);\n if (args.text[i] === \",\") {\n index += 1;\n i = skipWhitespace(args.text, i + 1);\n continue;\n }\n if (args.text[i] === \"]\") return { found: false };\n return { found: false };\n }\n\n return { found: false };\n };\n\n return visitValue(0, []);\n};\n\nconst extractCompletedValueAt = (args: {\n text: string;\n start: number;\n}): { complete: boolean; value?: unknown } => {\n const start = skipWhitespace(args.text, args.start);\n const first = args.text[start];\n if (!first) return { complete: false };\n\n if (first === '\"') {\n const parsed = extractCompletedStringValueAt({\n text: args.text,\n start: start + 1,\n });\n return parsed.complete\n ? {\n complete: true,\n value: parsed.value,\n }\n : {\n complete: false,\n };\n }\n\n if (first === \"{\") {\n return extractCompletedNestedValueAt({\n text: args.text,\n start,\n opener: \"{\",\n closer: \"}\",\n });\n }\n\n if (first === \"[\") {\n return extractCompletedNestedValueAt({\n text: args.text,\n start,\n opener: \"[\",\n closer: \"]\",\n });\n }\n\n for (let i = start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n if (ch !== \",\" && ch !== \"}\" && ch !== \"]\") continue;\n\n const raw = args.text.slice(start, i).trim();\n if (!raw) return { complete: false };\n\n try {\n return {\n complete: true,\n value: JSON.parse(raw),\n };\n } catch {\n return { complete: false };\n }\n }\n\n return { complete: false };\n};\n\nconst extractCompletedNestedValueAt = (args: {\n text: string;\n start: number;\n opener: \"{\" | \"[\";\n closer: \"}\" | \"]\";\n}): { complete: boolean; value?: unknown } => {\n let inString = false;\n let isEscaped = false;\n let nesting = 0;\n\n for (let i = args.start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\") {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n\n if (ch === '\"') {\n inString = true;\n continue;\n }\n\n if (ch === args.opener) {\n nesting += 1;\n continue;\n }\n\n if (ch === args.closer) {\n nesting -= 1;\n if (nesting === 0) {\n const raw = args.text.slice(args.start, i + 1);\n try {\n return {\n complete: true,\n value: JSON.parse(raw),\n };\n } catch {\n return {\n complete: false,\n };\n }\n }\n }\n }\n\n return {\n complete: false,\n };\n};\n\nexport const extractCompletedFieldValue = (args: {\n text: string;\n path: string;\n}): { found: boolean; complete: boolean; value?: unknown } => {\n const located = locateValueStart(args);\n if (!located.found || located.start === undefined) {\n return {\n found: located.found,\n complete: false,\n };\n }\n\n const parsed = extractCompletedValueAt({\n text: args.text,\n start: located.start,\n });\n return parsed.complete\n ? {\n found: true,\n complete: true,\n value: parsed.value,\n }\n : {\n found: true,\n complete: false,\n };\n};\n\nexport const extractCompletedArrayItems = (args: {\n text: string;\n path: string;\n}): unknown[] => {\n const located = locateValueStart(args);\n if (!located.found || located.start === undefined) return [];\n\n const arrayStart = skipWhitespace(args.text, located.start);\n if (args.text[arrayStart] !== \"[\") return [];\n const start = arrayStart + 1;\n\n const items: unknown[] = [];\n let inString = false;\n let isEscaped = false;\n let nesting = 0;\n let itemStart = -1;\n\n for (let i = start; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\") {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n\n if (ch === '\"') {\n inString = true;\n if (itemStart < 0) itemStart = i;\n continue;\n }\n\n if (itemStart < 0) {\n if (/\\s/.test(ch) || ch === \",\") continue;\n if (ch === \"]\") break;\n itemStart = i;\n if (ch === \"{\" || ch === \"[\") {\n nesting = 1;\n } else {\n nesting = 0;\n }\n continue;\n }\n\n if (ch === \"{\" || ch === \"[\") {\n nesting += 1;\n continue;\n }\n\n if (ch === \"}\" || ch === \"]\") {\n if (nesting > 0) {\n nesting -= 1;\n continue;\n }\n }\n\n if (nesting === 0 && (ch === \",\" || ch === \"]\")) {\n const raw = args.text.slice(itemStart, i).trim();\n if (raw) {\n try {\n items.push(JSON.parse(raw));\n } catch {}\n }\n itemStart = -1;\n if (ch === \"]\") break;\n }\n }\n\n return items;\n};\n\nexport const extractStreamingStringValue = (args: {\n text: string;\n path: string;\n}): { found: boolean; complete: boolean; value: string } => {\n const located = locateValueStart(args);\n if (!located.found || located.start === undefined) {\n return {\n found: located.found,\n complete: false,\n value: \"\",\n };\n }\n\n const stringStart = skipWhitespace(args.text, located.start);\n if (args.text[stringStart] !== '\"') {\n return {\n found: true,\n complete: false,\n value: \"\",\n };\n }\n\n let value = \"\";\n\n for (let i = stringStart + 1; i < args.text.length; i += 1) {\n const ch = args.text[i];\n if (ch === undefined) break;\n\n if (ch === '\"') {\n return {\n found: true,\n complete: true,\n value,\n };\n }\n\n if (ch !== \"\\\\\") {\n value += ch;\n continue;\n }\n\n const next = args.text[i + 1];\n if (!next) {\n return {\n found: true,\n complete: false,\n value,\n };\n }\n\n if (\n next === '\"' ||\n next === \"\\\\\" ||\n next === \"/\" ||\n next === \"b\" ||\n next === \"f\" ||\n next === \"n\" ||\n next === \"r\" ||\n next === \"t\"\n ) {\n value +=\n next === \"b\"\n ? \"\\b\"\n : next === \"f\"\n ? \"\\f\"\n : next === \"n\"\n ? \"\\n\"\n : next === \"r\"\n ? \"\\r\"\n : next === \"t\"\n ? \"\\t\"\n : next;\n i += 1;\n continue;\n }\n\n if (next === \"u\") {\n const hex = args.text.slice(i + 2, i + 6);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) {\n return {\n found: true,\n complete: false,\n value,\n };\n }\n value += String.fromCharCode(Number.parseInt(hex, 16));\n i += 5;\n continue;\n }\n\n return {\n found: true,\n complete: false,\n value,\n };\n }\n\n return {\n found: true,\n complete: false,\n value,\n };\n};\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport type {\n KortyxFinishReason,\n KortyxProviderMetadata,\n KortyxUsage,\n KortyxWarning,\n} from \"@kortyx/providers\";\nimport {\n accumulateTokenUsage,\n getHookContext,\n getReasonTraceAdapter,\n} from \"../context\";\nimport { awaitInterruptInternal } from \"../interrupt\";\nimport {\n emitStructuredData,\n shouldEmitStructured,\n shouldStreamStructured,\n} from \"../structured\";\nimport type { ReasonTraceSpan } from \"../tracing\";\nimport type { SchemaLike, UseReasonArgs, UseReasonResult } from \"../types\";\nimport { parseWithSchema } from \"../validation\";\nimport {\n type ReasonInterruptCheckpoint,\n readReasonCheckpoint,\n readReasonCompletedCheckpoint,\n resolveHookStatePatch,\n resolveReasonCheckpointKey,\n} from \"./checkpoint\";\nimport { createRuntimeId, reasonEngine } from \"./engine\";\nimport {\n parseInterruptFirstPassResult,\n parseReasonOutputWithSchema,\n} from \"./parsing\";\nimport {\n defaultContinuationInput,\n defaultInterruptFirstPassInput,\n withOutputGuardrails,\n withStructuredStreamHints,\n} from \"./prompting\";\nimport {\n extractCompletedArrayItems,\n extractCompletedFieldValue,\n extractStreamingStringValue,\n resolveAppendFieldPaths,\n resolveSetFieldPaths,\n resolveTextDeltaFieldPaths,\n} from \"./structured-stream\";\n\nconst mergeUsage = (\n left: KortyxUsage | undefined,\n right: KortyxUsage | undefined,\n): KortyxUsage | undefined => {\n if (!left) return right;\n if (!right) return left;\n\n const sum = (\n a: number | undefined,\n b: number | undefined,\n ): number | undefined =>\n a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n\n const raw =\n left.raw || right.raw\n ? {\n ...(left.raw ?? {}),\n ...(right.raw ?? {}),\n }\n : undefined;\n const input = sum(left.input, right.input);\n const output = sum(left.output, right.output);\n const total = sum(left.total, right.total);\n const reasoning = sum(left.reasoning, right.reasoning);\n const cacheRead = sum(left.cacheRead, right.cacheRead);\n const cacheWrite = sum(left.cacheWrite, right.cacheWrite);\n const merged: KortyxUsage = {};\n\n if (input !== undefined) merged.input = input;\n if (output !== undefined) merged.output = output;\n if (total !== undefined) merged.total = total;\n if (reasoning !== undefined) merged.reasoning = reasoning;\n if (cacheRead !== undefined) merged.cacheRead = cacheRead;\n if (cacheWrite !== undefined) merged.cacheWrite = cacheWrite;\n if (raw) merged.raw = raw;\n\n return merged;\n};\n\nconst mergeWarnings = (\n left: KortyxWarning[] | undefined,\n right: KortyxWarning[] | undefined,\n): KortyxWarning[] | undefined => {\n if (!left?.length) return right;\n if (!right?.length) return left;\n\n const seen = new Set<string>();\n const merged: KortyxWarning[] = [];\n for (const warning of [...left, ...right]) {\n const key = JSON.stringify(warning);\n if (seen.has(key)) continue;\n seen.add(key);\n merged.push(warning);\n }\n return merged;\n};\n\nconst mergeProviderMetadata = (\n left: KortyxProviderMetadata | undefined,\n right: KortyxProviderMetadata | undefined,\n): KortyxProviderMetadata | undefined => {\n if (!left) return right;\n if (!right) return left;\n return {\n ...left,\n ...right,\n };\n};\n\nconst emitReasonStructuredOutput = <TOutput>(args: {\n id?: string;\n opId: string;\n output: TOutput;\n structured: UseReasonArgs<TOutput>[\"structured\"];\n emit: boolean;\n}): void => {\n if (!args.emit || !shouldEmitStructured(args.structured)) return;\n\n emitStructuredData<TOutput>({\n dataType: args.structured?.dataType ?? \"reason-output\",\n data: args.output,\n kind: \"final\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(args.id ? { id: args.id } : {}),\n streamId: args.opId,\n });\n};\n\nconst shouldStreamReasonStructured = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): boolean => (args.emit ?? true) && shouldStreamStructured(args.structured);\n\nconst resolveEffectiveReasoningIncludeThoughts = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): boolean =>\n args.reasoning?.includeThoughts ??\n args.model.options?.reasoning?.includeThoughts ??\n false;\n\nconst resolveEffectiveResponseFormatType = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): \"text\" | \"json\" | undefined =>\n args.responseFormat?.type ?? args.model.options?.responseFormat?.type;\n\nconst assertReasoningThoughtsCompatibility = <\n TOutput,\n TRequest extends InterruptInput,\n TResponse,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): void => {\n if (!resolveEffectiveReasoningIncludeThoughts(args)) return;\n\n const usesStructuredOutput =\n Boolean(args.outputSchema) ||\n Boolean(args.interrupt) ||\n Boolean(args.structured) ||\n resolveEffectiveResponseFormatType(args) === \"json\";\n\n if (!usesStructuredOutput) return;\n\n throw new Error(\n \"useReason does not support reasoning.includeThoughts with structured output, interrupt mode, or JSON responseFormat. Disable includeThoughts for this call.\",\n );\n};\n\nexport async function useReason<\n TOutput = unknown,\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): Promise<UseReasonResult<TOutput, TResponse>> {\n assertReasoningThoughtsCompatibility(args);\n const ctx = getHookContext();\n const id =\n typeof args.id === \"string\" && args.id.length > 0 ? args.id : undefined;\n const opId = createRuntimeId();\n const checkpointKey = resolveReasonCheckpointKey({\n ...(id ? { id } : {}),\n autoIndex: ctx.reasonCallIndex++,\n });\n const existingCompleted = readReasonCompletedCheckpoint(\n ctx.currentNodeState.byKey[checkpointKey],\n );\n\n if (existingCompleted) {\n return existingCompleted.result as UseReasonResult<TOutput, TResponse>;\n }\n\n const existingCheckpoint = readReasonCheckpoint(\n ctx.currentNodeState.byKey[checkpointKey],\n );\n\n const reasonMeta =\n typeof id === \"string\" ? ({ id, opId } as const) : ({ opId } as const);\n const traceSpan: ReasonTraceSpan | undefined =\n getReasonTraceAdapter()?.startSpan({\n name: \"useReason\",\n attributes: {\n ...(id ? { id } : {}),\n opId,\n nodeId: ctx.node.graph.node,\n providerId: args.model.provider.id,\n modelId: args.model.modelId,\n stream: args.stream ?? args.model.options?.streaming ?? true,\n emit: args.emit ?? true,\n hasOutputSchema: Boolean(args.outputSchema),\n hasInterrupt: Boolean(args.interrupt),\n hasStructured: Boolean(args.structured),\n },\n });\n const suppressTextStream = Boolean(args.outputSchema || args.interrupt);\n const setFieldPaths = resolveSetFieldPaths(args.structured);\n const appendFieldPaths = resolveAppendFieldPaths(args.structured);\n const textDeltaFieldPaths = resolveTextDeltaFieldPaths(args.structured);\n const useStructuredIncrementalStreaming = Boolean(\n args.outputSchema &&\n !args.interrupt &&\n (setFieldPaths.length > 0 ||\n appendFieldPaths.length > 0 ||\n textDeltaFieldPaths.length > 0) &&\n args.stream !== false &&\n shouldStreamReasonStructured(args),\n );\n\n let firstText = \"\";\n let firstRaw: unknown;\n let firstOutput: TOutput | undefined;\n let firstInterruptRequest: TRequest | undefined;\n let firstInterruptRequired = false;\n\n let finalText = \"\";\n let finalRaw: unknown;\n let finalOutput: TOutput | undefined;\n let aggregatedUsage: KortyxUsage | undefined;\n let finalFinishReason: KortyxFinishReason | undefined;\n let aggregatedProviderMetadata: KortyxProviderMetadata | undefined;\n let aggregatedWarnings: KortyxWarning[] | undefined;\n const emittedSetValues = new Map<string, string>();\n const emittedAppendCounts = new Map<string, number>();\n const emittedTextValues = new Map<string, string>();\n\n if (existingCheckpoint) {\n firstText = existingCheckpoint.firstText;\n firstRaw = existingCheckpoint.firstRaw;\n firstOutput = existingCheckpoint.firstOutput as TOutput | undefined;\n finalText = firstText;\n finalRaw = firstRaw;\n finalOutput = firstOutput;\n aggregatedUsage = existingCheckpoint.firstUsage;\n finalFinishReason = existingCheckpoint.firstFinishReason;\n aggregatedProviderMetadata = existingCheckpoint.firstProviderMetadata;\n aggregatedWarnings = existingCheckpoint.firstWarnings;\n traceSpan?.addEvent?.(\"useReason.resume\", {\n checkpointKey,\n });\n } else {\n const first = await reasonEngine(\n {\n ...args,\n emit: suppressTextStream ? false : args.emit,\n stream: useStructuredIncrementalStreaming\n ? true\n : suppressTextStream\n ? false\n : args.stream,\n ...(useStructuredIncrementalStreaming\n ? {\n onTextChunk: (delta: string) => {\n firstText += delta;\n finalText = firstText;\n\n for (const path of setFieldPaths) {\n const current = extractCompletedFieldValue({\n text: firstText,\n path,\n });\n if (!current.found || !current.complete) continue;\n\n const nextSerialized = JSON.stringify(current.value);\n if (emittedSetValues.get(path) === nextSerialized) continue;\n\n emittedSetValues.set(path, nextSerialized);\n emitStructuredData({\n kind: \"set\",\n path,\n value: current.value,\n dataType: args.structured?.dataType ?? \"reason-output\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n streamId: opId,\n });\n }\n\n for (const path of appendFieldPaths) {\n const items = extractCompletedArrayItems({\n text: firstText,\n path,\n });\n const emittedAppendCount = emittedAppendCounts.get(path) ?? 0;\n if (items.length <= emittedAppendCount) continue;\n\n const nextItems = items.slice(emittedAppendCount);\n emittedAppendCounts.set(path, items.length);\n emitStructuredData({\n kind: \"append\",\n path,\n items: nextItems,\n dataType: args.structured?.dataType ?? \"reason-output\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n streamId: opId,\n });\n }\n\n for (const path of textDeltaFieldPaths) {\n const current = extractStreamingStringValue({\n text: firstText,\n path,\n });\n const emittedTextValue = emittedTextValues.get(path) ?? \"\";\n if (\n !current.found ||\n current.value.length <= emittedTextValue.length ||\n !current.value.startsWith(emittedTextValue)\n ) {\n continue;\n }\n\n const nextDelta = current.value.slice(\n emittedTextValue.length,\n );\n emittedTextValues.set(path, current.value);\n if (nextDelta.length === 0) continue;\n\n emitStructuredData({\n kind: \"text-delta\",\n path,\n delta: nextDelta,\n dataType: args.structured?.dataType ?? \"reason-output\",\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n streamId: opId,\n });\n }\n },\n }\n : {}),\n },\n reasonMeta,\n args.interrupt\n ? defaultInterruptFirstPassInput({\n input: args.input,\n requestSchema: args.interrupt.requestSchema,\n mode: args.interrupt.mode ?? \"required\",\n ...(args.outputSchema\n ? { outputSchema: args.outputSchema as SchemaLike<unknown> }\n : {}),\n })\n : args.outputSchema\n ? withOutputGuardrails(\n withStructuredStreamHints(args.input, {\n ...(setFieldPaths.length > 0 ? { setFieldPaths } : {}),\n ...(appendFieldPaths.length > 0 ? { appendFieldPaths } : {}),\n ...(textDeltaFieldPaths.length > 0\n ? { textDeltaFieldPaths }\n : {}),\n }),\n args.outputSchema as SchemaLike<unknown>,\n )\n : undefined,\n );\n firstRaw = first.raw;\n finalRaw = first.raw;\n accumulateTokenUsage(first.usage);\n aggregatedUsage = mergeUsage(aggregatedUsage, first.usage);\n finalFinishReason = first.finishReason;\n aggregatedProviderMetadata = mergeProviderMetadata(\n aggregatedProviderMetadata,\n first.providerMetadata,\n );\n aggregatedWarnings = mergeWarnings(aggregatedWarnings, first.warnings);\n traceSpan?.addEvent?.(\"useReason.first-pass.complete\", {\n textLength: first.text.length,\n hasInterrupt: Boolean(args.interrupt),\n });\n\n if (args.interrupt) {\n const firstPass = parseInterruptFirstPassResult<TRequest, TOutput>({\n text: first.text,\n requestSchema: args.interrupt.requestSchema,\n ...(first.finishReason ? { finishReason: first.finishReason } : {}),\n ...(args.outputSchema\n ? { outputSchema: args.outputSchema as SchemaLike<TOutput> }\n : {}),\n mode: args.interrupt.mode ?? \"required\",\n });\n firstText = firstPass.draftText;\n finalText = firstPass.draftText;\n firstInterruptRequired = firstPass.interruptRequired;\n firstInterruptRequest = firstPass.request;\n firstOutput = firstPass.output;\n finalOutput = firstPass.output;\n } else {\n firstText = first.text;\n finalText = first.text;\n if (args.outputSchema) {\n firstOutput = parseReasonOutputWithSchema({\n text: first.text,\n schema: args.outputSchema,\n ...(first.finishReason ? { finishReason: first.finishReason } : {}),\n label: \"useReason output\",\n });\n }\n finalOutput = firstOutput;\n }\n }\n\n let interruptResponse: TResponse | undefined;\n\n if (args.interrupt && (existingCheckpoint || firstInterruptRequired)) {\n const requestSchema = args.interrupt.requestSchema;\n\n const interruptRequest = existingCheckpoint\n ? parseWithSchema(\n requestSchema,\n existingCheckpoint.request,\n \"useReason interrupt.request\",\n )\n : firstInterruptRequest;\n\n if (!interruptRequest) {\n throw new Error(\n \"useReason interrupt request is missing; first pass did not produce a valid interrupt payload.\",\n );\n }\n\n if (!existingCheckpoint) {\n ctx.currentNodeState.byKey[checkpointKey] = {\n status: \"awaiting_interrupt\",\n request: interruptRequest,\n firstText,\n ...(firstRaw !== undefined ? { firstRaw } : {}),\n ...(aggregatedUsage !== undefined\n ? { firstUsage: aggregatedUsage }\n : {}),\n ...(finalFinishReason !== undefined\n ? { firstFinishReason: finalFinishReason }\n : {}),\n ...(aggregatedProviderMetadata !== undefined\n ? { firstProviderMetadata: aggregatedProviderMetadata }\n : {}),\n ...(aggregatedWarnings !== undefined\n ? { firstWarnings: aggregatedWarnings }\n : {}),\n ...(firstOutput !== undefined ? { firstOutput } : {}),\n } satisfies ReasonInterruptCheckpoint;\n ctx.stateDirty = true;\n }\n\n const resumeStatePatch = resolveHookStatePatch({\n nodeId: ctx.node.graph.node,\n currentNodeState: ctx.currentNodeState,\n workflowState: ctx.workflowState,\n });\n\n interruptResponse = await awaitInterruptInternal<TRequest, TResponse>({\n request: interruptRequest,\n requestSchema,\n responseSchema: args.interrupt.responseSchema,\n ...(args.interrupt.schemaId ? { schemaId: args.interrupt.schemaId } : {}),\n ...(args.interrupt.schemaVersion\n ? { schemaVersion: args.interrupt.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n meta: {\n __kortyxResumeStatePatch: resumeStatePatch,\n },\n });\n traceSpan?.addEvent?.(\"useReason.interrupt.resolved\", {\n checkpointKey,\n });\n\n if (Object.hasOwn(ctx.currentNodeState.byKey, checkpointKey)) {\n delete ctx.currentNodeState.byKey[checkpointKey];\n ctx.stateDirty = true;\n }\n\n const continuationInput = defaultContinuationInput({\n input: args.input,\n draftText: firstText,\n ...(firstOutput !== undefined ? { draftOutput: firstOutput } : {}),\n request: interruptRequest,\n response: interruptResponse,\n });\n\n const second = await reasonEngine(\n {\n ...args,\n emit: suppressTextStream ? false : args.emit,\n stream: suppressTextStream ? false : args.stream,\n },\n reasonMeta,\n args.outputSchema\n ? withOutputGuardrails(\n continuationInput,\n args.outputSchema as SchemaLike<unknown>,\n )\n : continuationInput,\n );\n finalText = second.text;\n finalRaw = second.raw;\n accumulateTokenUsage(second.usage);\n aggregatedUsage = mergeUsage(aggregatedUsage, second.usage);\n finalFinishReason = second.finishReason;\n aggregatedProviderMetadata = mergeProviderMetadata(\n aggregatedProviderMetadata,\n second.providerMetadata,\n );\n aggregatedWarnings = mergeWarnings(aggregatedWarnings, second.warnings);\n traceSpan?.addEvent?.(\"useReason.continuation.complete\", {\n textLength: second.text.length,\n });\n\n if (args.outputSchema) {\n finalOutput = parseReasonOutputWithSchema({\n text: finalText,\n schema: args.outputSchema,\n ...(second.finishReason ? { finishReason: second.finishReason } : {}),\n label: \"useReason output\",\n });\n }\n }\n\n if (finalOutput !== undefined) {\n emitReasonStructuredOutput<TOutput>({\n ...(id ? { id } : {}),\n opId,\n output: finalOutput,\n structured: args.structured,\n emit: args.emit ?? true,\n });\n }\n\n const result = {\n ...(id ? { id } : {}),\n opId,\n text: finalText,\n ...(finalRaw !== undefined ? { raw: finalRaw } : {}),\n ...(aggregatedUsage !== undefined ? { usage: aggregatedUsage } : {}),\n ...(finalFinishReason !== undefined\n ? { finishReason: finalFinishReason }\n : {}),\n ...(aggregatedProviderMetadata !== undefined\n ? { providerMetadata: aggregatedProviderMetadata }\n : {}),\n ...(aggregatedWarnings !== undefined\n ? { warnings: aggregatedWarnings }\n : {}),\n ...(finalOutput !== undefined ? { output: finalOutput } : {}),\n ...(interruptResponse !== undefined ? { interruptResponse } : {}),\n };\n\n if (args.interrupt) {\n ctx.currentNodeState.byKey[checkpointKey] = {\n status: \"completed\",\n result,\n };\n ctx.stateDirty = true;\n }\n\n traceSpan?.end?.({\n ...(aggregatedUsage !== undefined ? { usage: aggregatedUsage } : {}),\n ...(finalFinishReason !== undefined\n ? { finishReason: finalFinishReason }\n : {}),\n ...(aggregatedProviderMetadata !== undefined\n ? { providerMetadata: aggregatedProviderMetadata }\n : {}),\n ...(aggregatedWarnings !== undefined\n ? { warnings: aggregatedWarnings }\n : {}),\n attributes: {\n textLength: finalText.length,\n resumedFromCheckpoint: Boolean(existingCheckpoint),\n interrupted: Boolean(interruptResponse !== undefined),\n },\n });\n\n return result;\n}\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport { getHookContext } from \"./context\";\nimport { awaitInterruptInternal } from \"./interrupt\";\nimport { useReason as useReasonInternal } from \"./reason/use-reason\";\nimport { emitStructuredData } from \"./structured\";\nimport type {\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonResult,\n UseStructuredDataArgs,\n} from \"./types\";\n\nexport type {\n SchemaLike,\n StructuredDataKind,\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonInterruptConfig,\n UseReasonResult,\n UseReasonStructuredConfig,\n UseStructuredDataAppendArgs,\n UseStructuredDataArgs,\n UseStructuredDataFinalArgs,\n UseStructuredDataSetArgs,\n UseStructuredDataTextDeltaArgs,\n} from \"./types\";\n\ntype StateSetter<T> = (next: T | ((prev: T) => T)) => void;\n\nexport function useStructuredData<TData = unknown>(\n args: UseStructuredDataArgs<TData>,\n): void {\n emitStructuredData(args);\n}\n\nexport function useReason<\n TOutput = unknown,\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): Promise<UseReasonResult<TOutput, TResponse>> {\n return useReasonInternal(args);\n}\n\nexport function useInterrupt<\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(args: UseInterruptArgs<TRequest, TResponse>): Promise<TResponse> {\n return awaitInterruptInternal(args);\n}\n\nexport function useRuntimeContext<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n>(): TContext {\n const ctx = getHookContext();\n const config = ctx.state.config;\n const context =\n config && typeof config === \"object\" && \"context\" in config\n ? (config as { context?: unknown }).context\n : undefined;\n\n return context && typeof context === \"object\" && !Array.isArray(context)\n ? (context as TContext)\n : ({} as TContext);\n}\n\nexport function useNodeState<T>(initialValue: T): [T, StateSetter<T>] {\n const ctx = getHookContext();\n const nodeState = ctx.currentNodeState;\n\n const index = ctx.nodeStateIndex++;\n if (index >= nodeState.byIndex.length) {\n nodeState.byIndex[index] = initialValue as T;\n ctx.stateDirty = true;\n }\n\n const getValue = () => nodeState.byIndex[index] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n nodeState.byIndex[index] = resolved;\n ctx.stateDirty = true;\n };\n\n return [getValue(), setValue];\n}\n\nexport function useWorkflowState<T>(\n key: string,\n ...rest: [] | [T]\n): [T, StateSetter<T>] {\n const ctx = getHookContext();\n const workflowState = ctx.workflowState;\n const hasInitial = rest.length > 0;\n const initialValue = rest[0];\n\n if (!Object.hasOwn(workflowState, key) && hasInitial) {\n workflowState[key] = initialValue as T;\n ctx.stateDirty = true;\n }\n\n const getValue = () => workflowState[key] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n workflowState[key] = resolved;\n ctx.stateDirty = true;\n };\n\n return [getValue(), setValue];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;AAwDlC,IAAM,UAAU,IAAI,0CAAuC;AAE3D,IAAM,WAAW,CAAC,UAChB,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,qBAAqB,CAAC,UAAmC;AAC7D,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,EAAE,SAAS,CAAC,GAAG,KAAK,GAAG,OAAO,CAAC,EAAE;AAAA,EAC1C;AAEA,MAAI,SAAS,KAAK,GAAG;AACnB,UAAM,UAAU,MAAM,QAAQ,MAAM,OAAO,IAAI,CAAC,GAAG,MAAM,OAAO,IAAI,CAAC;AACrE,UAAM,QAAQ,SAAS,MAAM,KAAK,IAAI,EAAE,GAAG,MAAM,MAAM,IAAI,CAAC;AAC5D,WAAO,EAAE,SAAS,MAA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RuntimeId","isRecord","tryStringify","createRuntimeId","useReason"]}
|