luckytri 1.0.6 → 1.0.7

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.
Files changed (155) hide show
  1. package/LICENSE +21 -21
  2. package/docs/en/CHANGELOG.md +25 -16
  3. package/docs/en/chat-style.md +28 -9
  4. package/docs/en/guide.md +5 -5
  5. package/docs/en/her-life.md +2 -2
  6. package/docs/en/webui.md +1 -1
  7. package/docs/zh/CHANGELOG.md +25 -16
  8. package/docs/zh/chat-style.md +30 -9
  9. package/docs/zh/guide.md +5 -5
  10. package/docs/zh/her-life.md +2 -2
  11. package/docs/zh/webui.md +1 -1
  12. package/package.json +1 -1
  13. package/public/app/assets/{ChatsPage-DCYMkJ91.js → ChatsPage-CshdtTzV.js} +2 -2
  14. package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
  15. package/public/app/assets/{Empty-CLyZkxR5.js → Empty-C7yzOBzy.js} +1 -1
  16. package/public/app/assets/{Empty-DIobYG3x.css → Empty-DmUB2-Bk.css} +1 -1
  17. package/public/app/assets/{Field-BpaRwLI_.js → Field-BjFv4Rfn.js} +1 -1
  18. package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
  19. package/public/app/assets/{HeartPage-BIOMTiwr.js → HeartPage-eqo6ru16.js} +1 -1
  20. package/public/app/assets/LifePage-BUi5euBF.css +1 -0
  21. package/public/app/assets/{LifePage-BCgM4JkR.js → LifePage-CN8GE5NK.js} +1 -1
  22. package/public/app/assets/{MemoryPage-vShvRqMt.js → MemoryPage-CCpMN4Wg.js} +1 -1
  23. package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
  24. package/public/app/assets/{NaturePage-Cy9ptr4G.js → NaturePage-C0JqdBTR.js} +2 -2
  25. package/public/app/assets/NaturePage-CHkpb5NK.css +1 -0
  26. package/public/app/assets/PeoplePage-BTU0H1pM.css +1 -0
  27. package/public/app/assets/{PeoplePage-CUZekB2E.js → PeoplePage-BXGBbO4u.js} +1 -1
  28. package/public/app/assets/{PluginsPage-1RM4rmJP.js → PluginsPage-Dksp5AV5.js} +1 -1
  29. package/public/app/assets/{SystemPage-BI2CB5Ig.css → SystemPage-BenIyTvk.css} +1 -1
  30. package/public/app/assets/{SystemPage-BeT5TmIV.js → SystemPage-Cd7aa8eE.js} +1 -1
  31. package/public/app/assets/TimePage-BOms_n4I.css +1 -0
  32. package/public/app/assets/{TimePage-taTmPMM8.js → TimePage-Bs_zImb4.js} +2 -2
  33. package/public/app/assets/{index-DY5AM0Hz.css → index-BHZcHUMh.css} +1 -1
  34. package/public/app/assets/{index-DdYwC5ZU.js → index-CyRtYxP3.js} +3 -3
  35. package/public/app/assets/{knowledge-DJmfu2KN.js → knowledge-BJOIyuJo.js} +1 -1
  36. package/public/app/assets/{media-BEtnE0Gv.js → media-Bwtx8blz.js} +1 -1
  37. package/public/app/assets/{mind-Dtiw0-QK.js → mind-DtTVrW6Z.js} +1 -1
  38. package/public/app/index.html +5 -6
  39. package/public/guide.en.html +3 -3
  40. package/public/guide.html +3 -3
  41. package/scripts/import-data.js +128 -128
  42. package/scripts/proxy-config.js +167 -167
  43. package/scripts/update-instance.js +201 -201
  44. package/server/channels/adapters.js +27 -27
  45. package/server/channels/onebot/adapter.js +288 -288
  46. package/server/channels/qqbot/adapter.js +253 -253
  47. package/server/channels/qqbot/api.js +199 -199
  48. package/server/channels/qqbot/credentials.js +11 -11
  49. package/server/channels/qqbot/gateway.js +274 -274
  50. package/server/channels/qqbot/index.js +389 -389
  51. package/server/channels/segments.js +40 -40
  52. package/server/channels/session-key.js +153 -153
  53. package/server/channels/state.js +42 -42
  54. package/server/core/api.js +564 -564
  55. package/server/core/context-builder.js +288 -288
  56. package/server/core/context-compactor.js +454 -454
  57. package/server/core/conversation-cues.js +365 -325
  58. package/server/core/conversation-grounding.js +178 -0
  59. package/server/core/conversation-manager.js +87 -87
  60. package/server/core/dialogue-context.js +52 -0
  61. package/server/core/feedback.js +8 -8
  62. package/server/core/group-style.js +72 -72
  63. package/server/core/initiative-context.js +66 -66
  64. package/server/core/input-budget.js +32 -32
  65. package/server/core/local-demo.js +98 -98
  66. package/server/core/message-manager.js +118 -118
  67. package/server/core/message-scheduler.js +78 -78
  68. package/server/core/model-json.js +190 -190
  69. package/server/core/model-presets.js +900 -900
  70. package/server/core/name-call.js +29 -29
  71. package/server/core/network.js +157 -157
  72. package/server/core/person-name.js +22 -22
  73. package/server/core/persona-manager.js +324 -269
  74. package/server/core/reply-delivery.js +472 -404
  75. package/server/core/reply-target-resolver.js +50 -50
  76. package/server/core/response-generator.js +58 -50
  77. package/server/core/response-validator.js +30 -27
  78. package/server/core/retired-prompts.js +51 -51
  79. package/server/core/sessions.js +109 -109
  80. package/server/core/speaker-names.js +92 -92
  81. package/server/core/topic-tracker.js +65 -65
  82. package/server/core/turn.js +42 -8
  83. package/server/http.js +18 -18
  84. package/server/i18n/decisions.js +209 -209
  85. package/server/i18n/index.js +144 -144
  86. package/server/i18n/labels.js +0 -5
  87. package/server/i18n/models.js +111 -111
  88. package/server/knowledge/api.js +342 -342
  89. package/server/knowledge/embedding-profile.js +114 -114
  90. package/server/knowledge/index.js +13 -13
  91. package/server/knowledge/retrieval.js +93 -93
  92. package/server/knowledge/schema.js +158 -158
  93. package/server/knowledge/vector-index.js +90 -90
  94. package/server/mind/affect.js +265 -265
  95. package/server/mind/attention.js +200 -200
  96. package/server/mind/bonds.js +565 -565
  97. package/server/mind/clock.js +83 -83
  98. package/server/mind/context-selection.js +16 -4
  99. package/server/mind/continuity.js +562 -562
  100. package/server/mind/conversation-origin.js +175 -175
  101. package/server/mind/days.js +210 -210
  102. package/server/mind/evidence-read.js +45 -45
  103. package/server/mind/faces.js +373 -373
  104. package/server/mind/guard.js +68 -60
  105. package/server/mind/initiative.js +338 -338
  106. package/server/mind/life/activities.js +21 -21
  107. package/server/mind/life/context.js +330 -330
  108. package/server/mind/life/growth.js +261 -261
  109. package/server/mind/life/presence.js +305 -305
  110. package/server/mind/meetings.js +1069 -1069
  111. package/server/mind/memory-policy.js +48 -48
  112. package/server/mind/memory.js +888 -888
  113. package/server/mind/nature.js +358 -358
  114. package/server/mind/novelty.js +19 -19
  115. package/server/mind/periods.js +118 -118
  116. package/server/mind/reading.js +120 -120
  117. package/server/mind/relationship-context.js +71 -71
  118. package/server/mind/relationships.js +390 -390
  119. package/server/mind/salience.js +201 -201
  120. package/server/mind/schema.js +567 -567
  121. package/server/mind/self.js +496 -484
  122. package/server/mind/thoughts.js +274 -274
  123. package/server/mind/time/agenda.js +242 -242
  124. package/server/mind/time/api.js +200 -200
  125. package/server/mind/time/attention.js +34 -34
  126. package/server/mind/time/delivery-links.js +130 -130
  127. package/server/mind/time/games.js +7 -3
  128. package/server/mind/time/index.js +3 -0
  129. package/server/mind/time/model-material.js +77 -77
  130. package/server/mind/time/presentation.js +35 -51
  131. package/server/mind/time/schedule.js +83 -83
  132. package/server/mind/time/schema.js +84 -84
  133. package/server/mind/time/search.js +383 -383
  134. package/server/mind/time/sharing.js +472 -472
  135. package/server/mind/time/task-links.js +311 -311
  136. package/server/mind/time/works.js +438 -432
  137. package/server/mind/traits.js +191 -191
  138. package/server/mind/view.js +43 -6
  139. package/server/runtime/installation.js +116 -116
  140. package/server/runtime/update-manager.js +140 -140
  141. package/server/storage/data-package.js +298 -298
  142. package/server/storage/data-transfer-api.js +50 -50
  143. package/server/storage/data-transfer-worker.js +18 -18
  144. package/server/storage/data-transfer.js +416 -416
  145. package/server/studio/display-names.js +139 -139
  146. package/server/studio/management.js +102 -102
  147. package/server/studio/updates.js +144 -144
  148. package/server/version.js +10 -10
  149. package/public/app/assets/ChatsPage-CFMVozoG.css +0 -1
  150. package/public/app/assets/HeartPage-C-2jvgzF.css +0 -1
  151. package/public/app/assets/LifePage-CG1OHbRK.css +0 -1
  152. package/public/app/assets/MemoryPage-C_Bu4rfb.css +0 -1
  153. package/public/app/assets/NaturePage-CPZlImT0.css +0 -1
  154. package/public/app/assets/PeoplePage-3RRUITDz.css +0 -1
  155. package/public/app/assets/TimePage-C-guwPk2.css +0 -1
