@reinsjs/core 0.1.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 +18 -0
- package/LICENSE +21 -0
- package/README.md +76 -0
- package/dist/chunk-BOJD54XN.js +205 -0
- package/dist/chunk-BOJD54XN.js.map +1 -0
- package/dist/index.d.ts +1095 -0
- package/dist/index.js +1735 -0
- package/dist/index.js.map +1 -0
- package/dist/testing/index.d.ts +77 -0
- package/dist/testing/index.js +366 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/types-BeGSiC1e.d.ts +559 -0
- package/package.json +45 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1735 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CORE_SCHEMAS,
|
|
3
|
+
DEFAULT_TRUST,
|
|
4
|
+
EventSchemaRegistry,
|
|
5
|
+
SchemaError,
|
|
6
|
+
createCoreEvent,
|
|
7
|
+
createCoreRegistry,
|
|
8
|
+
createEvent,
|
|
9
|
+
uuidv7
|
|
10
|
+
} from "./chunk-BOJD54XN.js";
|
|
11
|
+
|
|
12
|
+
// src/events/core.ts
|
|
13
|
+
function contextTokensOf(usage) {
|
|
14
|
+
return usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/loop/fork.ts
|
|
18
|
+
async function forkSession(log, opts) {
|
|
19
|
+
const toSessionId = opts.toSessionId ?? uuidv7();
|
|
20
|
+
await log.fork(opts.fromSessionId, opts.atSeq, toSessionId);
|
|
21
|
+
return { toSessionId };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/lowering/errors.ts
|
|
25
|
+
var LoweringError = class extends Error {
|
|
26
|
+
constructor(code, message, context = {}) {
|
|
27
|
+
super(`[${code}] ${message}`);
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.context = context;
|
|
30
|
+
this.name = "LoweringError";
|
|
31
|
+
}
|
|
32
|
+
code;
|
|
33
|
+
context;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// src/loop/retry.ts
|
|
37
|
+
var DEFAULT_RETRY_MAX_ATTEMPTS = 3;
|
|
38
|
+
var DEFAULT_RETRY_BASE_DELAY_MS = 1e3;
|
|
39
|
+
var DEFAULT_RETRY_MAX_DELAY_MS = 8e3;
|
|
40
|
+
var TRANSIENT_STATUS = (status) => status === 408 || status === 409 || status === 429 || status >= 500;
|
|
41
|
+
var TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
42
|
+
"ECONNRESET",
|
|
43
|
+
"ECONNREFUSED",
|
|
44
|
+
"ETIMEDOUT",
|
|
45
|
+
"EAI_AGAIN",
|
|
46
|
+
"EPIPE",
|
|
47
|
+
"ENOTFOUND",
|
|
48
|
+
"ENETUNREACH",
|
|
49
|
+
"ECONNABORTED",
|
|
50
|
+
"UND_ERR_SOCKET",
|
|
51
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
52
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
53
|
+
"UND_ERR_BODY_TIMEOUT"
|
|
54
|
+
]);
|
|
55
|
+
var TRANSIENT_PATTERNS = [
|
|
56
|
+
/\b(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE|ENOTFOUND|ENETUNREACH|ECONNABORTED|UND_ERR_[A-Z_]+TIMEOUT|UND_ERR_SOCKET)\b/,
|
|
57
|
+
/\bterminated\b/i,
|
|
58
|
+
/connection (error|closed|reset|refused)/i,
|
|
59
|
+
/socket hang up/i,
|
|
60
|
+
/\bfetch failed\b/i,
|
|
61
|
+
/\b(timeout|timed out)\b/i,
|
|
62
|
+
/\boverloaded\b/i,
|
|
63
|
+
/rate[ _-]?limit/i,
|
|
64
|
+
/too many requests/i,
|
|
65
|
+
/temporarily unavailable/i,
|
|
66
|
+
/service unavailable/i,
|
|
67
|
+
/\bstream (ended|closed) (before|prematurely)/i,
|
|
68
|
+
/pi-ai 流在 done \/ error 之前就结束了/
|
|
69
|
+
];
|
|
70
|
+
var CONNECTION_ERROR_NAMES = /* @__PURE__ */ new Set([
|
|
71
|
+
"APIConnectionError",
|
|
72
|
+
"APIConnectionTimeoutError"
|
|
73
|
+
]);
|
|
74
|
+
function isDefinitelyPermanent(err) {
|
|
75
|
+
if (err instanceof LoweringError) return true;
|
|
76
|
+
const name = err?.name;
|
|
77
|
+
return name === "AbortError" || name === "APIUserAbortError";
|
|
78
|
+
}
|
|
79
|
+
function statusFromMessage(message) {
|
|
80
|
+
const m = /^\s*(\d{3})\b/.exec(message) ?? /\b(?:status(?:\s+code)?|HTTP)[\s:=]+(\d{3})\b/i.exec(message);
|
|
81
|
+
if (!m?.[1]) return void 0;
|
|
82
|
+
const status = Number(m[1]);
|
|
83
|
+
return status >= 100 && status <= 599 ? status : void 0;
|
|
84
|
+
}
|
|
85
|
+
function structuredOf(error) {
|
|
86
|
+
const layers = [];
|
|
87
|
+
let cur = error;
|
|
88
|
+
for (let depth = 0; cur && typeof cur === "object" && depth < 4; depth++) {
|
|
89
|
+
layers.push(cur);
|
|
90
|
+
cur = cur.cause;
|
|
91
|
+
}
|
|
92
|
+
const out = { texts: [] };
|
|
93
|
+
for (const l of layers) {
|
|
94
|
+
if (out.status === void 0 && typeof l.status === "number") out.status = l.status;
|
|
95
|
+
if (out.code === void 0 && typeof l.code === "string") out.code = l.code;
|
|
96
|
+
if (out.name === void 0 && typeof l.name === "string") out.name = l.name;
|
|
97
|
+
if (out.shouldRetry === void 0 && l.headers instanceof Headers) {
|
|
98
|
+
const h = l.headers.get("x-should-retry");
|
|
99
|
+
if (h === "true") out.shouldRetry = true;
|
|
100
|
+
else if (h === "false") out.shouldRetry = false;
|
|
101
|
+
}
|
|
102
|
+
if (typeof l.message === "string") out.texts.push(l.message);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
function isTransientFailure(failure) {
|
|
107
|
+
if (failure.kind === "outcome") {
|
|
108
|
+
const status2 = statusFromMessage(failure.message);
|
|
109
|
+
if (status2 !== void 0) return TRANSIENT_STATUS(status2);
|
|
110
|
+
return TRANSIENT_PATTERNS.some((re) => re.test(failure.message));
|
|
111
|
+
}
|
|
112
|
+
if (isDefinitelyPermanent(failure.error)) return false;
|
|
113
|
+
const info = structuredOf(failure.error);
|
|
114
|
+
if (info.name !== void 0 && CONNECTION_ERROR_NAMES.has(info.name)) return true;
|
|
115
|
+
if (info.shouldRetry !== void 0) return info.shouldRetry;
|
|
116
|
+
const status = info.status ?? info.texts.map(statusFromMessage).find((s) => s !== void 0);
|
|
117
|
+
if (status !== void 0) return TRANSIENT_STATUS(status);
|
|
118
|
+
if (info.code !== void 0 && TRANSIENT_CODES.has(info.code)) return true;
|
|
119
|
+
return TRANSIENT_PATTERNS.some((re) => info.texts.some((t) => re.test(t)));
|
|
120
|
+
}
|
|
121
|
+
function backoffDelayMs(attempt, opts = {}) {
|
|
122
|
+
const base = opts.baseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
|
|
123
|
+
const max = opts.maxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;
|
|
124
|
+
return Math.min(max, base * 2 ** Math.max(0, attempt - 1));
|
|
125
|
+
}
|
|
126
|
+
function defaultSleep(ms, signal) {
|
|
127
|
+
return new Promise((resolve2) => {
|
|
128
|
+
if (signal?.aborted) return resolve2();
|
|
129
|
+
const timer = setTimeout(done, ms);
|
|
130
|
+
function done() {
|
|
131
|
+
signal?.removeEventListener("abort", done);
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
resolve2();
|
|
134
|
+
}
|
|
135
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
function resolveRetry(opts = {}) {
|
|
139
|
+
const maxAttempts = opts.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
|
|
140
|
+
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
|
|
141
|
+
throw new RangeError(`retry.maxAttempts \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(maxAttempts)}`);
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
maxAttempts,
|
|
145
|
+
delayFor: (attempt) => backoffDelayMs(attempt, opts),
|
|
146
|
+
isTransient: opts.isTransient ?? isTransientFailure,
|
|
147
|
+
sleep: opts.sleep ?? defaultSleep
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// src/lowering/types.ts
|
|
152
|
+
function lossesOf(req) {
|
|
153
|
+
return req.landings.filter((l) => l.kind !== "exact");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/projection/filter.ts
|
|
157
|
+
var DEFAULT_MODEL_INVISIBLE_TYPES = /* @__PURE__ */ new Set([
|
|
158
|
+
"core.approval_request",
|
|
159
|
+
"core.approval_decision",
|
|
160
|
+
"core.run_paused",
|
|
161
|
+
"core.run_resumed",
|
|
162
|
+
"core.budget_usage",
|
|
163
|
+
"core.memory_op",
|
|
164
|
+
"core.handoff",
|
|
165
|
+
"core.error",
|
|
166
|
+
"core.tools_bound"
|
|
167
|
+
]);
|
|
168
|
+
function visibilityFilter(opts = {}) {
|
|
169
|
+
const invisible = opts.invisibleTypes ? new Set(opts.invisibleTypes) : DEFAULT_MODEL_INVISIBLE_TYPES;
|
|
170
|
+
const extra = opts.isVisible;
|
|
171
|
+
return {
|
|
172
|
+
name: "visibility-filter",
|
|
173
|
+
apply(events) {
|
|
174
|
+
return { events: events.filter((e) => !invisible.has(e.type) && (extra ? extra(e) : true)) };
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/projection/estimate.ts
|
|
180
|
+
var PER_EVENT_OVERHEAD = 4;
|
|
181
|
+
var IMAGE_TOKENS = 1600;
|
|
182
|
+
function estimateTextTokens(text) {
|
|
183
|
+
let ascii = 0;
|
|
184
|
+
let other = 0;
|
|
185
|
+
for (let i = 0; i < text.length; i++) {
|
|
186
|
+
if (text.charCodeAt(i) < 128) ascii++;
|
|
187
|
+
else other++;
|
|
188
|
+
}
|
|
189
|
+
return Math.ceil(ascii / 4) + other;
|
|
190
|
+
}
|
|
191
|
+
function partsTokens(parts) {
|
|
192
|
+
let n = 0;
|
|
193
|
+
for (const p of parts) n += p.type === "text" ? estimateTextTokens(p.text) : IMAGE_TOKENS;
|
|
194
|
+
return n;
|
|
195
|
+
}
|
|
196
|
+
function safeJson(value) {
|
|
197
|
+
const s = JSON.stringify(value);
|
|
198
|
+
return typeof s === "string" ? s : "";
|
|
199
|
+
}
|
|
200
|
+
function roughTokenEstimate(event) {
|
|
201
|
+
const e = event;
|
|
202
|
+
let body;
|
|
203
|
+
switch (e.type) {
|
|
204
|
+
case "core.user_message":
|
|
205
|
+
body = partsTokens(e.payload.content);
|
|
206
|
+
break;
|
|
207
|
+
case "core.tool_result":
|
|
208
|
+
body = partsTokens(e.payload.content) + estimateTextTokens(e.payload.name);
|
|
209
|
+
break;
|
|
210
|
+
case "core.model_text":
|
|
211
|
+
case "core.model_thinking":
|
|
212
|
+
case "core.system_note":
|
|
213
|
+
body = estimateTextTokens(e.payload.text);
|
|
214
|
+
break;
|
|
215
|
+
case "core.tool_call":
|
|
216
|
+
body = estimateTextTokens(e.payload.name) + estimateTextTokens(safeJson(e.payload.args));
|
|
217
|
+
break;
|
|
218
|
+
case "core.compaction":
|
|
219
|
+
case "core.handoff":
|
|
220
|
+
body = estimateTextTokens(e.payload.summary);
|
|
221
|
+
break;
|
|
222
|
+
default:
|
|
223
|
+
body = estimateTextTokens(safeJson(event.payload));
|
|
224
|
+
}
|
|
225
|
+
return body + PER_EVENT_OVERHEAD;
|
|
226
|
+
}
|
|
227
|
+
function estimateTotal(events, estimate) {
|
|
228
|
+
let n = 0;
|
|
229
|
+
for (const e of events) n += estimate(e);
|
|
230
|
+
return n;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// src/projection/fold.ts
|
|
234
|
+
function isCompaction(e) {
|
|
235
|
+
return e.type === "core.compaction";
|
|
236
|
+
}
|
|
237
|
+
function isPinNote(e) {
|
|
238
|
+
return e.type === "core.system_note" && e.payload.kind === "pin";
|
|
239
|
+
}
|
|
240
|
+
function covers(c, e) {
|
|
241
|
+
const [from, to] = c.payload.coversSeq;
|
|
242
|
+
return e.id !== c.id && e.seq >= from && e.seq <= to && e.seq < c.seq;
|
|
243
|
+
}
|
|
244
|
+
function supersededIds(timeline) {
|
|
245
|
+
const out = /* @__PURE__ */ new Set();
|
|
246
|
+
for (const e of timeline) {
|
|
247
|
+
if (e.type !== "core.system_note") continue;
|
|
248
|
+
const s = e.payload.supersedes;
|
|
249
|
+
if (s) {
|
|
250
|
+
for (const id of s) if (id !== e.id) out.add(id);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
function keptBy(c, e, autoKeepPinNotes, superseded = /* @__PURE__ */ new Set()) {
|
|
256
|
+
if (superseded.has(e.id)) return false;
|
|
257
|
+
return c.payload.pinsKept.includes(e.id) || autoKeepPinNotes && isPinNote(e);
|
|
258
|
+
}
|
|
259
|
+
function foldCompactions(opts = {}) {
|
|
260
|
+
const autoKeep = opts.autoKeepPinNotes ?? true;
|
|
261
|
+
return {
|
|
262
|
+
name: "fold-compactions",
|
|
263
|
+
apply(events, ctx) {
|
|
264
|
+
const compactions = events.filter(isCompaction);
|
|
265
|
+
if (compactions.length === 0) return { events: [...events] };
|
|
266
|
+
const superseded = supersededIds(ctx.timeline);
|
|
267
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
268
|
+
for (const e of events) {
|
|
269
|
+
const covering = compactions.filter((c) => covers(c, e));
|
|
270
|
+
if (covering.length > 0 && !covering.every((c) => keptBy(c, e, autoKeep, superseded)))
|
|
271
|
+
hidden.add(e.id);
|
|
272
|
+
}
|
|
273
|
+
const body = events.filter((e) => !hidden.has(e.id) && !isCompaction(e));
|
|
274
|
+
const visibleCompactions = compactions.filter((c) => !hidden.has(c.id)).sort((a, b) => a.seq - b.seq);
|
|
275
|
+
const insertBefore = /* @__PURE__ */ new Map();
|
|
276
|
+
for (const c of visibleCompactions) {
|
|
277
|
+
const to = Math.min(c.payload.coversSeq[1], c.seq - 1);
|
|
278
|
+
let idx = body.findIndex((e) => e.seq > to);
|
|
279
|
+
if (idx === -1) idx = body.length;
|
|
280
|
+
const bucket = insertBefore.get(idx);
|
|
281
|
+
if (bucket) bucket.push(c);
|
|
282
|
+
else insertBefore.set(idx, [c]);
|
|
283
|
+
}
|
|
284
|
+
const out = [];
|
|
285
|
+
for (let i = 0; i <= body.length; i++) {
|
|
286
|
+
const bucket = insertBefore.get(i);
|
|
287
|
+
if (bucket) out.push(...bucket);
|
|
288
|
+
const e = body[i];
|
|
289
|
+
if (e) out.push(e);
|
|
290
|
+
}
|
|
291
|
+
return { events: out };
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// src/projection/pins.ts
|
|
297
|
+
function reinjectPins() {
|
|
298
|
+
return {
|
|
299
|
+
name: "reinject-pins",
|
|
300
|
+
apply(events) {
|
|
301
|
+
const compactions = events.filter(isCompaction);
|
|
302
|
+
if (compactions.length === 0) return { events: [...events] };
|
|
303
|
+
const moved = /* @__PURE__ */ new Set();
|
|
304
|
+
const after = /* @__PURE__ */ new Map();
|
|
305
|
+
for (const e of events) {
|
|
306
|
+
if (isCompaction(e)) continue;
|
|
307
|
+
const covering = compactions.filter((c) => covers(c, e));
|
|
308
|
+
if (covering.length === 0) continue;
|
|
309
|
+
const target = covering.reduce((a, b) => b.seq > a.seq ? b : a);
|
|
310
|
+
moved.add(e.id);
|
|
311
|
+
const bucket = after.get(target.id);
|
|
312
|
+
if (bucket) bucket.push(e);
|
|
313
|
+
else after.set(target.id, [e]);
|
|
314
|
+
}
|
|
315
|
+
if (moved.size === 0) return { events: [...events] };
|
|
316
|
+
const out = [];
|
|
317
|
+
for (const e of events) {
|
|
318
|
+
if (moved.has(e.id)) continue;
|
|
319
|
+
out.push(e);
|
|
320
|
+
if (isCompaction(e)) {
|
|
321
|
+
const bucket = after.get(e.id);
|
|
322
|
+
if (bucket) out.push(...bucket);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return { events: out };
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// src/projection/manifest.ts
|
|
331
|
+
function textChars(content) {
|
|
332
|
+
let n = 0;
|
|
333
|
+
for (const p of content) if (p.type === "text") n += p.text.length;
|
|
334
|
+
return n;
|
|
335
|
+
}
|
|
336
|
+
function foldedToolResults(removed, opts = {}) {
|
|
337
|
+
const exclude = opts.exclude ?? /* @__PURE__ */ new Set();
|
|
338
|
+
const calls = /* @__PURE__ */ new Map();
|
|
339
|
+
for (const e of opts.lookup ?? removed) {
|
|
340
|
+
if (e.type === "core.tool_call") {
|
|
341
|
+
const c = e;
|
|
342
|
+
calls.set(c.payload.toolCallId, c);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const out = [];
|
|
346
|
+
for (const e of removed) {
|
|
347
|
+
if (e.type !== "core.tool_result") continue;
|
|
348
|
+
const r = e;
|
|
349
|
+
if (exclude.has(r.payload.name)) continue;
|
|
350
|
+
const item = {
|
|
351
|
+
seq: r.seq,
|
|
352
|
+
name: r.payload.name,
|
|
353
|
+
args: calls.get(r.payload.toolCallId)?.payload.args,
|
|
354
|
+
chars: textChars(r.payload.content),
|
|
355
|
+
isError: r.payload.isError
|
|
356
|
+
};
|
|
357
|
+
if (r.payload.spilled) item.spilledBlobId = r.payload.spilled.blobId;
|
|
358
|
+
out.push(item);
|
|
359
|
+
}
|
|
360
|
+
return out.sort((a, b) => a.seq - b.seq);
|
|
361
|
+
}
|
|
362
|
+
function digestArgs(args, max = 100) {
|
|
363
|
+
if (args === void 0) return "";
|
|
364
|
+
let text;
|
|
365
|
+
try {
|
|
366
|
+
text = JSON.stringify(
|
|
367
|
+
args,
|
|
368
|
+
(_k, v) => typeof v === "object" && v !== null && !Array.isArray(v) ? Object.fromEntries(
|
|
369
|
+
Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
|
|
370
|
+
) : v
|
|
371
|
+
) ?? String(args);
|
|
372
|
+
} catch {
|
|
373
|
+
text = String(args);
|
|
374
|
+
}
|
|
375
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
376
|
+
}
|
|
377
|
+
function fmtChars(n) {
|
|
378
|
+
return n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k chars` : `${n} chars`;
|
|
379
|
+
}
|
|
380
|
+
function renderFoldedToolResults(items, opts) {
|
|
381
|
+
if (items.length === 0) return "";
|
|
382
|
+
const maxItems = opts.maxItems ?? 80;
|
|
383
|
+
const lines = [opts.heading];
|
|
384
|
+
const shown = items.slice(0, maxItems);
|
|
385
|
+
for (const it of shown) {
|
|
386
|
+
const tail = it.spilledBlobId ? `stored as blob "${it.spilledBlobId}", read with fetch_blob` : `${fmtChars(it.chars)}${it.isError ? ", error" : ""}`;
|
|
387
|
+
lines.push(`- seq ${it.seq} ${it.name}(${digestArgs(it.args, opts.maxArgsChars)}) \u2014 ${tail}`);
|
|
388
|
+
}
|
|
389
|
+
if (items.length > shown.length) {
|
|
390
|
+
const rest = items.slice(shown.length);
|
|
391
|
+
lines.push(`- \u2026and ${rest.length} more (seq ${rest[0]?.seq}\u2013${rest[rest.length - 1]?.seq})`);
|
|
392
|
+
}
|
|
393
|
+
return lines.join("\n");
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/projection/truncate.ts
|
|
397
|
+
var ASSISTANT_TYPES = /* @__PURE__ */ new Set([
|
|
398
|
+
"core.model_thinking",
|
|
399
|
+
"core.model_text",
|
|
400
|
+
"core.tool_call"
|
|
401
|
+
]);
|
|
402
|
+
function splitTurns(events) {
|
|
403
|
+
const turns = [];
|
|
404
|
+
let current = [];
|
|
405
|
+
let currentIsAssistant = null;
|
|
406
|
+
for (const e of events) {
|
|
407
|
+
const isAssistant = ASSISTANT_TYPES.has(e.type);
|
|
408
|
+
if (currentIsAssistant !== null && isAssistant !== currentIsAssistant) {
|
|
409
|
+
turns.push(current);
|
|
410
|
+
current = [];
|
|
411
|
+
}
|
|
412
|
+
current.push(e);
|
|
413
|
+
currentIsAssistant = isAssistant;
|
|
414
|
+
}
|
|
415
|
+
if (current.length > 0) turns.push(current);
|
|
416
|
+
return turns;
|
|
417
|
+
}
|
|
418
|
+
function excerpt(parts, max = 120) {
|
|
419
|
+
const text = parts.map((p) => p.type === "text" ? p.text : "[image]").join(" ").replace(/\s+/g, " ").trim();
|
|
420
|
+
return text.length > max ? `${text.slice(0, max)}\u2026` : text;
|
|
421
|
+
}
|
|
422
|
+
var defaultThresholdSummary = (removed, ctx) => {
|
|
423
|
+
const prior = removed.filter(isCompaction);
|
|
424
|
+
const fresh = removed.filter((e) => !isCompaction(e));
|
|
425
|
+
const seqs = removed.map((e) => e.seq);
|
|
426
|
+
const from = Math.min(...seqs, ...prior.map((c) => c.payload.coversSeq[0]));
|
|
427
|
+
const to = Math.max(...seqs);
|
|
428
|
+
const counts = /* @__PURE__ */ new Map();
|
|
429
|
+
for (const e of fresh) counts.set(e.type, (counts.get(e.type) ?? 0) + 1);
|
|
430
|
+
const countText = [...counts.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([type, n]) => `${n} ${type.replace(/^core\./, "")}`).join(", ");
|
|
431
|
+
const lines = [
|
|
432
|
+
`[Context truncated by budget] Events seq ${from}-${to} were removed to fit the context window. They remain in the session log and can be recovered by the host if needed.`
|
|
433
|
+
];
|
|
434
|
+
if (countText) lines.push(`Removed: ${countText}.`);
|
|
435
|
+
if (prior.length > 0) {
|
|
436
|
+
lines.push("Earlier summaries (preserved verbatim):");
|
|
437
|
+
for (const c of prior) lines.push(`- ${c.payload.summary}`);
|
|
438
|
+
}
|
|
439
|
+
const users = fresh.filter((e) => e.type === "core.user_message");
|
|
440
|
+
if (users.length > 0) {
|
|
441
|
+
lines.push("User messages that were removed (openings only):");
|
|
442
|
+
for (const u of users) lines.push(`- ${excerpt(u.payload.content)}`);
|
|
443
|
+
}
|
|
444
|
+
const manifest = renderFoldedToolResults(foldedToolResults(fresh, { lookup: ctx.timeline }), {
|
|
445
|
+
heading: "Tool results that were removed (still in the session log, by seq):"
|
|
446
|
+
});
|
|
447
|
+
if (manifest) lines.push(manifest);
|
|
448
|
+
return lines.join("\n");
|
|
449
|
+
};
|
|
450
|
+
function turnStartsCleanly(turn) {
|
|
451
|
+
return !turn.some((e) => e.type === "core.tool_result");
|
|
452
|
+
}
|
|
453
|
+
function maxSeq(events) {
|
|
454
|
+
let m = 0;
|
|
455
|
+
for (const e of events) if (e.seq > m) m = e.seq;
|
|
456
|
+
return m;
|
|
457
|
+
}
|
|
458
|
+
function minSeq(events) {
|
|
459
|
+
let m = Number.POSITIVE_INFINITY;
|
|
460
|
+
for (const e of events) if (e.seq < m) m = e.seq;
|
|
461
|
+
return m;
|
|
462
|
+
}
|
|
463
|
+
function budgetTruncate(opts = {}) {
|
|
464
|
+
const autoKeep = opts.autoKeepPinNotes ?? true;
|
|
465
|
+
const summarize = opts.summarize ?? defaultThresholdSummary;
|
|
466
|
+
return {
|
|
467
|
+
name: "budget-truncate",
|
|
468
|
+
apply(events, ctx) {
|
|
469
|
+
const target = ctx.budget.contextLimit - ctx.budget.reserveTokens;
|
|
470
|
+
const total = estimateTotal(events, ctx.estimate);
|
|
471
|
+
if (total <= target) return { events: [...events] };
|
|
472
|
+
const turns = splitTurns(events);
|
|
473
|
+
let chosen = null;
|
|
474
|
+
let lastValid = null;
|
|
475
|
+
let removedTokens = 0;
|
|
476
|
+
for (let k2 = 1; k2 < turns.length; k2++) {
|
|
477
|
+
removedTokens += estimateTotal(turns[k2 - 1] ?? [], ctx.estimate);
|
|
478
|
+
const kept2 = turns.slice(k2).flat();
|
|
479
|
+
const removed2 = turns.slice(0, k2).flat();
|
|
480
|
+
const firstKept = turns[k2];
|
|
481
|
+
if (!firstKept || !turnStartsCleanly(firstKept)) continue;
|
|
482
|
+
if (minSeq(kept2) <= maxSeq(removed2)) continue;
|
|
483
|
+
lastValid = k2;
|
|
484
|
+
const { survivors: survivors2, summaryTokens } = plan(removed2, ctx, autoKeep, summarize);
|
|
485
|
+
if (total - removedTokens + summaryTokens + estimateTotal(survivors2, ctx.estimate) <= target) {
|
|
486
|
+
chosen = k2;
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
const k = chosen ?? lastValid;
|
|
491
|
+
if (k === null) return { events: [...events] };
|
|
492
|
+
const removed = turns.slice(0, k).flat();
|
|
493
|
+
const kept = turns.slice(k).flat();
|
|
494
|
+
const { survivors, compaction } = plan(removed, ctx, autoKeep, summarize);
|
|
495
|
+
return { events: [compaction, ...survivors, ...kept], emitted: [compaction] };
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
function plan(removed, ctx, autoKeep, summarize) {
|
|
500
|
+
const priorCompactions = removed.filter(isCompaction);
|
|
501
|
+
const superseded = supersededIds(ctx.timeline);
|
|
502
|
+
const survivors = removed.filter(
|
|
503
|
+
(e) => !isCompaction(e) && !superseded.has(e.id) && (autoKeep && isPinNote(e) || priorCompactions.some((c) => c.payload.pinsKept.includes(e.id)))
|
|
504
|
+
);
|
|
505
|
+
const from = Math.min(minSeq(removed), ...priorCompactions.map((c) => c.payload.coversSeq[0]));
|
|
506
|
+
const to = maxSeq(removed);
|
|
507
|
+
const compaction = createCoreEvent(ctx.registry, {
|
|
508
|
+
type: "core.compaction",
|
|
509
|
+
sessionId: ctx.sessionId,
|
|
510
|
+
seq: ctx.nextSeq(),
|
|
511
|
+
actor: "system",
|
|
512
|
+
at: ctx.now,
|
|
513
|
+
id: ctx.newId(ctx.now),
|
|
514
|
+
payload: {
|
|
515
|
+
coversSeq: [from, to],
|
|
516
|
+
summary: summarize(removed, ctx),
|
|
517
|
+
decidedBy: "threshold",
|
|
518
|
+
pinsKept: survivors.map((e) => e.id)
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
return { survivors, compaction, summaryTokens: ctx.estimate(compaction) };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/projection/project.ts
|
|
525
|
+
var DEFAULT_RESERVE_RATIO = 0.15;
|
|
526
|
+
function defaultProjectionChain(opts = {}) {
|
|
527
|
+
return [
|
|
528
|
+
visibilityFilter(opts.filter),
|
|
529
|
+
foldCompactions(opts.fold),
|
|
530
|
+
reinjectPins(),
|
|
531
|
+
budgetTruncate({ autoKeepPinNotes: opts.fold?.autoKeepPinNotes ?? true, ...opts.truncate })
|
|
532
|
+
];
|
|
533
|
+
}
|
|
534
|
+
var defaultRegistry;
|
|
535
|
+
function coreRegistry() {
|
|
536
|
+
if (!defaultRegistry) defaultRegistry = createCoreRegistry();
|
|
537
|
+
return defaultRegistry;
|
|
538
|
+
}
|
|
539
|
+
function project(opts) {
|
|
540
|
+
const { timeline } = opts;
|
|
541
|
+
for (let i = 1; i < timeline.length; i++) {
|
|
542
|
+
const prev = timeline[i - 1];
|
|
543
|
+
const cur = timeline[i];
|
|
544
|
+
if (prev && cur && cur.seq <= prev.seq) {
|
|
545
|
+
throw new RangeError(
|
|
546
|
+
`\u6295\u5F71\u8F93\u5165\u5FC5\u987B\u6309 seq \u4E25\u683C\u5347\u5E8F\uFF1A\u4F4D\u7F6E ${i} \u7684 seq ${cur.seq} \u4E0D\u5927\u4E8E\u524D\u4E00\u6761 ${prev.seq}`
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const last = timeline[timeline.length - 1];
|
|
551
|
+
const sessionId = opts.sessionId ?? last?.sessionId;
|
|
552
|
+
if (sessionId === void 0) throw new RangeError("\u7A7A\u65F6\u95F4\u7EBF\u5FC5\u987B\u663E\u5F0F\u63D0\u4F9B sessionId");
|
|
553
|
+
const reserveTokens = opts.budget.reserveTokens ?? Math.floor(opts.budget.contextLimit * DEFAULT_RESERVE_RATIO);
|
|
554
|
+
const budget = { contextLimit: opts.budget.contextLimit, reserveTokens };
|
|
555
|
+
const estimate = opts.estimate ?? roughTokenEstimate;
|
|
556
|
+
const registry = opts.registry ?? coreRegistry();
|
|
557
|
+
const now = opts.now ?? Date.now();
|
|
558
|
+
const newId = opts.newId ?? uuidv7;
|
|
559
|
+
const strategies = opts.strategies ?? defaultProjectionChain();
|
|
560
|
+
let events = [...timeline];
|
|
561
|
+
const emitted = [];
|
|
562
|
+
const steps = [];
|
|
563
|
+
const lastSeq = last?.seq ?? 0;
|
|
564
|
+
for (const strategy of strategies) {
|
|
565
|
+
const ctx = {
|
|
566
|
+
sessionId,
|
|
567
|
+
timeline,
|
|
568
|
+
budget,
|
|
569
|
+
estimate,
|
|
570
|
+
registry,
|
|
571
|
+
now,
|
|
572
|
+
newId,
|
|
573
|
+
emitted: [...emitted],
|
|
574
|
+
nextSeq: () => lastSeq + emitted.length + 1
|
|
575
|
+
};
|
|
576
|
+
const before = events.length;
|
|
577
|
+
const step = strategy.apply(events, ctx);
|
|
578
|
+
events = step.events;
|
|
579
|
+
if (step.emitted) emitted.push(...step.emitted);
|
|
580
|
+
steps.push({ name: strategy.name, before, after: events.length });
|
|
581
|
+
}
|
|
582
|
+
const estimatedTokens = estimateTotal(events, estimate);
|
|
583
|
+
const targetTokens = budget.contextLimit - budget.reserveTokens;
|
|
584
|
+
return {
|
|
585
|
+
events,
|
|
586
|
+
emitted,
|
|
587
|
+
stats: { estimatedTokens, targetTokens, overBudget: estimatedTokens > targetTokens, steps }
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// src/store/read-timeline.ts
|
|
592
|
+
async function* readEvents(log, sessionId, opts) {
|
|
593
|
+
const { registry, ...range } = opts;
|
|
594
|
+
for await (const raw of log.read(sessionId, range)) yield registry.read(raw);
|
|
595
|
+
}
|
|
596
|
+
async function readTimeline(log, sessionId, opts) {
|
|
597
|
+
const out = [];
|
|
598
|
+
for await (const e of readEvents(log, sessionId, opts)) out.push(e);
|
|
599
|
+
return out;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// src/loop/state.ts
|
|
603
|
+
function pendingToolCalls(timeline) {
|
|
604
|
+
const answered = /* @__PURE__ */ new Set();
|
|
605
|
+
for (const raw of timeline) {
|
|
606
|
+
const e = raw;
|
|
607
|
+
if (e.type === "core.tool_result") answered.add(e.payload.toolCallId);
|
|
608
|
+
}
|
|
609
|
+
const pending = [];
|
|
610
|
+
for (const raw of timeline) {
|
|
611
|
+
const e = raw;
|
|
612
|
+
if (e.type === "core.tool_call" && !answered.has(e.payload.toolCallId)) pending.push(e);
|
|
613
|
+
}
|
|
614
|
+
return pending;
|
|
615
|
+
}
|
|
616
|
+
var encoder = new TextEncoder();
|
|
617
|
+
function hex(bytes) {
|
|
618
|
+
return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
619
|
+
}
|
|
620
|
+
async function sha256(material) {
|
|
621
|
+
return hex(await crypto.subtle.digest("SHA-256", encoder.encode(material)));
|
|
622
|
+
}
|
|
623
|
+
async function computeConfigHash(input) {
|
|
624
|
+
return sha256(
|
|
625
|
+
JSON.stringify({
|
|
626
|
+
model: input.model,
|
|
627
|
+
tools: input.tools.map((t) => t.name).sort(),
|
|
628
|
+
systemPrompt: input.systemPrompt ?? null
|
|
629
|
+
})
|
|
630
|
+
);
|
|
631
|
+
}
|
|
632
|
+
async function computePendingDigest(calls) {
|
|
633
|
+
return sha256(
|
|
634
|
+
JSON.stringify(calls.map((c) => [c.payload.toolCallId, c.payload.name, c.payload.args ?? null]))
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
async function serializeRunState(input) {
|
|
638
|
+
const state = {
|
|
639
|
+
v: 1,
|
|
640
|
+
sessionId: input.sessionId,
|
|
641
|
+
lastSeq: input.lastSeq,
|
|
642
|
+
pendingToolCallIds: input.pending.map((c) => c.payload.toolCallId),
|
|
643
|
+
configHash: input.configHash,
|
|
644
|
+
pendingDigest: await computePendingDigest(input.pending)
|
|
645
|
+
};
|
|
646
|
+
return input.secret === void 0 ? state : signRunState(state, input.secret);
|
|
647
|
+
}
|
|
648
|
+
function signingMaterial(state) {
|
|
649
|
+
return JSON.stringify([
|
|
650
|
+
state.v,
|
|
651
|
+
state.sessionId,
|
|
652
|
+
state.lastSeq,
|
|
653
|
+
state.pendingToolCallIds,
|
|
654
|
+
state.configHash,
|
|
655
|
+
state.pendingDigest
|
|
656
|
+
]);
|
|
657
|
+
}
|
|
658
|
+
async function hmac(secret, material) {
|
|
659
|
+
const key = await crypto.subtle.importKey(
|
|
660
|
+
"raw",
|
|
661
|
+
encoder.encode(secret),
|
|
662
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
663
|
+
false,
|
|
664
|
+
["sign"]
|
|
665
|
+
);
|
|
666
|
+
return hex(await crypto.subtle.sign("HMAC", key, encoder.encode(material)));
|
|
667
|
+
}
|
|
668
|
+
async function signRunState(state, secret) {
|
|
669
|
+
const { sig: _drop, ...unsigned } = state;
|
|
670
|
+
return { ...unsigned, sig: await hmac(secret, signingMaterial(unsigned)) };
|
|
671
|
+
}
|
|
672
|
+
function timingSafeEqual(a, b) {
|
|
673
|
+
if (a.length !== b.length) return false;
|
|
674
|
+
let diff = 0;
|
|
675
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
676
|
+
return diff === 0;
|
|
677
|
+
}
|
|
678
|
+
async function verifyRunState(state, secret) {
|
|
679
|
+
if (typeof state.sig !== "string") return false;
|
|
680
|
+
const expected = await hmac(secret, signingMaterial(state));
|
|
681
|
+
return timingSafeEqual(expected, state.sig);
|
|
682
|
+
}
|
|
683
|
+
var RunStateError = class extends Error {
|
|
684
|
+
constructor(code, message, context = {}) {
|
|
685
|
+
super(`[${code}] ${message}`);
|
|
686
|
+
this.code = code;
|
|
687
|
+
this.context = context;
|
|
688
|
+
this.name = "RunStateError";
|
|
689
|
+
}
|
|
690
|
+
code;
|
|
691
|
+
context;
|
|
692
|
+
};
|
|
693
|
+
function assertRunStateShape(raw) {
|
|
694
|
+
const s = raw;
|
|
695
|
+
const ok = typeof s === "object" && s !== null && s.v === 1 && typeof s.sessionId === "string" && Number.isInteger(s.lastSeq) && Array.isArray(s.pendingToolCallIds) && s.pendingToolCallIds.every((id) => typeof id === "string") && typeof s.configHash === "string" && typeof s.pendingDigest === "string" && (s.sig === void 0 || typeof s.sig === "string");
|
|
696
|
+
if (!ok) throw new RunStateError("malformed", "run \u72B6\u6001\u4E0D\u662F v1 \u7684\u5F62\u72B6");
|
|
697
|
+
}
|
|
698
|
+
async function validateResume(input) {
|
|
699
|
+
const { state } = input;
|
|
700
|
+
assertRunStateShape(state);
|
|
701
|
+
if (state.sessionId !== input.sessionId) {
|
|
702
|
+
throw new RunStateError(
|
|
703
|
+
"session_mismatch",
|
|
704
|
+
`\u72B6\u6001\u5C5E\u4E8E\u4F1A\u8BDD ${state.sessionId}\uFF0C\u5F53\u524D\u662F ${input.sessionId}`,
|
|
705
|
+
{
|
|
706
|
+
expected: input.sessionId,
|
|
707
|
+
got: state.sessionId
|
|
708
|
+
}
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
if (input.secret !== void 0) {
|
|
712
|
+
if (state.sig === void 0) throw new RunStateError("missing_signature", "\u914D\u7F6E\u4E86\u5BC6\u94A5\uFF0C\u4F46\u72B6\u6001\u6CA1\u6709\u7B7E\u540D");
|
|
713
|
+
if (!await verifyRunState(state, input.secret)) {
|
|
714
|
+
throw new RunStateError("bad_signature", "\u72B6\u6001\u7B7E\u540D\u4E0D\u5339\u914D\uFF1A\u5185\u5BB9\u88AB\u6539\u8FC7\u6216\u5BC6\u94A5\u4E0D\u540C");
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
if (state.configHash !== input.configHash && !input.allowConfigDrift) {
|
|
718
|
+
throw new RunStateError(
|
|
719
|
+
"config_mismatch",
|
|
720
|
+
"\u6A21\u578B\u3001\u5DE5\u5177\u96C6\u6216\u7CFB\u7EDF\u63D0\u793A\u4E0E\u6682\u505C\u65F6\u4E0D\u540C\uFF1B\u786E\u8BA4\u65E0\u8BEF\u53EF\u4F20 allowConfigDrift",
|
|
721
|
+
{
|
|
722
|
+
expected: state.configHash,
|
|
723
|
+
got: input.configHash
|
|
724
|
+
}
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
const lastSeq = input.timeline[input.timeline.length - 1]?.seq ?? 0;
|
|
728
|
+
if (lastSeq < state.lastSeq) {
|
|
729
|
+
throw new RunStateError("log_behind", `\u65E5\u5FD7\u53EA\u5230 seq ${lastSeq}\uFF0C\u72B6\u6001\u8BB0\u5F55\u7684\u662F ${state.lastSeq}`, {
|
|
730
|
+
logLastSeq: lastSeq,
|
|
731
|
+
stateLastSeq: state.lastSeq
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
const pending = pendingToolCalls(input.timeline);
|
|
735
|
+
const ids = pending.map((c) => c.payload.toolCallId);
|
|
736
|
+
if (JSON.stringify(ids) !== JSON.stringify(state.pendingToolCallIds) || await computePendingDigest(pending) !== state.pendingDigest) {
|
|
737
|
+
throw new RunStateError("pending_mismatch", "\u65E5\u5FD7\u91CC\u7684\u5F85\u5904\u7406\u8C03\u7528\u4E0E\u72B6\u6001\u4E0D\u4E00\u81F4", {
|
|
738
|
+
expected: state.pendingToolCallIds,
|
|
739
|
+
got: ids
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
return pending;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// src/loop/static.ts
|
|
746
|
+
async function resolve(contribution, setup) {
|
|
747
|
+
if (typeof contribution === "function")
|
|
748
|
+
return await contribution(setup);
|
|
749
|
+
return contribution;
|
|
750
|
+
}
|
|
751
|
+
async function resolveSocketContributions(cfg) {
|
|
752
|
+
const hostTools = cfg.tools ?? [];
|
|
753
|
+
const sockets = cfg.sockets ?? [];
|
|
754
|
+
const setup = {
|
|
755
|
+
log: cfg.log,
|
|
756
|
+
model: cfg.model,
|
|
757
|
+
hostTools,
|
|
758
|
+
...cfg.blobs ? { blobs: cfg.blobs } : {},
|
|
759
|
+
...cfg.memory ? { memory: cfg.memory } : {},
|
|
760
|
+
...cfg.principal ? { principal: cfg.principal } : {}
|
|
761
|
+
};
|
|
762
|
+
const tools = [...hostTools];
|
|
763
|
+
const names = new Set(hostTools.map((t) => t.name));
|
|
764
|
+
const prompts = [];
|
|
765
|
+
if (typeof cfg.systemPrompt === "string" && cfg.systemPrompt.trim().length > 0)
|
|
766
|
+
prompts.push(cfg.systemPrompt);
|
|
767
|
+
for (const s of sockets) {
|
|
768
|
+
for (const t of await resolve(s.tools, setup) ?? []) {
|
|
769
|
+
if (names.has(t.name)) continue;
|
|
770
|
+
names.add(t.name);
|
|
771
|
+
tools.push(t);
|
|
772
|
+
}
|
|
773
|
+
const prompt = await resolve(s.systemPrompt, setup);
|
|
774
|
+
if (typeof prompt === "string" && prompt.trim().length > 0) prompts.push(prompt);
|
|
775
|
+
}
|
|
776
|
+
return prompts.length > 0 ? { tools, systemPrompt: prompts.join("\n\n") } : { tools };
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// src/loop/subagent.ts
|
|
780
|
+
var SUBAGENT_PAUSE = /* @__PURE__ */ Symbol.for("reins.subagentPause");
|
|
781
|
+
function subagentPause(detail) {
|
|
782
|
+
return { [SUBAGENT_PAUSE]: true, detail };
|
|
783
|
+
}
|
|
784
|
+
function isSubagentPause(value) {
|
|
785
|
+
return typeof value === "object" && value !== null && value[SUBAGENT_PAUSE] === true;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// src/loop/tools.ts
|
|
789
|
+
function toolResultTrust(tool, isError) {
|
|
790
|
+
if (!tool || tool.resultTrust === void 0 || isError) return void 0;
|
|
791
|
+
return tool.resultTrust;
|
|
792
|
+
}
|
|
793
|
+
function defineTool(tool) {
|
|
794
|
+
return tool;
|
|
795
|
+
}
|
|
796
|
+
function toolSpecOf(tool) {
|
|
797
|
+
return { name: tool.name, description: tool.description, inputSchema: tool.inputSchema };
|
|
798
|
+
}
|
|
799
|
+
function isContentPart(x) {
|
|
800
|
+
if (typeof x !== "object" || x === null) return false;
|
|
801
|
+
const p = x;
|
|
802
|
+
if (p.type === "text") return typeof p.text === "string";
|
|
803
|
+
if (p.type === "image") return typeof p.mime === "string" && typeof p.data === "string";
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
function isToolResult(x) {
|
|
807
|
+
if (typeof x !== "object" || x === null) return false;
|
|
808
|
+
const r = x;
|
|
809
|
+
return Array.isArray(r.content) && r.content.every(isContentPart) && (r.isError === void 0 || typeof r.isError === "boolean");
|
|
810
|
+
}
|
|
811
|
+
function normalizeToolOutput(output) {
|
|
812
|
+
if (typeof output === "string") return { content: [{ type: "text", text: output }] };
|
|
813
|
+
if (output === void 0 || output === null) return { content: [{ type: "text", text: "" }] };
|
|
814
|
+
if (Array.isArray(output) && output.every(isContentPart)) return { content: output };
|
|
815
|
+
if (isToolResult(output)) return output;
|
|
816
|
+
const json = JSON.stringify(output);
|
|
817
|
+
return { content: [{ type: "text", text: typeof json === "string" ? json : String(output) }] };
|
|
818
|
+
}
|
|
819
|
+
function errorMessageOf(err) {
|
|
820
|
+
if (err instanceof Error) return err.message;
|
|
821
|
+
return typeof err === "string" ? err : JSON.stringify(err) ?? String(err);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// src/loop/tools-bound.ts
|
|
825
|
+
function lastToolsBound(timeline) {
|
|
826
|
+
for (let i = timeline.length - 1; i >= 0; i--) {
|
|
827
|
+
const e = timeline[i];
|
|
828
|
+
if (e?.type === "core.tools_bound") return e;
|
|
829
|
+
}
|
|
830
|
+
return void 0;
|
|
831
|
+
}
|
|
832
|
+
function diffToolNames(previous, next) {
|
|
833
|
+
const before = new Set(previous);
|
|
834
|
+
const after = new Set(next);
|
|
835
|
+
const added = [...after].filter((n) => !before.has(n)).sort();
|
|
836
|
+
const removed = [...before].filter((n) => !after.has(n)).sort();
|
|
837
|
+
if (added.length === 0 && removed.length === 0) return void 0;
|
|
838
|
+
return { added, removed };
|
|
839
|
+
}
|
|
840
|
+
function renderToolChangeNote(diff) {
|
|
841
|
+
const lines = ["Your available tools changed since the previous run."];
|
|
842
|
+
if (diff.added.length > 0) lines.push(`Added: ${diff.added.join(", ")}.`);
|
|
843
|
+
if (diff.removed.length > 0)
|
|
844
|
+
lines.push(`Removed (no longer callable, even if earlier turns used them): ${diff.removed.join(", ")}.`);
|
|
845
|
+
return lines.join(" ");
|
|
846
|
+
}
|
|
847
|
+
function toolsBoundDrafts(input) {
|
|
848
|
+
const toolNames = [...input.toolNames].sort();
|
|
849
|
+
const drafts = [
|
|
850
|
+
{ type: "core.tools_bound", actor: "system", payload: { toolNames, configHash: input.configHash } }
|
|
851
|
+
];
|
|
852
|
+
const previous = lastToolsBound(input.timeline);
|
|
853
|
+
if (!input.announce || previous === void 0) return drafts;
|
|
854
|
+
const diff = diffToolNames(previous.payload.toolNames, toolNames);
|
|
855
|
+
if (!diff) return drafts;
|
|
856
|
+
drafts.push({
|
|
857
|
+
type: "core.system_note",
|
|
858
|
+
actor: "host",
|
|
859
|
+
payload: { kind: "host", text: renderToolChangeNote(diff), meta: { toolsChanged: diff } }
|
|
860
|
+
});
|
|
861
|
+
return drafts;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// src/loop/run-loop.ts
|
|
865
|
+
var DEFAULT_MAX_TURNS = 100;
|
|
866
|
+
var BUILTIN_APPROVAL_POLICY = "tool.needsApproval";
|
|
867
|
+
var INPUT_DRAFT_TYPES = /* @__PURE__ */ new Set([
|
|
868
|
+
"core.user_message",
|
|
869
|
+
"core.tool_result",
|
|
870
|
+
"core.system_note"
|
|
871
|
+
]);
|
|
872
|
+
function inputDraft(input) {
|
|
873
|
+
if (typeof input === "string")
|
|
874
|
+
return { type: "core.user_message", actor: "user", payload: { content: [{ type: "text", text: input }] } };
|
|
875
|
+
if (Array.isArray(input))
|
|
876
|
+
return { type: "core.user_message", actor: "user", payload: { content: input } };
|
|
877
|
+
if (typeof input.type !== "string" || !INPUT_DRAFT_TYPES.has(input.type) && !input.type.startsWith("ext.")) {
|
|
878
|
+
throw new RangeError(
|
|
879
|
+
`input \u8349\u7A3F\u4E0D\u63A5\u53D7\u4E8B\u4EF6\u7C7B\u578B ${String(input.type)}\uFF1A\u53EA\u80FD\u662F core.user_message\u3001core.tool_result\u3001core.system_note \u6216 ext.*`
|
|
880
|
+
);
|
|
881
|
+
}
|
|
882
|
+
return input;
|
|
883
|
+
}
|
|
884
|
+
async function* runLoop(cfg) {
|
|
885
|
+
const { sessionId, log, lowering, model } = cfg;
|
|
886
|
+
const registry = cfg.registry ?? createCoreRegistry();
|
|
887
|
+
const now = cfg.now ?? (() => Date.now());
|
|
888
|
+
const newId = cfg.newId ?? uuidv7;
|
|
889
|
+
const sockets = cfg.sockets ?? [];
|
|
890
|
+
const { tools: baseTools, systemPrompt: baseSystemPrompt } = await resolveSocketContributions(cfg);
|
|
891
|
+
const maxTurns = cfg.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
892
|
+
const retry = resolveRetry(cfg.retry);
|
|
893
|
+
const input = cfg.input !== void 0 ? inputDraft(cfg.input) : void 0;
|
|
894
|
+
const capabilities = lowering.capabilities(model);
|
|
895
|
+
const configHash = await computeConfigHash({
|
|
896
|
+
model,
|
|
897
|
+
tools: baseTools,
|
|
898
|
+
...baseSystemPrompt !== void 0 ? { systemPrompt: baseSystemPrompt } : {}
|
|
899
|
+
});
|
|
900
|
+
const startedAt = now();
|
|
901
|
+
let lastSeq = (await readTimeline(log, sessionId, { registry })).at(-1)?.seq ?? 0;
|
|
902
|
+
let turns = 0;
|
|
903
|
+
let tokensSpent = 0;
|
|
904
|
+
let toolCallsTotal = 0;
|
|
905
|
+
const append = async (drafts) => {
|
|
906
|
+
if (drafts.length === 0) return [];
|
|
907
|
+
const at = now();
|
|
908
|
+
const events = drafts.map(
|
|
909
|
+
(d, i) => createEvent(registry, { ...d, sessionId, seq: lastSeq + 1 + i, at, id: newId(at) })
|
|
910
|
+
);
|
|
911
|
+
await log.append(events);
|
|
912
|
+
lastSeq += events.length;
|
|
913
|
+
return events;
|
|
914
|
+
};
|
|
915
|
+
const pause = async (reason, interruptions) => {
|
|
916
|
+
const events = await append([{ type: "core.run_paused", actor: "system", payload: { reason } }]);
|
|
917
|
+
const pending = pendingToolCalls(await readTimeline(log, sessionId, { registry }));
|
|
918
|
+
const state = await serializeRunState({
|
|
919
|
+
sessionId,
|
|
920
|
+
lastSeq,
|
|
921
|
+
pending,
|
|
922
|
+
configHash,
|
|
923
|
+
...cfg.secret !== void 0 ? { secret: cfg.secret } : {}
|
|
924
|
+
});
|
|
925
|
+
return { events, result: { status: "paused", sessionId, lastSeq, reason, interruptions, state } };
|
|
926
|
+
};
|
|
927
|
+
const spendInto = (ctx) => (usage) => {
|
|
928
|
+
tokensSpent += usage.input + usage.output;
|
|
929
|
+
ctx.budget.tokensSpent = tokensSpent;
|
|
930
|
+
};
|
|
931
|
+
const fail = async (payload) => {
|
|
932
|
+
const events = await append([{ type: "core.error", actor: "system", payload }]);
|
|
933
|
+
const error = events[0];
|
|
934
|
+
return { events, result: { status: "error", sessionId, lastSeq, error } };
|
|
935
|
+
};
|
|
936
|
+
const ownDecisions = (cfg.decisions ?? []).filter(
|
|
937
|
+
(d) => d.sessionId === void 0 || d.sessionId === sessionId
|
|
938
|
+
);
|
|
939
|
+
const forwardedDecisions = (cfg.decisions ?? []).filter(
|
|
940
|
+
(d) => d.sessionId !== void 0 && d.sessionId !== sessionId
|
|
941
|
+
);
|
|
942
|
+
if (cfg.resume !== void 0 || ownDecisions.length > 0) {
|
|
943
|
+
const timeline = await readTimeline(log, sessionId, { registry });
|
|
944
|
+
if (cfg.resume !== void 0) {
|
|
945
|
+
await validateResume({
|
|
946
|
+
state: cfg.resume,
|
|
947
|
+
sessionId,
|
|
948
|
+
timeline,
|
|
949
|
+
configHash,
|
|
950
|
+
...cfg.secret !== void 0 ? { secret: cfg.secret } : {},
|
|
951
|
+
...cfg.allowConfigDrift !== void 0 ? { allowConfigDrift: cfg.allowConfigDrift } : {}
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
const decisions = ownDecisions;
|
|
955
|
+
const pendingIds = new Set(pendingToolCalls(timeline).map((c) => c.payload.toolCallId));
|
|
956
|
+
for (const d of decisions) {
|
|
957
|
+
if (!pendingIds.has(d.toolCallId)) {
|
|
958
|
+
throw new RunStateError("unknown_tool_call", `\u5BA1\u6279\u7ED3\u8BBA\u6307\u5411\u7684\u8C03\u7528 ${d.toolCallId} \u5E76\u4E0D\u5728\u7B49\u5F85\u4E2D`, {
|
|
959
|
+
toolCallId: d.toolCallId
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
if (cfg.resume !== void 0) {
|
|
964
|
+
const by = decisions[0]?.by;
|
|
965
|
+
yield* await append([
|
|
966
|
+
{ type: "core.run_resumed", actor: "host", payload: by !== void 0 ? { by } : {} }
|
|
967
|
+
]);
|
|
968
|
+
}
|
|
969
|
+
yield* await append(
|
|
970
|
+
decisions.map((d) => ({
|
|
971
|
+
type: "core.approval_decision",
|
|
972
|
+
actor: "host",
|
|
973
|
+
payload: {
|
|
974
|
+
toolCallId: d.toolCallId,
|
|
975
|
+
approved: d.approved,
|
|
976
|
+
by: d.by,
|
|
977
|
+
...d.reason !== void 0 ? { reason: d.reason } : {}
|
|
978
|
+
}
|
|
979
|
+
}))
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
yield* await append(
|
|
983
|
+
toolsBoundDrafts({
|
|
984
|
+
timeline: await readTimeline(log, sessionId, { registry }),
|
|
985
|
+
toolNames: baseTools.map((t) => t.name),
|
|
986
|
+
configHash,
|
|
987
|
+
announce: cfg.announceToolChanges ?? true
|
|
988
|
+
})
|
|
989
|
+
);
|
|
990
|
+
if (input !== void 0) yield* await append([withResultTrust(input, baseTools)]);
|
|
991
|
+
while (true) {
|
|
992
|
+
const turnStartedAt = now();
|
|
993
|
+
const timeline = await readTimeline(log, sessionId, { registry });
|
|
994
|
+
const lastUsage = lastBudgetUsage(timeline)?.payload.tokens;
|
|
995
|
+
const projected = project({
|
|
996
|
+
timeline,
|
|
997
|
+
budget: {
|
|
998
|
+
contextLimit: capabilities.contextWindow,
|
|
999
|
+
...cfg.projection?.reserveTokens !== void 0 ? { reserveTokens: cfg.projection.reserveTokens } : {}
|
|
1000
|
+
},
|
|
1001
|
+
registry,
|
|
1002
|
+
sessionId,
|
|
1003
|
+
now: turnStartedAt,
|
|
1004
|
+
newId,
|
|
1005
|
+
...cfg.projection?.strategies ? { strategies: cfg.projection.strategies } : {},
|
|
1006
|
+
...cfg.projection?.estimate ? { estimate: cfg.projection.estimate } : {}
|
|
1007
|
+
});
|
|
1008
|
+
if (projected.emitted.length > 0) {
|
|
1009
|
+
await log.append(projected.emitted);
|
|
1010
|
+
lastSeq += projected.emitted.length;
|
|
1011
|
+
yield* projected.emitted;
|
|
1012
|
+
}
|
|
1013
|
+
const emitted = [];
|
|
1014
|
+
const ctx = {
|
|
1015
|
+
session: { id: sessionId, turn: turns + 1 },
|
|
1016
|
+
...cfg.principal ? { principal: cfg.principal } : {},
|
|
1017
|
+
events: projected.events,
|
|
1018
|
+
timeline,
|
|
1019
|
+
log,
|
|
1020
|
+
...cfg.blobs ? { blobs: cfg.blobs } : {},
|
|
1021
|
+
...cfg.memory ? { memory: cfg.memory } : {},
|
|
1022
|
+
tools: baseTools,
|
|
1023
|
+
model,
|
|
1024
|
+
capabilities,
|
|
1025
|
+
budget: {
|
|
1026
|
+
contextLimit: capabilities.contextWindow,
|
|
1027
|
+
targetTokens: projected.stats.targetTokens,
|
|
1028
|
+
used: projected.stats.estimatedTokens,
|
|
1029
|
+
tokensSpent,
|
|
1030
|
+
turns,
|
|
1031
|
+
toolCalls: toolCallsTotal,
|
|
1032
|
+
wallMs: turnStartedAt - startedAt,
|
|
1033
|
+
...lastUsage ? { lastUsage } : {}
|
|
1034
|
+
},
|
|
1035
|
+
...cfg.signal ? { signal: cfg.signal } : {},
|
|
1036
|
+
emit: (d) => emitted.push(d)
|
|
1037
|
+
};
|
|
1038
|
+
const flush = async () => {
|
|
1039
|
+
const events = await append(emitted.splice(0));
|
|
1040
|
+
return events;
|
|
1041
|
+
};
|
|
1042
|
+
if (cfg.signal?.aborted) {
|
|
1043
|
+
const { events, result } = await pause("host", [{ kind: "host", note: "\u5BBF\u4E3B\u5728\u672C\u8F6E\u5F00\u59CB\u524D\u4E2D\u6B62" }]);
|
|
1044
|
+
yield* events;
|
|
1045
|
+
return result;
|
|
1046
|
+
}
|
|
1047
|
+
const pending = pendingToolCalls(timeline);
|
|
1048
|
+
if (pending.length > 0) {
|
|
1049
|
+
const settled = yield* executeToolCalls(ctx, pending, timeline, {
|
|
1050
|
+
cfg,
|
|
1051
|
+
sockets,
|
|
1052
|
+
append,
|
|
1053
|
+
flush,
|
|
1054
|
+
forwardedDecisions,
|
|
1055
|
+
spend: spendInto(ctx)
|
|
1056
|
+
});
|
|
1057
|
+
toolCallsTotal += settled.executed;
|
|
1058
|
+
if (settled.interruptions.length > 0) {
|
|
1059
|
+
const reason = pauseReasonOf(settled.interruptions);
|
|
1060
|
+
const { events, result } = await pause(reason, settled.interruptions);
|
|
1061
|
+
yield* events;
|
|
1062
|
+
return result;
|
|
1063
|
+
}
|
|
1064
|
+
const ended2 = yield* endTurn(ctx, "continue", flush);
|
|
1065
|
+
if (ended2) return ended2;
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
if (turns >= maxTurns) {
|
|
1069
|
+
const note = `\u5355\u6B21 run \u8F6E\u6570\u8FBE\u5230\u4E0A\u9650 ${maxTurns}`;
|
|
1070
|
+
const { events, result } = await pause("budget", [{ kind: "budget", note }]);
|
|
1071
|
+
yield* events;
|
|
1072
|
+
return result;
|
|
1073
|
+
}
|
|
1074
|
+
turns++;
|
|
1075
|
+
ctx.session.turn = turns;
|
|
1076
|
+
ctx.budget.turns = turns;
|
|
1077
|
+
let visible = ctx.events;
|
|
1078
|
+
let tools = baseTools;
|
|
1079
|
+
let systemPrompt = baseSystemPrompt;
|
|
1080
|
+
for (const s of sockets) {
|
|
1081
|
+
const patch = await s.beforeModel?.(ctx);
|
|
1082
|
+
if (!patch) continue;
|
|
1083
|
+
if (patch.events) visible = patch.events;
|
|
1084
|
+
if (patch.tools) tools = patch.tools;
|
|
1085
|
+
if (patch.systemPrompt !== void 0) systemPrompt = patch.systemPrompt;
|
|
1086
|
+
ctx.events = visible;
|
|
1087
|
+
ctx.tools = tools;
|
|
1088
|
+
}
|
|
1089
|
+
const injected = await flush();
|
|
1090
|
+
yield* injected;
|
|
1091
|
+
visible = [...visible, ...injected.filter((e) => !DEFAULT_MODEL_INVISIBLE_TYPES.has(e.type))];
|
|
1092
|
+
ctx.events = visible;
|
|
1093
|
+
ctx.tools = tools;
|
|
1094
|
+
let outcome;
|
|
1095
|
+
const modelEvents = [];
|
|
1096
|
+
for (let attempt = 1; ; attempt++) {
|
|
1097
|
+
let failure;
|
|
1098
|
+
let attemptOutput = 0;
|
|
1099
|
+
try {
|
|
1100
|
+
const request = lowering.toRequest({
|
|
1101
|
+
events: visible,
|
|
1102
|
+
tools: tools.map(toolSpecOf),
|
|
1103
|
+
model,
|
|
1104
|
+
...systemPrompt !== void 0 ? { systemPrompt } : {}
|
|
1105
|
+
});
|
|
1106
|
+
cfg.onLandings?.(lossesOf(request), request);
|
|
1107
|
+
const streamCtx = {
|
|
1108
|
+
...cfg.signal ? { signal: cfg.signal } : {},
|
|
1109
|
+
...cfg.onDelta ? { onDelta: cfg.onDelta } : {}
|
|
1110
|
+
};
|
|
1111
|
+
const stream = lowering.stream(request, streamCtx);
|
|
1112
|
+
while (true) {
|
|
1113
|
+
const step = await stream.next();
|
|
1114
|
+
if (step.done) {
|
|
1115
|
+
outcome = step.value;
|
|
1116
|
+
break;
|
|
1117
|
+
}
|
|
1118
|
+
const appended = await append([step.value]);
|
|
1119
|
+
modelEvents.push(...appended);
|
|
1120
|
+
attemptOutput += appended.length;
|
|
1121
|
+
yield* appended;
|
|
1122
|
+
}
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
failure = { kind: "thrown", error: err };
|
|
1125
|
+
}
|
|
1126
|
+
if (outcome) {
|
|
1127
|
+
tokensSpent += outcome.usage.input + outcome.usage.output;
|
|
1128
|
+
ctx.budget.tokensSpent = tokensSpent;
|
|
1129
|
+
ctx.budget.lastUsage = outcome.usage;
|
|
1130
|
+
if (outcome.stopReason === "error")
|
|
1131
|
+
failure = { kind: "outcome", message: outcome.errorMessage ?? "\u6A21\u578B\u54CD\u5E94\u51FA\u9519" };
|
|
1132
|
+
}
|
|
1133
|
+
ctx.budget.wallMs = now() - startedAt;
|
|
1134
|
+
if (!failure) break;
|
|
1135
|
+
const transient = retry.isTransient(failure);
|
|
1136
|
+
const canRetry = transient && attemptOutput === 0 && attempt < retry.maxAttempts && !cfg.signal?.aborted;
|
|
1137
|
+
const base = failure.kind === "thrown" ? {
|
|
1138
|
+
category: "lowering",
|
|
1139
|
+
message: errorMessageOf(failure.error),
|
|
1140
|
+
detail: { name: failure.error?.name ?? "Error" }
|
|
1141
|
+
} : {
|
|
1142
|
+
category: "provider",
|
|
1143
|
+
message: failure.message,
|
|
1144
|
+
detail: { usage: outcome?.usage }
|
|
1145
|
+
};
|
|
1146
|
+
if (!canRetry) {
|
|
1147
|
+
const { events, result } = await fail({
|
|
1148
|
+
...base,
|
|
1149
|
+
retryable: transient,
|
|
1150
|
+
detail: {
|
|
1151
|
+
...base.detail,
|
|
1152
|
+
attempts: attempt,
|
|
1153
|
+
...attemptOutput > 0 ? { partialOutput: attemptOutput } : {}
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
1156
|
+
yield* events;
|
|
1157
|
+
return result;
|
|
1158
|
+
}
|
|
1159
|
+
const delayMs = retry.delayFor(attempt);
|
|
1160
|
+
yield* await append([
|
|
1161
|
+
{
|
|
1162
|
+
type: "core.error",
|
|
1163
|
+
actor: "system",
|
|
1164
|
+
payload: {
|
|
1165
|
+
...base,
|
|
1166
|
+
retryable: true,
|
|
1167
|
+
detail: { ...base.detail, attempts: attempt, willRetry: true, delayMs }
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
]);
|
|
1171
|
+
outcome = void 0;
|
|
1172
|
+
await retry.sleep(delayMs, cfg.signal);
|
|
1173
|
+
if (cfg.signal?.aborted) {
|
|
1174
|
+
const { events, result } = await pause("host", [{ kind: "host", note: "\u5BBF\u4E3B\u5728\u91CD\u8BD5\u7B49\u5F85\u671F\u95F4\u4E2D\u6B62" }]);
|
|
1175
|
+
yield* events;
|
|
1176
|
+
return result;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
if (!outcome) throw new Error("runLoop \u5185\u90E8\u9519\u8BEF\uFF1A\u6A21\u578B\u8C03\u7528\u65E2\u65E0\u7ED3\u679C\u4E5F\u65E0\u5931\u8D25");
|
|
1180
|
+
for (const s of sockets) await s.afterModel?.(ctx, modelEvents);
|
|
1181
|
+
yield* await flush();
|
|
1182
|
+
if (outcome.stopReason === "aborted") {
|
|
1183
|
+
const { events, result } = await pause("host", [{ kind: "host", note: "\u5BBF\u4E3B\u4E2D\u6B62\u4E86\u6A21\u578B\u54CD\u5E94" }]);
|
|
1184
|
+
yield* events;
|
|
1185
|
+
return result;
|
|
1186
|
+
}
|
|
1187
|
+
const calls = modelEvents.filter((e) => e.type === "core.tool_call");
|
|
1188
|
+
let interruptions = [];
|
|
1189
|
+
if (calls.length > 0) {
|
|
1190
|
+
const settled = yield* executeToolCalls(ctx, calls, [...timeline, ...injected, ...modelEvents], {
|
|
1191
|
+
cfg,
|
|
1192
|
+
sockets,
|
|
1193
|
+
append,
|
|
1194
|
+
flush,
|
|
1195
|
+
forwardedDecisions,
|
|
1196
|
+
spend: spendInto(ctx)
|
|
1197
|
+
});
|
|
1198
|
+
toolCallsTotal += settled.executed;
|
|
1199
|
+
ctx.budget.toolCalls = toolCallsTotal;
|
|
1200
|
+
interruptions = settled.interruptions;
|
|
1201
|
+
}
|
|
1202
|
+
yield* await append([
|
|
1203
|
+
{
|
|
1204
|
+
type: "core.budget_usage",
|
|
1205
|
+
actor: "system",
|
|
1206
|
+
payload: {
|
|
1207
|
+
tokens: outcome.usage,
|
|
1208
|
+
toolCalls: calls.length,
|
|
1209
|
+
wallMs: now() - turnStartedAt,
|
|
1210
|
+
contextEstimate: projected.stats.estimatedTokens
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
]);
|
|
1214
|
+
if (interruptions.length > 0) {
|
|
1215
|
+
const { events, result } = await pause(pauseReasonOf(interruptions), interruptions);
|
|
1216
|
+
yield* events;
|
|
1217
|
+
return result;
|
|
1218
|
+
}
|
|
1219
|
+
const ended = yield* endTurn(ctx, calls.length > 0 ? "continue" : "stop", flush);
|
|
1220
|
+
if (ended) return ended;
|
|
1221
|
+
}
|
|
1222
|
+
async function* endTurn(ctx, fallback, flush) {
|
|
1223
|
+
let decision = fallback;
|
|
1224
|
+
for (const s of sockets) {
|
|
1225
|
+
const d = await s.onTurnEnd?.(ctx);
|
|
1226
|
+
if (d !== void 0) {
|
|
1227
|
+
decision = d;
|
|
1228
|
+
break;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
yield* await flush();
|
|
1232
|
+
if (decision === "continue") return void 0;
|
|
1233
|
+
if (decision === "stop") return { status: "done", sessionId, lastSeq };
|
|
1234
|
+
if ("pause" in decision) {
|
|
1235
|
+
const note = decision.pause.note ?? `Socket \u8981\u6C42\u6682\u505C\uFF08${decision.pause.reason}\uFF09`;
|
|
1236
|
+
const kind = decision.pause.reason;
|
|
1237
|
+
const { events, result } = await pause(kind, [{ kind, note }]);
|
|
1238
|
+
yield* events;
|
|
1239
|
+
return result;
|
|
1240
|
+
}
|
|
1241
|
+
const intent = decision.handoff;
|
|
1242
|
+
const toSessionId = intent.toSessionId ?? newId(now());
|
|
1243
|
+
yield* await append([
|
|
1244
|
+
{
|
|
1245
|
+
type: "core.handoff",
|
|
1246
|
+
actor: intent.by ?? "model",
|
|
1247
|
+
payload: {
|
|
1248
|
+
toSessionId,
|
|
1249
|
+
summary: intent.summary,
|
|
1250
|
+
reason: intent.reason,
|
|
1251
|
+
...intent.triggerMessage !== void 0 ? { triggerMessage: intent.triggerMessage } : {}
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
]);
|
|
1255
|
+
const at = now();
|
|
1256
|
+
const opening = [
|
|
1257
|
+
{ type: "core.system_note", actor: "host", payload: { kind: "host", text: intent.summary } },
|
|
1258
|
+
...intent.opening ?? []
|
|
1259
|
+
];
|
|
1260
|
+
if (intent.triggerMessage !== void 0) {
|
|
1261
|
+
opening.push({
|
|
1262
|
+
type: "core.user_message",
|
|
1263
|
+
actor: "user",
|
|
1264
|
+
payload: { content: [{ type: "text", text: intent.triggerMessage }] }
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
const openingEvents = opening.map(
|
|
1268
|
+
(d, i) => createEvent(registry, { ...d, sessionId: toSessionId, seq: i + 1, at, id: newId(at) })
|
|
1269
|
+
);
|
|
1270
|
+
await log.append(openingEvents);
|
|
1271
|
+
yield* openingEvents;
|
|
1272
|
+
await cfg.onHandoff?.(sessionId, toSessionId);
|
|
1273
|
+
return { status: "handoff", sessionId, lastSeq, toSessionId };
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
function pauseReasonOf(interruptions) {
|
|
1277
|
+
const reasons = interruptions.map(
|
|
1278
|
+
(i) => i.kind === "subagent" ? i.reason : i.kind === "client_tool" ? "host" : i.kind
|
|
1279
|
+
);
|
|
1280
|
+
if (reasons.includes("approval")) return "approval";
|
|
1281
|
+
if (reasons.includes("budget")) return "budget";
|
|
1282
|
+
return "host";
|
|
1283
|
+
}
|
|
1284
|
+
function lastBudgetUsage(timeline) {
|
|
1285
|
+
for (let i = timeline.length - 1; i >= 0; i--) {
|
|
1286
|
+
const e = timeline[i];
|
|
1287
|
+
if (e?.type === "core.budget_usage") return e;
|
|
1288
|
+
}
|
|
1289
|
+
return void 0;
|
|
1290
|
+
}
|
|
1291
|
+
function withTrust(trust) {
|
|
1292
|
+
return trust === void 0 ? {} : { trust };
|
|
1293
|
+
}
|
|
1294
|
+
function withResultTrust(input, tools) {
|
|
1295
|
+
if (input.type !== "core.tool_result" || input.trust !== void 0) return input;
|
|
1296
|
+
const payload = input.payload;
|
|
1297
|
+
const tool = tools.find((t) => t.name === payload?.name);
|
|
1298
|
+
return { ...input, ...withTrust(toolResultTrust(tool, payload?.isError === true)) };
|
|
1299
|
+
}
|
|
1300
|
+
async function* executeToolCalls(ctx, calls, timeline, deps) {
|
|
1301
|
+
const { cfg, sockets, append, flush, forwardedDecisions, spend } = deps;
|
|
1302
|
+
const decisions = /* @__PURE__ */ new Map();
|
|
1303
|
+
const requested = /* @__PURE__ */ new Set();
|
|
1304
|
+
for (const raw of timeline) {
|
|
1305
|
+
const e = raw;
|
|
1306
|
+
if (e.type === "core.approval_decision") decisions.set(e.payload.toolCallId, e.payload);
|
|
1307
|
+
if (e.type === "core.approval_request") requested.add(e.payload.toolCallId);
|
|
1308
|
+
}
|
|
1309
|
+
const summary = { executed: 0, interruptions: [] };
|
|
1310
|
+
const settle = async (draft) => [
|
|
1311
|
+
...await flush(),
|
|
1312
|
+
...await append([draft])
|
|
1313
|
+
];
|
|
1314
|
+
for (const call of calls) {
|
|
1315
|
+
const { toolCallId, name } = call.payload;
|
|
1316
|
+
const tool = ctx.tools.find((t) => t.name === name);
|
|
1317
|
+
const errorResult = (text) => ({
|
|
1318
|
+
type: "core.tool_result",
|
|
1319
|
+
actor: "tool",
|
|
1320
|
+
parentId: call.id,
|
|
1321
|
+
provenance: { source: name },
|
|
1322
|
+
payload: { toolCallId, name, content: [{ type: "text", text }], isError: true }
|
|
1323
|
+
});
|
|
1324
|
+
const decided = decisions.get(toolCallId);
|
|
1325
|
+
if (decided && !decided.approved) {
|
|
1326
|
+
yield* await append([errorResult(`\u5BA1\u6279\u88AB\u62D2\u7EDD${decided.reason ? `\uFF1A${decided.reason}` : ""}`)]);
|
|
1327
|
+
continue;
|
|
1328
|
+
}
|
|
1329
|
+
let args = call.payload.args;
|
|
1330
|
+
let seen = call;
|
|
1331
|
+
let verdict = "proceed";
|
|
1332
|
+
for (const s of sockets) {
|
|
1333
|
+
const d = await s.beforeTool?.(ctx, seen, tool);
|
|
1334
|
+
if (d === void 0 || d === "proceed") continue;
|
|
1335
|
+
if ("rewrite" in d) {
|
|
1336
|
+
args = d.rewrite;
|
|
1337
|
+
seen = { ...seen, payload: { ...seen.payload, args } };
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
if ("defer" in d && decided?.approved) continue;
|
|
1341
|
+
verdict = d;
|
|
1342
|
+
break;
|
|
1343
|
+
}
|
|
1344
|
+
if (typeof verdict === "object" && "block" in verdict) {
|
|
1345
|
+
yield* await settle(errorResult(`\u5DE5\u5177\u8C03\u7528\u88AB\u62E6\u622A\uFF1A${verdict.block}`));
|
|
1346
|
+
continue;
|
|
1347
|
+
}
|
|
1348
|
+
if (!tool) {
|
|
1349
|
+
yield* await settle(errorResult(`\u672A\u77E5\u5DE5\u5177\uFF1A${name}`));
|
|
1350
|
+
continue;
|
|
1351
|
+
}
|
|
1352
|
+
try {
|
|
1353
|
+
if (tool.validate) args = tool.validate(args);
|
|
1354
|
+
} catch (err) {
|
|
1355
|
+
yield* await settle(errorResult(`\u5165\u53C2\u4E0D\u5408\u6CD5\uFF1A${errorMessageOf(err)}`));
|
|
1356
|
+
continue;
|
|
1357
|
+
}
|
|
1358
|
+
const toolCtx = {
|
|
1359
|
+
sessionId: ctx.session.id,
|
|
1360
|
+
toolCallId,
|
|
1361
|
+
...ctx.principal ? { principal: ctx.principal } : {},
|
|
1362
|
+
log: ctx.log,
|
|
1363
|
+
...ctx.blobs ? { blobs: ctx.blobs } : {},
|
|
1364
|
+
...ctx.memory ? { memory: ctx.memory } : {},
|
|
1365
|
+
...ctx.signal ? { signal: ctx.signal } : {},
|
|
1366
|
+
emit: ctx.emit,
|
|
1367
|
+
...forwardedDecisions.length > 0 ? { decisions: forwardedDecisions } : {},
|
|
1368
|
+
spend
|
|
1369
|
+
};
|
|
1370
|
+
let approval = typeof verdict === "object" && "defer" in verdict ? verdict.defer : void 0;
|
|
1371
|
+
if (!approval && !decided?.approved && tool.needsApproval !== void 0) {
|
|
1372
|
+
const need = typeof tool.needsApproval === "function" ? await tool.needsApproval(args, toolCtx) : tool.needsApproval;
|
|
1373
|
+
if (need) {
|
|
1374
|
+
approval = { policyId: BUILTIN_APPROVAL_POLICY, summary: `${name}(${JSON.stringify(args) ?? ""})` };
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
if (approval && !decided?.approved) {
|
|
1378
|
+
const request = { toolCallId, policyId: approval.policyId, summary: approval.summary };
|
|
1379
|
+
if (!requested.has(toolCallId)) {
|
|
1380
|
+
yield* await settle({
|
|
1381
|
+
type: "core.approval_request",
|
|
1382
|
+
actor: "system",
|
|
1383
|
+
parentId: call.id,
|
|
1384
|
+
payload: request
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
summary.interruptions.push({ kind: "approval", toolCallId, request, call: call.payload });
|
|
1388
|
+
continue;
|
|
1389
|
+
}
|
|
1390
|
+
if (!tool.execute || tool.side === "client") {
|
|
1391
|
+
summary.interruptions.push({ kind: "client_tool", toolCallId, call: call.payload });
|
|
1392
|
+
continue;
|
|
1393
|
+
}
|
|
1394
|
+
let result;
|
|
1395
|
+
try {
|
|
1396
|
+
summary.executed++;
|
|
1397
|
+
const out = await tool.execute(args, toolCtx);
|
|
1398
|
+
if (isSubagentPause(out)) {
|
|
1399
|
+
summary.interruptions.push({ kind: "subagent", toolCallId, call: call.payload, ...out.detail });
|
|
1400
|
+
if (cfg.signal?.aborted) break;
|
|
1401
|
+
continue;
|
|
1402
|
+
}
|
|
1403
|
+
const normalized = tool.toModelOutput ? { content: tool.toModelOutput(out) } : normalizeToolOutput(out);
|
|
1404
|
+
result = {
|
|
1405
|
+
type: "core.tool_result",
|
|
1406
|
+
actor: "tool",
|
|
1407
|
+
parentId: call.id,
|
|
1408
|
+
provenance: { source: name },
|
|
1409
|
+
// 工具声明的结果 trust(如 skill_read 的 system)只用于成功结果;isError 结果与执行抛错仍是缺省 untrusted
|
|
1410
|
+
...withTrust(toolResultTrust(tool, normalized.isError ?? false)),
|
|
1411
|
+
payload: { toolCallId, name, content: normalized.content, isError: normalized.isError ?? false }
|
|
1412
|
+
};
|
|
1413
|
+
} catch (err) {
|
|
1414
|
+
result = errorResult(`\u5DE5\u5177\u6267\u884C\u5931\u8D25\uFF1A${errorMessageOf(err)}`);
|
|
1415
|
+
}
|
|
1416
|
+
for (const s of sockets) {
|
|
1417
|
+
const replaced = await s.afterTool?.(ctx, call, result);
|
|
1418
|
+
if (replaced) result = replaced;
|
|
1419
|
+
}
|
|
1420
|
+
yield* await settle(result);
|
|
1421
|
+
if (cfg.signal?.aborted) break;
|
|
1422
|
+
}
|
|
1423
|
+
return summary;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// src/lowering/trust.ts
|
|
1427
|
+
var UNTRUSTED_TAG = "untrusted";
|
|
1428
|
+
function untrustedSourceOf(e) {
|
|
1429
|
+
if (e.type === "core.tool_result") {
|
|
1430
|
+
const name = e.payload?.name;
|
|
1431
|
+
if (typeof name === "string" && name !== "") return `tool:${name}`;
|
|
1432
|
+
}
|
|
1433
|
+
if (e.provenance?.source) return e.provenance.source;
|
|
1434
|
+
return e.actor;
|
|
1435
|
+
}
|
|
1436
|
+
var CLOSE_TAG = new RegExp(`</${UNTRUSTED_TAG}`, "gi");
|
|
1437
|
+
function escapeUntrustedText(text) {
|
|
1438
|
+
let escaped = false;
|
|
1439
|
+
const out = text.replace(CLOSE_TAG, (m) => {
|
|
1440
|
+
escaped = true;
|
|
1441
|
+
return `<\\/${m.slice(2)}`;
|
|
1442
|
+
});
|
|
1443
|
+
return { text: out, escaped };
|
|
1444
|
+
}
|
|
1445
|
+
function untrustedOpenTag(source) {
|
|
1446
|
+
return `<${UNTRUSTED_TAG} source="${source.replace(/"/g, """)}">`;
|
|
1447
|
+
}
|
|
1448
|
+
var UNTRUSTED_CLOSE_TAG = `</${UNTRUSTED_TAG}>`;
|
|
1449
|
+
function markUntrustedText(text, source) {
|
|
1450
|
+
const e = escapeUntrustedText(text);
|
|
1451
|
+
return { text: `${untrustedOpenTag(source)}
|
|
1452
|
+
${e.text}
|
|
1453
|
+
${UNTRUSTED_CLOSE_TAG}`, escaped: e.escaped };
|
|
1454
|
+
}
|
|
1455
|
+
function markUntrusted(parts, source) {
|
|
1456
|
+
let escaped = false;
|
|
1457
|
+
const body = parts.map((p) => {
|
|
1458
|
+
if (p.type !== "text") return p;
|
|
1459
|
+
const e = escapeUntrustedText(p.text);
|
|
1460
|
+
escaped = escaped || e.escaped;
|
|
1461
|
+
return { type: "text", text: e.text };
|
|
1462
|
+
});
|
|
1463
|
+
const open = untrustedOpenTag(source);
|
|
1464
|
+
const first = body[0];
|
|
1465
|
+
if (first?.type === "text") body[0] = { type: "text", text: `${open}
|
|
1466
|
+
${first.text}` };
|
|
1467
|
+
else body.unshift({ type: "text", text: open });
|
|
1468
|
+
const last = body[body.length - 1];
|
|
1469
|
+
if (last?.type === "text" && body.length > (first?.type === "text" ? 0 : 1)) {
|
|
1470
|
+
body[body.length - 1] = { type: "text", text: `${last.text}
|
|
1471
|
+
${UNTRUSTED_CLOSE_TAG}` };
|
|
1472
|
+
} else body.push({ type: "text", text: UNTRUSTED_CLOSE_TAG });
|
|
1473
|
+
return { parts: body, escaped };
|
|
1474
|
+
}
|
|
1475
|
+
function needsUntrustedMark(e) {
|
|
1476
|
+
return e.trust === "untrusted";
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
// src/replay/replay.ts
|
|
1480
|
+
var MODEL_OUTPUT_TYPES = /* @__PURE__ */ new Set([
|
|
1481
|
+
"core.model_thinking",
|
|
1482
|
+
"core.model_text",
|
|
1483
|
+
"core.tool_call"
|
|
1484
|
+
]);
|
|
1485
|
+
function isModelOutput(e) {
|
|
1486
|
+
return MODEL_OUTPUT_TYPES.has(e.type);
|
|
1487
|
+
}
|
|
1488
|
+
function replayTurns(timeline, opts) {
|
|
1489
|
+
const sessionId = timeline[0]?.sessionId;
|
|
1490
|
+
const turns = [];
|
|
1491
|
+
const preamble = [];
|
|
1492
|
+
let i = 0;
|
|
1493
|
+
while (i < timeline.length && !isModelOutput(timeline[i])) preamble.push(timeline[i++]);
|
|
1494
|
+
while (i < timeline.length) {
|
|
1495
|
+
const first = timeline[i];
|
|
1496
|
+
const requestAtSeq = first.seq - 1;
|
|
1497
|
+
const output = [];
|
|
1498
|
+
while (i < timeline.length && isModelOutput(timeline[i])) output.push(timeline[i++]);
|
|
1499
|
+
const aftermath = [];
|
|
1500
|
+
while (i < timeline.length && !isModelOutput(timeline[i])) aftermath.push(timeline[i++]);
|
|
1501
|
+
const prefix = timeline.slice(0, requestAtSeq);
|
|
1502
|
+
const projected = project({
|
|
1503
|
+
timeline: prefix,
|
|
1504
|
+
budget: opts.budget,
|
|
1505
|
+
// 回放不该产生新 id,也不依赖当前时间;给确定值让输出可比对
|
|
1506
|
+
now: first.at,
|
|
1507
|
+
newId: (at) => `replay-${at}-${requestAtSeq}`,
|
|
1508
|
+
...sessionId !== void 0 ? { sessionId } : {},
|
|
1509
|
+
...opts.strategies ? { strategies: opts.strategies } : {},
|
|
1510
|
+
...opts.estimate ? { estimate: opts.estimate } : {},
|
|
1511
|
+
...opts.registry ? { registry: opts.registry } : {}
|
|
1512
|
+
});
|
|
1513
|
+
const usage = aftermath.find(
|
|
1514
|
+
(e) => e.type === "core.budget_usage"
|
|
1515
|
+
)?.payload;
|
|
1516
|
+
turns.push({
|
|
1517
|
+
index: turns.length + 1,
|
|
1518
|
+
requestAtSeq,
|
|
1519
|
+
visible: projected.events,
|
|
1520
|
+
stats: projected.stats,
|
|
1521
|
+
diverged: projected.emitted.length > 0,
|
|
1522
|
+
output,
|
|
1523
|
+
aftermath,
|
|
1524
|
+
...usage ? { usage } : {}
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
return { turns, preamble };
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
// src/store/errors.ts
|
|
1531
|
+
var StoreError = class extends Error {
|
|
1532
|
+
constructor(code, message, context = {}) {
|
|
1533
|
+
super(`[${code}] ${message}`);
|
|
1534
|
+
this.code = code;
|
|
1535
|
+
this.context = context;
|
|
1536
|
+
this.name = "StoreError";
|
|
1537
|
+
}
|
|
1538
|
+
code;
|
|
1539
|
+
context;
|
|
1540
|
+
};
|
|
1541
|
+
|
|
1542
|
+
// src/store/in-memory.ts
|
|
1543
|
+
var InMemoryEventLog = class {
|
|
1544
|
+
sessions = /* @__PURE__ */ new Map();
|
|
1545
|
+
async append(events) {
|
|
1546
|
+
if (events.length === 0) throw new StoreError("empty_batch", "append \u7684\u4E8B\u4EF6\u6570\u7EC4\u4E3A\u7A7A");
|
|
1547
|
+
const sessionId = events[0].sessionId;
|
|
1548
|
+
const existing = this.sessions.get(sessionId) ?? [];
|
|
1549
|
+
let expected = existing.length + 1;
|
|
1550
|
+
for (const e of events) {
|
|
1551
|
+
if (e.sessionId !== sessionId) {
|
|
1552
|
+
throw new StoreError("session_mismatch", "\u540C\u4E00\u6279 append \u5FC5\u987B\u5C5E\u4E8E\u540C\u4E00\u4E2A\u4F1A\u8BDD", {
|
|
1553
|
+
expected: sessionId,
|
|
1554
|
+
got: e.sessionId
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
if (e.seq !== expected) {
|
|
1558
|
+
throw new StoreError("seq_conflict", `\u4F1A\u8BDD ${sessionId} \u671F\u671B seq=${expected}\uFF0C\u6536\u5230 ${e.seq}`, {
|
|
1559
|
+
sessionId,
|
|
1560
|
+
expected,
|
|
1561
|
+
got: e.seq
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
expected++;
|
|
1565
|
+
}
|
|
1566
|
+
const copy = existing.slice();
|
|
1567
|
+
for (const e of events) copy.push(structuredClone(e));
|
|
1568
|
+
this.sessions.set(sessionId, copy);
|
|
1569
|
+
}
|
|
1570
|
+
async *read(sessionId, opts = {}) {
|
|
1571
|
+
const events = this.sessions.get(sessionId) ?? [];
|
|
1572
|
+
const from = opts.fromSeq ?? 1;
|
|
1573
|
+
const to = opts.toSeq ?? Number.POSITIVE_INFINITY;
|
|
1574
|
+
for (let i = Math.max(from, 1) - 1; i < events.length && i + 1 <= to; i++) {
|
|
1575
|
+
yield structuredClone(events[i]);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
async tail(sessionId, n) {
|
|
1579
|
+
if (!Number.isInteger(n) || n < 0)
|
|
1580
|
+
throw new StoreError("invalid_argument", `tail \u7684 n \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570\uFF1A${n}`);
|
|
1581
|
+
const events = this.sessions.get(sessionId) ?? [];
|
|
1582
|
+
return events.slice(Math.max(0, events.length - n)).map((e) => structuredClone(e));
|
|
1583
|
+
}
|
|
1584
|
+
async fork(fromSessionId, atSeq, toSessionId) {
|
|
1585
|
+
const source = this.sessions.get(fromSessionId) ?? [];
|
|
1586
|
+
if (!Number.isInteger(atSeq) || atSeq < 1 || atSeq > source.length) {
|
|
1587
|
+
throw new StoreError(
|
|
1588
|
+
"out_of_range",
|
|
1589
|
+
`fork \u70B9 ${atSeq} \u8D85\u51FA\u4F1A\u8BDD ${fromSessionId} \u7684\u8303\u56F4 [1, ${source.length}]`,
|
|
1590
|
+
{
|
|
1591
|
+
fromSessionId,
|
|
1592
|
+
atSeq,
|
|
1593
|
+
lastSeq: source.length
|
|
1594
|
+
}
|
|
1595
|
+
);
|
|
1596
|
+
}
|
|
1597
|
+
if ((this.sessions.get(toSessionId)?.length ?? 0) > 0) {
|
|
1598
|
+
throw new StoreError("target_not_empty", `\u76EE\u6807\u4F1A\u8BDD ${toSessionId} \u5DF2\u6709\u4E8B\u4EF6`, { toSessionId });
|
|
1599
|
+
}
|
|
1600
|
+
this.sessions.set(
|
|
1601
|
+
toSessionId,
|
|
1602
|
+
source.slice(0, atSeq).map((e) => ({ ...structuredClone(e), sessionId: toSessionId }))
|
|
1603
|
+
);
|
|
1604
|
+
}
|
|
1605
|
+
};
|
|
1606
|
+
var InMemoryBlobStore = class {
|
|
1607
|
+
blobs = /* @__PURE__ */ new Map();
|
|
1608
|
+
async put(bytes, meta) {
|
|
1609
|
+
const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes.slice();
|
|
1610
|
+
const id = uuidv7();
|
|
1611
|
+
this.blobs.set(id, {
|
|
1612
|
+
bytes: data,
|
|
1613
|
+
meta: { mime: meta.mime, sessionId: meta.sessionId, size: data.byteLength, createdAt: Date.now() }
|
|
1614
|
+
});
|
|
1615
|
+
return { id };
|
|
1616
|
+
}
|
|
1617
|
+
async get(id) {
|
|
1618
|
+
const hit = this.blobs.get(id);
|
|
1619
|
+
if (!hit) throw new StoreError("not_found", `blob \u4E0D\u5B58\u5728\uFF1A${id}`, { id });
|
|
1620
|
+
return { bytes: hit.bytes.slice(), meta: { ...hit.meta } };
|
|
1621
|
+
}
|
|
1622
|
+
async slice(id, range) {
|
|
1623
|
+
const { bytes } = await this.get(id);
|
|
1624
|
+
return bytes.slice(Math.max(0, range.start), Math.min(bytes.byteLength, range.end));
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
var InMemoryMemoryStore = class {
|
|
1628
|
+
files = /* @__PURE__ */ new Map();
|
|
1629
|
+
async list(prefix) {
|
|
1630
|
+
return [...this.files.keys()].filter((p) => p.startsWith(prefix)).sort();
|
|
1631
|
+
}
|
|
1632
|
+
async read(path) {
|
|
1633
|
+
return this.files.get(path) ?? null;
|
|
1634
|
+
}
|
|
1635
|
+
async write(path, content) {
|
|
1636
|
+
this.files.set(path, content);
|
|
1637
|
+
}
|
|
1638
|
+
async delete(path) {
|
|
1639
|
+
this.files.delete(path);
|
|
1640
|
+
}
|
|
1641
|
+
};
|
|
1642
|
+
function memoryStore() {
|
|
1643
|
+
return { log: new InMemoryEventLog(), blobs: new InMemoryBlobStore(), memory: new InMemoryMemoryStore() };
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
// src/index.ts
|
|
1647
|
+
var REINS_VERSION = "0.1.0";
|
|
1648
|
+
export {
|
|
1649
|
+
BUILTIN_APPROVAL_POLICY,
|
|
1650
|
+
CORE_SCHEMAS,
|
|
1651
|
+
DEFAULT_MAX_TURNS,
|
|
1652
|
+
DEFAULT_MODEL_INVISIBLE_TYPES,
|
|
1653
|
+
DEFAULT_RESERVE_RATIO,
|
|
1654
|
+
DEFAULT_RETRY_BASE_DELAY_MS,
|
|
1655
|
+
DEFAULT_RETRY_MAX_ATTEMPTS,
|
|
1656
|
+
DEFAULT_RETRY_MAX_DELAY_MS,
|
|
1657
|
+
DEFAULT_TRUST,
|
|
1658
|
+
EventSchemaRegistry,
|
|
1659
|
+
INPUT_DRAFT_TYPES,
|
|
1660
|
+
InMemoryBlobStore,
|
|
1661
|
+
InMemoryEventLog,
|
|
1662
|
+
InMemoryMemoryStore,
|
|
1663
|
+
LoweringError,
|
|
1664
|
+
REINS_VERSION,
|
|
1665
|
+
RunStateError,
|
|
1666
|
+
SchemaError,
|
|
1667
|
+
StoreError,
|
|
1668
|
+
UNTRUSTED_CLOSE_TAG,
|
|
1669
|
+
UNTRUSTED_TAG,
|
|
1670
|
+
assertRunStateShape,
|
|
1671
|
+
backoffDelayMs,
|
|
1672
|
+
budgetTruncate,
|
|
1673
|
+
computeConfigHash,
|
|
1674
|
+
computePendingDigest,
|
|
1675
|
+
contextTokensOf,
|
|
1676
|
+
covers,
|
|
1677
|
+
createCoreEvent,
|
|
1678
|
+
createCoreRegistry,
|
|
1679
|
+
createEvent,
|
|
1680
|
+
defaultProjectionChain,
|
|
1681
|
+
defaultSleep,
|
|
1682
|
+
defaultThresholdSummary,
|
|
1683
|
+
defineTool,
|
|
1684
|
+
diffToolNames,
|
|
1685
|
+
digestArgs,
|
|
1686
|
+
errorMessageOf,
|
|
1687
|
+
escapeUntrustedText,
|
|
1688
|
+
estimateTextTokens,
|
|
1689
|
+
estimateTotal,
|
|
1690
|
+
foldCompactions,
|
|
1691
|
+
foldedToolResults,
|
|
1692
|
+
forkSession,
|
|
1693
|
+
inputDraft,
|
|
1694
|
+
isCompaction,
|
|
1695
|
+
isModelOutput,
|
|
1696
|
+
isPinNote,
|
|
1697
|
+
isSubagentPause,
|
|
1698
|
+
isTransientFailure,
|
|
1699
|
+
keptBy,
|
|
1700
|
+
lastToolsBound,
|
|
1701
|
+
lossesOf,
|
|
1702
|
+
markUntrusted,
|
|
1703
|
+
markUntrustedText,
|
|
1704
|
+
memoryStore,
|
|
1705
|
+
needsUntrustedMark,
|
|
1706
|
+
normalizeToolOutput,
|
|
1707
|
+
pendingToolCalls,
|
|
1708
|
+
project,
|
|
1709
|
+
readEvents,
|
|
1710
|
+
readTimeline,
|
|
1711
|
+
reinjectPins,
|
|
1712
|
+
renderFoldedToolResults,
|
|
1713
|
+
renderToolChangeNote,
|
|
1714
|
+
replayTurns,
|
|
1715
|
+
resolveRetry,
|
|
1716
|
+
resolveSocketContributions,
|
|
1717
|
+
roughTokenEstimate,
|
|
1718
|
+
runLoop,
|
|
1719
|
+
serializeRunState,
|
|
1720
|
+
signRunState,
|
|
1721
|
+
splitTurns,
|
|
1722
|
+
statusFromMessage,
|
|
1723
|
+
subagentPause,
|
|
1724
|
+
supersededIds,
|
|
1725
|
+
toolResultTrust,
|
|
1726
|
+
toolSpecOf,
|
|
1727
|
+
toolsBoundDrafts,
|
|
1728
|
+
untrustedOpenTag,
|
|
1729
|
+
untrustedSourceOf,
|
|
1730
|
+
uuidv7,
|
|
1731
|
+
validateResume,
|
|
1732
|
+
verifyRunState,
|
|
1733
|
+
visibilityFilter
|
|
1734
|
+
};
|
|
1735
|
+
//# sourceMappingURL=index.js.map
|