@@ -1,78 +1,78 @@
1
- import { randomUUID } from "node:crypto";
2
- import { persistReply } from "./message-manager.js";
3
- export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
- export async function deliver(
5
- repo,
6
- message,
7
- bubbles,
8
- trace,
9
- send,
10
- isCurrent,
11
- {
12
- wait = sleep,
13
- random = Math.random,
14
- now = Date.now,
15
- prepareBubble = (line) => line,
16
- } = {},
17
- ) {
18
- const ids = bubbles.map((text, i) => {
19
- const id = randomUUID();
20
- repo.db
21
- .prepare(
22
- "INSERT INTO core_outbox(id,trace_id,session_id,position,text,status,time) VALUES (?,?,?,?,?,?,?)",
23
- )
24
- .run(id, trace.id, message.sessionId, i, text, "pending", now());
25
- return id;
26
- });
27
- const sent = [];
28
- trace.sent = sent;
29
- try {
30
- for (let i = 0; i < bubbles.length; i++) {
31
- // Typing pace between bubbles; physical, not a decision.
32
- if (i)
33
- await wait(
34
- Math.min(1200, 300 + bubbles[i].length * 15 + random() * 350),
35
- );
36
- if (!isCurrent()) {
37
- trace.steps.push("发送前配置或语境变化,取消剩余气泡");
38
- break;
39
- }
40
- const outgoing = prepareBubble(bubbles[i]);
41
- repo.db
42
- .prepare("UPDATE core_outbox SET status='sending',text=? WHERE id=?")
43
- .run(outgoing, ids[i]);
44
- try {
45
- const result = await send(message, outgoing);
46
- repo.db
47
- .prepare(
48
- "UPDATE core_outbox SET status='confirmed',platform_id=? WHERE id=?",
49
- )
50
- .run(String(result?.message_id || ""), ids[i]);
51
- persistReply(
52
- repo,
53
- {
54
- ...message,
55
- traceId: trace.id,
56
- replyTargetIds: trace.decision?.targetMessageIds || [],
57
- },
58
- outgoing,
59
- result?.message_id,
60
- now(),
61
- );
62
- sent.push(outgoing);
63
- } catch (e) {
64
- repo.db
65
- .prepare("UPDATE core_outbox SET status='uncertain' WHERE id=?")
66
- .run(ids[i]);
67
- throw e;
68
- }
69
- }
70
- } finally {
71
- repo.db
72
- .prepare(
73
- "UPDATE core_outbox SET status='cancelled' WHERE trace_id=? AND status='pending'",
74
- )
75
- .run(trace.id);
76
- }
77
- return sent;
78
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { persistReply } from "./message-manager.js";
3
+ export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
+ export async function deliver(
5
+ repo,
6
+ message,
7
+ bubbles,
8
+ trace,
9
+ send,
10
+ isCurrent,
11
+ {
12
+ wait = sleep,
13
+ random = Math.random,
14
+ now = Date.now,
15
+ prepareBubble = (line) => line,
16
+ } = {},
17
+ ) {
18
+ const ids = bubbles.map((text, i) => {
19
+ const id = randomUUID();
20
+ repo.db
21
+ .prepare(
22
+ "INSERT INTO core_outbox(id,trace_id,session_id,position,text,status,time) VALUES (?,?,?,?,?,?,?)",
23
+ )
24
+ .run(id, trace.id, message.sessionId, i, text, "pending", now());
25
+ return id;
26
+ });
27
+ const sent = [];
28
+ trace.sent = sent;
29
+ try {
30
+ for (let i = 0; i < bubbles.length; i++) {
31
+ // Typing pace between bubbles; physical, not a decision.
32
+ if (i)
33
+ await wait(
34
+ Math.min(1200, 300 + bubbles[i].length * 15 + random() * 350),
35
+ );
36
+ if (!isCurrent()) {
37
+ trace.steps.push("发送前配置或语境变化,取消剩余气泡");
38
+ break;
39
+ }
40
+ const outgoing = prepareBubble(bubbles[i]);
41
+ repo.db
42
+ .prepare("UPDATE core_outbox SET status='sending',text=? WHERE id=?")
43
+ .run(outgoing, ids[i]);
44
+ try {
45
+ const result = await send(message, outgoing);
46
+ repo.db
47
+ .prepare(
48
+ "UPDATE core_outbox SET status='confirmed',platform_id=? WHERE id=?",
49
+ )
50
+ .run(String(result?.message_id || ""), ids[i]);
51
+ persistReply(
52
+ repo,
53
+ {
54
+ ...message,
55
+ traceId: trace.id,
56
+ replyTargetIds: trace.decision?.targetMessageIds || [],
57
+ },
58
+ outgoing,
59
+ result?.message_id,
60
+ now(),
61
+ );
62
+ sent.push(outgoing);
63
+ } catch (e) {
64
+ repo.db
65
+ .prepare("UPDATE core_outbox SET status='uncertain' WHERE id=?")
66
+ .run(ids[i]);
67
+ throw e;
68
+ }
69
+ }
70
+ } finally {
71
+ repo.db
72
+ .prepare(
73
+ "UPDATE core_outbox SET status='cancelled' WHERE trace_id=? AND status='pending'",
74
+ )
75
+ .run(trace.id);
76
+ }
77
+ return sent;
78
+ }
@@ -1,190 +1,190 @@
1
- // Models are asked for one JSON object and mostly comply. The rest of the time
2
- // they wrap it in a fence, think out loud first, add a sentence afterwards,
3
- // leave out a comma, or put an unescaped quote inside a Chinese sentence. A
4
- // whole turn (or a whole stretch of solitude) used to be lost to each of these.
5
- // Everything here only runs after strict parsing has failed, so a valid reply
6
- // is never touched, and a fragment is never pulled out of a truncated one.
7
-
8
- const THINK_BLOCK = /<(think|thinking|reasoning)>[\s\S]*?<\/\1>/gi;
9
-
10
- function withoutReasoning(raw) {
11
- let text = String(raw ?? "")
12
- .replace(/^\uFEFF/, "")
13
- .replace(THINK_BLOCK, "");
14
- // A reply that only shows the closing tag: everything before it is thinking.
15
- const close = text.search(/<\/(think|thinking|reasoning)>/i);
16
- if (close !== -1)
17
- text = text.replace(/^[\s\S]*<\/(think|thinking|reasoning)>/i, "");
18
- return text.trim();
19
- }
20
-
21
- function unfenced(text) {
22
- return text.replace(/^```(?:json)?\s*|\s*```$/gi, "").trim();
23
- }
24
-
25
- // End index of the JSON value that opens at `start`, or -1 when it never
26
- // closes. Quotes and escapes inside strings are respected.
27
- function balancedEnd(text, start) {
28
- const open = text[start];
29
- const stack = [open === "{" ? "}" : "]"];
30
- let inString = false;
31
- for (let i = start + 1; i < text.length; i++) {
32
- const c = text[i];
33
- if (inString) {
34
- if (c === "\\") i++;
35
- else if (c === '"') inString = false;
36
- continue;
37
- }
38
- if (c === '"') inString = true;
39
- else if (c === "{") stack.push("}");
40
- else if (c === "[") stack.push("]");
41
- else if (c === "}" || c === "]") {
42
- if (stack.pop() !== c) return -1;
43
- if (!stack.length) return i;
44
- }
45
- }
46
- return -1;
47
- }
48
-
49
- const isSpace = (c) => c === " " || c === "\n" || c === "\r" || c === "\t";
50
-
51
- function nextSignificant(text, from) {
52
- let i = from;
53
- while (i < text.length && isSpace(text[i])) i++;
54
- return i;
55
- }
56
-
57
- // Whether the string that starts at text[index] (a quote) is followed by a
58
- // colon, that is, whether it is an object key rather than a value.
59
- function startsKey(text, index) {
60
- for (let i = index + 1; i < text.length; i++) {
61
- if (text[i] === "\\") i++;
62
- else if (text[i] === '"') return text[nextSignificant(text, i + 1)] === ":";
63
- }
64
- return false;
65
- }
66
-
67
- // One pass over the text that fixes the slips models actually make:
68
- // raw line breaks inside strings, quotes inside a sentence, a missing comma
69
- // between two members, and a comma before a closing bracket.
70
- export function repairJson(text) {
71
- let out = "";
72
- let inString = false;
73
- const stack = [];
74
- // The last significant thing written outside a string, to spot a missing comma.
75
- let lastValue = false;
76
- for (let i = 0; i < text.length; i++) {
77
- const c = text[i];
78
- if (inString) {
79
- if (c === "\\") {
80
- out += c + (text[i + 1] ?? "");
81
- i++;
82
- } else if (c === '"') {
83
- const after = nextSignificant(text, i + 1);
84
- const next = text[after];
85
- if (
86
- after >= text.length ||
87
- next === "," ||
88
- next === "}" ||
89
- next === "]" ||
90
- next === ":"
91
- ) {
92
- inString = false;
93
- lastValue = true;
94
- out += c;
95
- } else if (next === '"' && startsKey(text, after)) {
96
- // `"a": "x" "b": 1` - the string ended and a comma is missing.
97
- inString = false;
98
- lastValue = true;
99
- out += c;
100
- } else out += '\\"';
101
- } else if (c === "\n") out += "\\n";
102
- else if (c === "\r") out += "\\r";
103
- else if (c === "\t") out += "\\t";
104
- else if (c < " ") out += " ";
105
- else out += c;
106
- continue;
107
- }
108
- if (isSpace(c)) {
109
- out += c;
110
- continue;
111
- }
112
- if (c === ",") {
113
- const next = text[nextSignificant(text, i + 1)];
114
- if (next === "}" || next === "]") continue;
115
- lastValue = false;
116
- out += c;
117
- continue;
118
- }
119
- if (c === '"') {
120
- if (lastValue) out += ",";
121
- inString = true;
122
- lastValue = false;
123
- out += c;
124
- continue;
125
- }
126
- if (c === "{" || c === "[") {
127
- if (lastValue) out += ",";
128
- lastValue = false;
129
- stack.push(c === "{" ? "}" : "]");
130
- out += c;
131
- continue;
132
- }
133
- if (c === "}" || c === "]") {
134
- lastValue = true;
135
- // A closer of the wrong kind (`]` where `}` is due) becomes the one the
136
- // opener asks for, and a closer with nothing left to close is dropped.
137
- if (stack.length) out += stack.pop();
138
- continue;
139
- }
140
- if (c === ":") {
141
- lastValue = false;
142
- out += c;
143
- continue;
144
- }
145
- // A number or a bare word.
146
- if (lastValue && /[-\d]|[tfn]/.test(c)) out += ",";
147
- lastValue = true;
148
- out += c;
149
- while (i + 1 < text.length && /[\w.+\-]/.test(text[i + 1])) {
150
- out += text[i + 1];
151
- i++;
152
- }
153
- }
154
- return out;
155
- }
156
-
157
- const tryParse = (text) => {
158
- try {
159
- return { value: JSON.parse(text) };
160
- } catch (error) {
161
- return { error };
162
- }
163
- };
164
-
165
- // Returns the parsed value or throws the error strict parsing gave, so callers
166
- // and traces keep the message they always had.
167
- export function parseModelJson(raw) {
168
- const text = withoutReasoning(raw);
169
- const plain = unfenced(text);
170
- const strict = tryParse(plain);
171
- if (!("error" in strict)) return strict.value;
172
-
173
- const candidates = [];
174
- const fence = /```(?:json)?\s*([\s\S]*?)```/i.exec(text);
175
- if (fence) candidates.push(fence[1].trim());
176
- const open = plain.search(/[{[]/);
177
- if (open !== -1) {
178
- const end = balancedEnd(plain, open);
179
- if (end !== -1) candidates.push(plain.slice(open, end + 1));
180
- else candidates.push(plain.slice(open));
181
- }
182
- candidates.push(plain);
183
- for (const candidate of candidates) {
184
- const first = tryParse(candidate);
185
- if (!("error" in first)) return first.value;
186
- const repaired = tryParse(repairJson(candidate));
187
- if (!("error" in repaired)) return repaired.value;
188
- }
189
- throw strict.error;
190
- }
1
+ // Models are asked for one JSON object and mostly comply. The rest of the time
2
+ // they wrap it in a fence, think out loud first, add a sentence afterwards,
3
+ // leave out a comma, or put an unescaped quote inside a Chinese sentence. A
4
+ // whole turn (or a whole stretch of solitude) used to be lost to each of these.
5
+ // Everything here only runs after strict parsing has failed, so a valid reply
6
+ // is never touched, and a fragment is never pulled out of a truncated one.
7
+
8
+ const THINK_BLOCK = /<(think|thinking|reasoning)>[\s\S]*?<\/\1>/gi;
9
+
10
+ function withoutReasoning(raw) {
11
+ let text = String(raw ?? "")
12
+ .replace(/^\uFEFF/, "")
13
+ .replace(THINK_BLOCK, "");
14
+ // A reply that only shows the closing tag: everything before it is thinking.
15
+ const close = text.search(/<\/(think|thinking|reasoning)>/i);
16
+ if (close !== -1)
17
+ text = text.replace(/^[\s\S]*<\/(think|thinking|reasoning)>/i, "");
18
+ return text.trim();
19
+ }
20
+
21
+ function unfenced(text) {
22
+ return text.replace(/^```(?:json)?\s*|\s*```$/gi, "").trim();
23
+ }
24
+
25
+ // End index of the JSON value that opens at `start`, or -1 when it never
26
+ // closes. Quotes and escapes inside strings are respected.
27
+ function balancedEnd(text, start) {
28
+ const open = text[start];
29
+ const stack = [open === "{" ? "}" : "]"];
30
+ let inString = false;
31
+ for (let i = start + 1; i < text.length; i++) {
32
+ const c = text[i];
33
+ if (inString) {
34
+ if (c === "\\") i++;
35
+ else if (c === '"') inString = false;
36
+ continue;
37
+ }
38
+ if (c === '"') inString = true;
39
+ else if (c === "{") stack.push("}");
40
+ else if (c === "[") stack.push("]");
41
+ else if (c === "}" || c === "]") {
42
+ if (stack.pop() !== c) return -1;
43
+ if (!stack.length) return i;
44
+ }
45
+ }
46
+ return -1;
47
+ }
48
+
49
+ const isSpace = (c) => c === " " || c === "\n" || c === "\r" || c === "\t";
50
+
51
+ function nextSignificant(text, from) {
52
+ let i = from;
53
+ while (i < text.length && isSpace(text[i])) i++;
54
+ return i;
55
+ }
56
+
57
+ // Whether the string that starts at text[index] (a quote) is followed by a
58
+ // colon, that is, whether it is an object key rather than a value.
59
+ function startsKey(text, index) {
60
+ for (let i = index + 1; i < text.length; i++) {
61
+ if (text[i] === "\\") i++;
62
+ else if (text[i] === '"') return text[nextSignificant(text, i + 1)] === ":";
63
+ }
64
+ return false;
65
+ }
66
+
67
+ // One pass over the text that fixes the slips models actually make:
68
+ // raw line breaks inside strings, quotes inside a sentence, a missing comma
69
+ // between two members, and a comma before a closing bracket.
70
+ export function repairJson(text) {
71
+ let out = "";
72
+ let inString = false;
73
+ const stack = [];
74
+ // The last significant thing written outside a string, to spot a missing comma.
75
+ let lastValue = false;
76
+ for (let i = 0; i < text.length; i++) {
77
+ const c = text[i];
78
+ if (inString) {
79
+ if (c === "\\") {
80
+ out += c + (text[i + 1] ?? "");
81
+ i++;
82
+ } else if (c === '"') {
83
+ const after = nextSignificant(text, i + 1);
84
+ const next = text[after];
85
+ if (
86
+ after >= text.length ||
87
+ next === "," ||
88
+ next === "}" ||
89
+ next === "]" ||
90
+ next === ":"
91
+ ) {
92
+ inString = false;
93
+ lastValue = true;
94
+ out += c;
95
+ } else if (next === '"' && startsKey(text, after)) {
96
+ // `"a": "x" "b": 1` - the string ended and a comma is missing.
97
+ inString = false;
98
+ lastValue = true;
99
+ out += c;
100
+ } else out += '\\"';
101
+ } else if (c === "\n") out += "\\n";
102
+ else if (c === "\r") out += "\\r";
103
+ else if (c === "\t") out += "\\t";
104
+ else if (c < " ") out += " ";
105
+ else out += c;
106
+ continue;
107
+ }
108
+ if (isSpace(c)) {
109
+ out += c;
110
+ continue;
111
+ }
112
+ if (c === ",") {
113
+ const next = text[nextSignificant(text, i + 1)];
114
+ if (next === "}" || next === "]") continue;
115
+ lastValue = false;
116
+ out += c;
117
+ continue;
118
+ }
119
+ if (c === '"') {
120
+ if (lastValue) out += ",";
121
+ inString = true;
122
+ lastValue = false;
123
+ out += c;
124
+ continue;
125
+ }
126
+ if (c === "{" || c === "[") {
127
+ if (lastValue) out += ",";
128
+ lastValue = false;
129
+ stack.push(c === "{" ? "}" : "]");
130
+ out += c;
131
+ continue;
132
+ }
133
+ if (c === "}" || c === "]") {
134
+ lastValue = true;
135
+ // A closer of the wrong kind (`]` where `}` is due) becomes the one the
136
+ // opener asks for, and a closer with nothing left to close is dropped.
137
+ if (stack.length) out += stack.pop();
138
+ continue;
139
+ }
140
+ if (c === ":") {
141
+ lastValue = false;
142
+ out += c;
143
+ continue;
144
+ }
145
+ // A number or a bare word.
146
+ if (lastValue && /[-\d]|[tfn]/.test(c)) out += ",";
147
+ lastValue = true;
148
+ out += c;
149
+ while (i + 1 < text.length && /[\w.+\-]/.test(text[i + 1])) {
150
+ out += text[i + 1];
151
+ i++;
152
+ }
153
+ }
154
+ return out;
155
+ }
156
+
157
+ const tryParse = (text) => {
158
+ try {
159
+ return { value: JSON.parse(text) };
160
+ } catch (error) {
161
+ return { error };
162
+ }
163
+ };
164
+
165
+ // Returns the parsed value or throws the error strict parsing gave, so callers
166
+ // and traces keep the message they always had.
167
+ export function parseModelJson(raw) {
168
+ const text = withoutReasoning(raw);
169
+ const plain = unfenced(text);
170
+ const strict = tryParse(plain);
171
+ if (!("error" in strict)) return strict.value;
172
+
173
+ const candidates = [];
174
+ const fence = /```(?:json)?\s*([\s\S]*?)```/i.exec(text);
175
+ if (fence) candidates.push(fence[1].trim());
176
+ const open = plain.search(/[{[]/);
177
+ if (open !== -1) {
178
+ const end = balancedEnd(plain, open);
179
+ if (end !== -1) candidates.push(plain.slice(open, end + 1));
180
+ else candidates.push(plain.slice(open));
181
+ }
182
+ candidates.push(plain);
183
+ for (const candidate of candidates) {
184
+ const first = tryParse(candidate);
185
+ if (!("error" in first)) return first.value;
186
+ const repaired = tryParse(repairJson(candidate));
187
+ if (!("error" in repaired)) return repaired.value;
188
+ }
189
+ throw strict.error;
190
+ }