@reinsjs/brain 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/dist/index.js ADDED
@@ -0,0 +1,2517 @@
1
+ import {
2
+ DEFAULT_SKILLS_ROOT,
3
+ SKILL_FILE_NAME,
4
+ SKILL_NAME_RE
5
+ } from "./chunk-5O2TB7FV.js";
6
+
7
+ // src/approval/approval.ts
8
+ import {
9
+ BUILTIN_APPROVAL_POLICY
10
+ } from "@reinsjs/core";
11
+
12
+ // src/approval/rules.ts
13
+ var APPROVAL_RULES = `Tool permissions:
14
+ - Some tool calls require human approval before they run. When that happens the run pauses until a person decides; this is normal, not an error. Do not repeat the call while it is waiting.
15
+ - A call may be denied by policy. A denied call returns an error naming the policy; do not retry it with the same or a disguised input. Explain what you were trying to do and ask the user how to proceed.`;
16
+
17
+ // src/approval/approval.ts
18
+ var APPROVAL_SOCKET_NAME = "approval";
19
+ var DEFAULT_MAX_SUMMARY_CHARS = 200;
20
+ var APPROVAL_POLICY_IDS = {
21
+ /** 模型调了工具表里没有的工具 */
22
+ unknownTool: "approval.unknown_tool",
23
+ /** 三段都没命中、unmatched="deny" */
24
+ unmatched: "approval.unmatched",
25
+ /** 三段都没命中、按 risk 兜底:`approval.risk.<low|medium|high|undeclared>` */
26
+ risk: (level) => `approval.risk.${level ?? "undeclared"}`,
27
+ /** 入参没过工具自己的 validate:不问人、放行给循环以"入参不合法"拒掉(执行不会发生) */
28
+ invalidArgs: "approval.invalid_args"
29
+ };
30
+ function validatedCall(call) {
31
+ const tool = call.tool;
32
+ if (!tool?.validate) return call;
33
+ try {
34
+ return { ...call, args: tool.validate(call.args) };
35
+ } catch {
36
+ return void 0;
37
+ }
38
+ }
39
+ function globToRegExp(pattern) {
40
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
41
+ return new RegExp(`^${escaped}$`);
42
+ }
43
+ function normalizeRule(spec) {
44
+ if (typeof spec !== "string") return spec;
45
+ const re = globToRegExp(spec);
46
+ return { id: `name:${spec}`, match: (call) => re.test(call.name) };
47
+ }
48
+ function defaultSummary(call, maxChars) {
49
+ const json = JSON.stringify(call.args) ?? "";
50
+ const clipped = json.length > maxChars ? `${json.slice(0, maxChars)}\u2026` : json;
51
+ return `${call.name}(${clipped})`;
52
+ }
53
+ async function evaluatePolicy(call, ctx, stages, opts) {
54
+ const summaryOf = (rule) => rule?.summary ? rule.summary(call) : defaultSummary(call, opts.maxSummaryChars);
55
+ const denyBy = (rule) => ({
56
+ verdict: "deny",
57
+ policyId: rule.id,
58
+ reason: rule.reason ?? `\u7B56\u7565 ${rule.id} \u4E0D\u5141\u8BB8\u8C03\u7528 ${call.name}`
59
+ });
60
+ const failClosed = (rule, err) => {
61
+ opts.onError?.(rule, err);
62
+ return {
63
+ verdict: "deny",
64
+ policyId: rule,
65
+ reason: `\u7B56\u7565 ${rule} \u6C42\u503C\u5F02\u5E38\uFF0C\u6309\u62D2\u7EDD\u5904\u7406\uFF1A${err instanceof Error ? err.message : String(err)}`
66
+ };
67
+ };
68
+ if (!call.tool) {
69
+ return { verdict: "deny", policyId: APPROVAL_POLICY_IDS.unknownTool, reason: `\u672A\u77E5\u5DE5\u5177\uFF1A${call.name}` };
70
+ }
71
+ const tool = call.tool;
72
+ const validated = validatedCall(call);
73
+ if (!validated) return { verdict: "allow", policyId: APPROVAL_POLICY_IDS.invalidArgs };
74
+ call = validated;
75
+ const firstMatch = async (rules) => {
76
+ for (const rule of rules) {
77
+ try {
78
+ if (await rule.match(call, ctx)) return rule;
79
+ } catch (err) {
80
+ return failClosed(rule.id, err);
81
+ }
82
+ }
83
+ return void 0;
84
+ };
85
+ const isOutcome = (x) => x !== void 0 && "verdict" in x;
86
+ const denied = await firstMatch(stages.deny);
87
+ if (isOutcome(denied)) return denied;
88
+ if (denied) return denyBy(denied);
89
+ const asked = await firstMatch(stages.ask);
90
+ if (isOutcome(asked)) return asked;
91
+ if (asked) return { verdict: "ask", policyId: asked.id, summary: summaryOf(asked) };
92
+ if (tool.needsApproval !== void 0) {
93
+ try {
94
+ const need = typeof tool.needsApproval === "function" ? await tool.needsApproval(call.args, toolContextOf(call, ctx)) : tool.needsApproval;
95
+ if (need) return { verdict: "ask", policyId: BUILTIN_APPROVAL_POLICY, summary: summaryOf(void 0) };
96
+ } catch (err) {
97
+ return failClosed(BUILTIN_APPROVAL_POLICY, err);
98
+ }
99
+ }
100
+ const allowed = await firstMatch(stages.allow);
101
+ if (isOutcome(allowed)) return allowed;
102
+ if (allowed) return { verdict: "allow", policyId: allowed.id };
103
+ switch (opts.unmatched) {
104
+ case "deny":
105
+ return {
106
+ verdict: "deny",
107
+ policyId: APPROVAL_POLICY_IDS.unmatched,
108
+ reason: `\u6CA1\u6709\u7B56\u7565\u5141\u8BB8\u8C03\u7528 ${call.name}`
109
+ };
110
+ case "ask":
111
+ return { verdict: "ask", policyId: APPROVAL_POLICY_IDS.unmatched, summary: summaryOf(void 0) };
112
+ default: {
113
+ const level = tool.risk;
114
+ const policyId = APPROVAL_POLICY_IDS.risk(level);
115
+ return level === "low" ? { verdict: "allow", policyId } : { verdict: "ask", policyId, summary: summaryOf(void 0) };
116
+ }
117
+ }
118
+ }
119
+ function toolContextOf(call, ctx) {
120
+ return {
121
+ sessionId: ctx.session.id,
122
+ toolCallId: call.toolCallId,
123
+ ...ctx.principal ? { principal: ctx.principal } : {},
124
+ log: ctx.log,
125
+ ...ctx.blobs ? { blobs: ctx.blobs } : {},
126
+ ...ctx.memory ? { memory: ctx.memory } : {},
127
+ ...ctx.signal ? { signal: ctx.signal } : {},
128
+ emit: ctx.emit
129
+ };
130
+ }
131
+ function approval(options = {}) {
132
+ const stages = {
133
+ deny: (options.deny ?? []).map(normalizeRule),
134
+ ask: (options.ask ?? []).map(normalizeRule),
135
+ allow: (options.allow ?? []).map(normalizeRule)
136
+ };
137
+ const unmatched = options.unmatched ?? "byRisk";
138
+ const maxSummaryChars = options.maxSummaryChars ?? DEFAULT_MAX_SUMMARY_CHARS;
139
+ const warn = options.warn ?? ((message) => console.warn(message));
140
+ const rules = options.rules === void 0 ? APPROVAL_RULES : options.rules;
141
+ return {
142
+ name: APPROVAL_SOCKET_NAME,
143
+ ...rules === false ? {} : { systemPrompt: rules },
144
+ async beforeTool(ctx, call, tool) {
145
+ const { toolCallId, name, args } = call.payload;
146
+ const outcome = await evaluatePolicy({ toolCallId, name, args, tool }, ctx, stages, {
147
+ unmatched,
148
+ maxSummaryChars,
149
+ onError: (rule, err) => warn(
150
+ `[reins/approval] \u7B56\u7565 ${rule} \u6C42\u503C\u5F02\u5E38\uFF0C\u5DF2\u6309\u62D2\u7EDD\u5904\u7406\uFF08${name}\uFF09\uFF1A${err instanceof Error ? err.message : String(err)}`
151
+ )
152
+ });
153
+ switch (outcome.verdict) {
154
+ case "allow":
155
+ return "proceed";
156
+ case "ask":
157
+ return { defer: { policyId: outcome.policyId, summary: outcome.summary } };
158
+ case "deny":
159
+ ctx.emit({
160
+ type: "core.approval_decision",
161
+ actor: "system",
162
+ parentId: call.id,
163
+ payload: { toolCallId, approved: false, by: outcome.policyId, reason: outcome.reason }
164
+ });
165
+ return { block: outcome.reason };
166
+ }
167
+ }
168
+ };
169
+ }
170
+
171
+ // src/budget/budget.ts
172
+ import { contextTokensOf } from "@reinsjs/core";
173
+ var BUDGET_SOCKET_NAME = "budget";
174
+ function assertLimits(limits) {
175
+ for (const [dimension, limit] of Object.entries(limits)) {
176
+ if (limit === void 0) continue;
177
+ if (typeof limit !== "number" || !Number.isFinite(limit) || limit <= 0) {
178
+ throw new RangeError(`budget.limits.${dimension} \u5FC5\u987B\u662F\u6B63\u7684\u6709\u9650\u6570\uFF1A${String(limit)}`);
179
+ }
180
+ }
181
+ }
182
+ function budgetUsedOf(budget2) {
183
+ return {
184
+ contextTokens: budget2.lastUsage ? contextTokensOf(budget2.lastUsage) : void 0,
185
+ totalTokens: budget2.tokensSpent,
186
+ turns: budget2.turns,
187
+ toolCalls: budget2.toolCalls,
188
+ wallMs: budget2.wallMs
189
+ };
190
+ }
191
+ function checkBudget(budget2, limits) {
192
+ const used = budgetUsedOf(budget2);
193
+ const hits = [];
194
+ for (const dimension of Object.keys(used)) {
195
+ const limit = limits[dimension];
196
+ const value = used[dimension];
197
+ if (limit === void 0 || value === void 0) continue;
198
+ if (value >= limit) hits.push({ dimension, used: value, limit });
199
+ }
200
+ return hits;
201
+ }
202
+ function defaultBudgetNote(hits) {
203
+ const parts = hits.map((h) => `${h.dimension} ${h.used}/${h.limit}`);
204
+ return `Run budget reached: ${parts.join(", ")}. Paused for the host to decide whether to grant more; resuming the session starts a fresh run budget.`;
205
+ }
206
+ function budget(opts) {
207
+ assertLimits(opts.limits);
208
+ const note = opts.note ?? defaultBudgetNote;
209
+ const continuing = /* @__PURE__ */ new WeakMap();
210
+ return {
211
+ name: BUDGET_SOCKET_NAME,
212
+ afterModel(ctx, events) {
213
+ continuing.set(
214
+ ctx,
215
+ events.some((e) => e.type === "core.tool_call")
216
+ );
217
+ },
218
+ onTurnEnd(ctx) {
219
+ if (!continuing.get(ctx)) return void 0;
220
+ const hits = checkBudget(ctx.budget, opts.limits);
221
+ if (hits.length === 0) return void 0;
222
+ return { pause: { reason: "budget", note: note(hits) } };
223
+ }
224
+ };
225
+ }
226
+
227
+ // src/compact/compact.ts
228
+ import {
229
+ isCompaction as isCompaction2
230
+ } from "@reinsjs/core";
231
+
232
+ // src/compact/plan.ts
233
+ import {
234
+ foldedToolResults,
235
+ isCompaction,
236
+ isPinNote,
237
+ renderFoldedToolResults,
238
+ splitTurns,
239
+ supersededIds
240
+ } from "@reinsjs/core";
241
+
242
+ // src/pins/rules.ts
243
+ var PIN_TOOL_NAME = "pin";
244
+ function pinToolDescription(maxTextLength) {
245
+ return [
246
+ "Pin a short note so it survives compaction verbatim and is shown again right after every summary.",
247
+ "Use it for the user's explicit constraints, the goal as stated, and identifiers or numbers you will need after folding.",
248
+ `A note is at most ${maxTextLength} characters: split a long list across several notes, or leave it to your compact summary.`,
249
+ "Pins are permanent until replaced: to update one, pass the exact text of the old note in `replaces`.",
250
+ "Notes pinned by the host cannot be replaced."
251
+ ].join(" ");
252
+ }
253
+ var PIN_TOOL_DESCRIPTION = pinToolDescription(500);
254
+ var PIN_RULES = `## Pinned notes
255
+ Notes marked kind="pin" survive compaction verbatim and reappear right after each summary, so the pins are what you can rely on after folding. You have a \`${PIN_TOOL_NAME}\` tool to add one.
256
+ - Pin what must not drift: the user's explicit constraints, the goal in the user's words, identifiers and numbers you will need later. One or two sentences each.
257
+ - Do not pin what you can re-derive, large content, or the current step. Every pin costs context on every turn until it is replaced.
258
+ - When a pinned fact changes, pin the new version with \`replaces\` set to the old note's exact text instead of adding a second note. Notes pinned by the host are the host's constraints and cannot be replaced.
259
+ - Before compacting, check the pins still say what you need; whatever is not pinned or in your summary is only reachable by recalling the folded tool result it came from.`;
260
+
261
+ // src/spill/rules.ts
262
+ var FETCH_BLOB_TOOL_NAME = "fetch_blob";
263
+ var FETCH_BLOB_TOOL_DESCRIPTION = [
264
+ "Read a slice of a stored tool output (a blob) by character offsets.",
265
+ "When a tool's output is too large to show inline, the result you see is a preview (first and last lines) plus a blob id;",
266
+ "the complete output is kept verbatim in the blob.",
267
+ "Pass `start` and `end` (0-based character offsets, end exclusive) to read a range; omit them to read from the beginning.",
268
+ "Each call returns at most the same amount that fits inline; the header tells you where to continue."
269
+ ].join(" ");
270
+ var SPILL_RULES = `## Large tool outputs
271
+ When a tool returns more than fits inline, you see a preview (the first and last lines) and a blob id instead of the full output; nothing is lost, the complete output is stored verbatim. You have a \`${FETCH_BLOB_TOOL_NAME}\` tool to read it by character offsets.
272
+ - Read the preview first: often the head and tail already answer the question, or show that the call should be narrowed (a filter, a smaller page, a specific file) rather than paged through.
273
+ - Fetch only the ranges you need. Each fetch costs context on every later turn; paging through a huge output end to end is rarely worth it.
274
+ - The header of each fetch tells you the total size and where to continue; the offsets are characters, not lines.
275
+ - A blob id stays valid for the whole session, including after compaction, so you can note the id in your summary and come back to it.`;
276
+
277
+ // src/compact/rules.ts
278
+ var COMPACT_TOOL_NAME = "compact";
279
+ var RECALL_TOOL_NAME = "recall";
280
+ var COMPACT_TOOL_DESCRIPTION = [
281
+ "Fold earlier conversation into a summary you write, freeing context window.",
282
+ "Everything visible before the current turn (or before the last `keepRecentTurns` model turns) is replaced by your summary;",
283
+ "the originals stay in the session log but you will no longer see them.",
284
+ "Earlier summaries inside the folded range are replaced too \u2014 carry forward whatever still matters.",
285
+ "The most recent user message and pinned notes survive verbatim, so you need not repeat them.",
286
+ `Under your summary the harness lists every folded tool result (seq, tool, arguments); any of them can be brought back verbatim later with \`${RECALL_TOOL_NAME}\`.`
287
+ ].join(" ");
288
+ var RECALL_TOOL_DESCRIPTION = [
289
+ "Bring back, verbatim, a tool result that was folded away by a compaction.",
290
+ "Each summary lists its folded tool results as `seq N tool(arguments)`; pass that `seq`.",
291
+ "The original output is returned exactly as the tool produced it (large outputs are stored as blobs and read with fetch_blob instead).",
292
+ "Use it when you need a value that the summary only mentioned or left out; each recall costs a turn and stays in context afterwards."
293
+ ].join(" ");
294
+ var COMPACT_RULES = `## Managing your context window
295
+ You have a \`${COMPACT_TOOL_NAME}\` tool that folds earlier conversation into a summary you write. Runtime notes titled "Runtime context status" tell you how full the window is.
296
+ - Compact when a sub-task is finished or the trajectory has converged and the folded details are no longer needed verbatim. Do it at a natural pause, not while acting on something.
297
+ - Do not compact in the middle of a derivation, while a problem is still unresolved, or when you feel stuck: you would lose exactly the details you still need.
298
+ - The summary replaces everything it folds, including earlier summaries. Carry forward the user's goals and constraints, decisions made and why, the current state, and what comes next. List each fact that must survive in \`keep\`. The most recent user message and pinned notes survive verbatim on their own; check the pins still say what you need.
299
+ - Keep exact values, not just conclusions: identifiers, status and enum fields you verified, numbers, dates, error codes. "Checked, all ENABLE" loses the field values themselves.
300
+ - Nothing folded is lost for good: under each summary the harness lists the folded tool results as \`seq N tool(arguments)\`, and \`${RECALL_TOOL_NAME}({ seq })\` brings one back verbatim. When asked about a detail your summary did not keep, recall the result that contained it instead of guessing or saying it is gone.
301
+ - If you never compact, the harness folds the oldest turns mechanically once the window nears its limit. Its summary is worse than yours, but it lists the folded tool results the same way.`;
302
+
303
+ // src/compact/plan.ts
304
+ function parseCompactArgs(raw) {
305
+ if (typeof raw !== "object" || raw === null) throw new RangeError("compact expects an object");
306
+ const o = raw;
307
+ if (typeof o.summary !== "string" || o.summary.trim().length === 0) {
308
+ throw new RangeError("`summary` must be a non-empty string");
309
+ }
310
+ const keep = o.keep ?? [];
311
+ if (!Array.isArray(keep) || !keep.every((k) => typeof k === "string")) {
312
+ throw new RangeError("`keep` must be an array of strings");
313
+ }
314
+ const keepRecentTurns = o.keepRecentTurns ?? 0;
315
+ if (typeof keepRecentTurns !== "number" || !Number.isInteger(keepRecentTurns) || keepRecentTurns < 0) {
316
+ throw new RangeError("`keepRecentTurns` must be a non-negative integer");
317
+ }
318
+ return { summary: o.summary.trim(), keep: keep.map((k) => k.trim()).filter(Boolean), keepRecentTurns };
319
+ }
320
+ var MANIFEST_DEFAULT_EXCLUDE = /* @__PURE__ */ new Set([
321
+ COMPACT_TOOL_NAME,
322
+ RECALL_TOOL_NAME,
323
+ PIN_TOOL_NAME,
324
+ FETCH_BLOB_TOOL_NAME
325
+ ]);
326
+ var MANIFEST_HEADING = `Folded tool results (bring one back verbatim with ${RECALL_TOOL_NAME}({ seq })):`;
327
+ function renderCompactionSummary(args, folded = [], manifest = {}) {
328
+ const parts = [args.summary];
329
+ if (args.keep.length > 0)
330
+ parts.push(`Key facts carried forward:
331
+ ${args.keep.map((k) => `- ${k}`).join("\n")}`);
332
+ const list = renderFoldedToolResults(folded, { heading: MANIFEST_HEADING, ...manifest });
333
+ if (list) parts.push(list);
334
+ return parts.join("\n\n");
335
+ }
336
+ var ASSISTANT_TYPES = /* @__PURE__ */ new Set([
337
+ "core.model_thinking",
338
+ "core.model_text",
339
+ "core.tool_call"
340
+ ]);
341
+ function minSeq(events) {
342
+ let m = Number.POSITIVE_INFINITY;
343
+ for (const e of events) if (e.seq < m) m = e.seq;
344
+ return m;
345
+ }
346
+ function maxSeq(events) {
347
+ let m = 0;
348
+ for (const e of events) if (e.seq > m) m = e.seq;
349
+ return m;
350
+ }
351
+ function planCompaction(visible, args, opts = {}) {
352
+ const turns = splitTurns(visible);
353
+ const modelTurnStarts = [];
354
+ let protectedStart = visible.length;
355
+ let offset = 0;
356
+ for (const t of turns) {
357
+ if (t[0] && ASSISTANT_TYPES.has(t[0].type)) {
358
+ modelTurnStarts.push(offset);
359
+ if (opts.protectCallId !== void 0 && t.some((e) => e.id === opts.protectCallId))
360
+ protectedStart = offset;
361
+ }
362
+ offset += t.length;
363
+ }
364
+ let cut;
365
+ if (args.keepRecentTurns === 0) cut = visible.length;
366
+ else if (modelTurnStarts.length < args.keepRecentTurns) {
367
+ return {
368
+ ok: false,
369
+ reason: `Nothing to fold: only ${modelTurnStarts.length} model turn(s) are visible before this one, and you asked to keep ${args.keepRecentTurns}.`
370
+ };
371
+ } else cut = modelTurnStarts[modelTurnStarts.length - args.keepRecentTurns];
372
+ cut = Math.min(cut, protectedStart);
373
+ const before = visible.slice(0, cut);
374
+ const kept = visible.slice(cut);
375
+ const keptMin = minSeq(kept);
376
+ const absorbed = before.filter((e) => isCompaction(e) && e.seq < keptMin);
377
+ const folded = before.filter((e) => !isCompaction(e));
378
+ if (folded.length === 0) {
379
+ return {
380
+ ok: false,
381
+ reason: "Nothing to fold: the visible history before the kept turns is already a summary."
382
+ };
383
+ }
384
+ const priorKept = new Set(absorbed.flatMap((c) => isCompaction(c) ? c.payload.pinsKept : []));
385
+ let latestUser;
386
+ if (opts.keepLatestUserMessage !== false) {
387
+ for (let i = folded.length - 1; i >= 0 && !latestUser; i--) {
388
+ if (folded[i]?.type === "core.user_message") latestUser = folded[i];
389
+ }
390
+ }
391
+ const superseded = supersededIds(opts.timeline ?? visible);
392
+ const survivors = folded.filter(
393
+ (e) => !superseded.has(e.id) && (isPinNote(e) || priorKept.has(e.id) || e === latestUser)
394
+ );
395
+ const survivorIds = new Set(survivors.map((e) => e.id));
396
+ const manifestOpts = opts.manifest === false ? void 0 : { exclude: MANIFEST_DEFAULT_EXCLUDE, ...opts.manifest };
397
+ let manifest = [];
398
+ if (manifestOpts) {
399
+ const listed = new Set(folded.map((e) => e.id));
400
+ const scope = folded.filter((e) => !survivorIds.has(e.id));
401
+ if (opts.timeline) {
402
+ for (const c of absorbed) {
403
+ if (!isCompaction(c)) continue;
404
+ const [from2, to2] = c.payload.coversSeq;
405
+ for (const e of opts.timeline) {
406
+ if (e.seq >= from2 && e.seq <= to2 && e.seq < c.seq && !listed.has(e.id) && !isCompaction(e)) {
407
+ listed.add(e.id);
408
+ scope.push(e);
409
+ }
410
+ }
411
+ }
412
+ }
413
+ manifest = foldedToolResults(scope, {
414
+ lookup: opts.timeline ?? visible,
415
+ exclude: manifestOpts.exclude ?? MANIFEST_DEFAULT_EXCLUDE
416
+ });
417
+ }
418
+ const from = Math.min(
419
+ minSeq(folded),
420
+ ...absorbed.map((c) => isCompaction(c) ? c.payload.coversSeq[0] : Number.POSITIVE_INFINITY)
421
+ );
422
+ const to = Math.max(maxSeq(folded), maxSeq(absorbed));
423
+ return {
424
+ ok: true,
425
+ payload: {
426
+ coversSeq: [from, to],
427
+ summary: renderCompactionSummary(args, manifest, manifestOpts ?? {}),
428
+ decidedBy: "model",
429
+ pinsKept: survivors.map((e) => e.id)
430
+ },
431
+ folded,
432
+ absorbed,
433
+ keptTurns: args.keepRecentTurns,
434
+ manifest
435
+ };
436
+ }
437
+ function isPreModelEvent(e) {
438
+ if (isCompaction(e)) return e.payload.decidedBy === "threshold";
439
+ return e.type === "core.system_note" && e.actor === "system";
440
+ }
441
+ function segmentTimelineByTurn(timeline) {
442
+ const starts = [];
443
+ for (let i = 0; i < timeline.length; i++) {
444
+ const e = timeline[i];
445
+ const prev = timeline[i - 1];
446
+ if (!ASSISTANT_TYPES.has(e.type) || prev && ASSISTANT_TYPES.has(prev.type)) continue;
447
+ let j = i;
448
+ while (j > 0 && isPreModelEvent(timeline[j - 1]) && !starts.includes(j - 1)) j--;
449
+ if (starts.at(-1) !== j) starts.push(j);
450
+ }
451
+ if (starts.length === 0) return timeline.length > 0 ? [[...timeline]] : [];
452
+ const segments = [];
453
+ if (starts[0] > 0) segments.push(timeline.slice(0, starts[0]));
454
+ for (let k = 0; k < starts.length; k++) {
455
+ segments.push(timeline.slice(starts[k], starts[k + 1] ?? timeline.length));
456
+ }
457
+ return segments;
458
+ }
459
+ function trailingCompactionRun(timeline) {
460
+ const segments = segmentTimelineByTurn(timeline);
461
+ let count = 0;
462
+ for (let i = segments.length - 1; i >= 0; i--) {
463
+ const n = segments[i].filter(isCompaction).length;
464
+ if (n === 0) break;
465
+ count += n;
466
+ }
467
+ return count;
468
+ }
469
+
470
+ // src/compact/recall.ts
471
+ var RECALL_INPUT_SCHEMA = {
472
+ type: "object",
473
+ properties: {
474
+ seq: {
475
+ type: "integer",
476
+ minimum: 1,
477
+ description: "The `seq` shown next to the folded tool result in a summary's list."
478
+ }
479
+ },
480
+ required: ["seq"],
481
+ additionalProperties: false
482
+ };
483
+ function parseRecallArgs(raw) {
484
+ if (typeof raw !== "object" || raw === null) throw new RangeError(`${RECALL_TOOL_NAME} expects an object`);
485
+ const seq = raw.seq;
486
+ if (typeof seq !== "number" || !Number.isInteger(seq) || seq < 1) {
487
+ throw new RangeError("`seq` must be a positive integer");
488
+ }
489
+ return { seq };
490
+ }
491
+ var fail = (text) => ({ content: [{ type: "text", text }], isError: true });
492
+ function digest(args, max = 200) {
493
+ if (args === void 0) return "";
494
+ let text;
495
+ try {
496
+ text = JSON.stringify(args) ?? String(args);
497
+ } catch {
498
+ text = String(args);
499
+ }
500
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
501
+ }
502
+ async function locate(ctx, seq) {
503
+ let result;
504
+ let foundType;
505
+ const calls = /* @__PURE__ */ new Map();
506
+ for await (const e of ctx.log.read(ctx.sessionId)) {
507
+ if (e.type === "core.tool_call") calls.set(e.payload.toolCallId, e);
508
+ if (e.seq === seq) {
509
+ foundType = e.type;
510
+ if (e.type === "core.tool_result") result = e;
511
+ }
512
+ if (result && calls.has(result.payload.toolCallId)) break;
513
+ }
514
+ const out = {};
515
+ if (result) {
516
+ out.result = result;
517
+ const call = calls.get(result.payload.toolCallId);
518
+ if (call) out.call = call;
519
+ }
520
+ if (foundType) out.foundType = foundType;
521
+ return out;
522
+ }
523
+ async function recallResult(args, ctx) {
524
+ const { result, call, foundType } = await locate(ctx, args.seq);
525
+ if (!result) {
526
+ return fail(
527
+ foundType ? `seq ${args.seq} is a ${foundType.replace(/^core\./, "")} event, not a tool result. Pass a seq from a summary's "Folded tool results" list.` : `No event with seq ${args.seq} in this session.`
528
+ );
529
+ }
530
+ const { name, spilled, isError, content } = result.payload;
531
+ const head = `${name}(${digest(call?.payload.args)})`;
532
+ if (spilled) {
533
+ return fail(
534
+ `The output of seq ${args.seq} ${head} was too large to keep inline; it is stored verbatim as blob "${spilled.blobId}". Read it with ${FETCH_BLOB_TOOL_NAME}({ id: "${spilled.blobId}" }).`
535
+ );
536
+ }
537
+ const header = `[Recalled tool result seq ${args.seq}: ${head}${isError ? " (the tool reported an error)" : ""}. Original output follows verbatim.]`;
538
+ return { content: [{ type: "text", text: header }, ...content], isError: false };
539
+ }
540
+ function recallTool() {
541
+ return {
542
+ name: RECALL_TOOL_NAME,
543
+ description: RECALL_TOOL_DESCRIPTION,
544
+ inputSchema: RECALL_INPUT_SCHEMA,
545
+ validate: parseRecallArgs,
546
+ risk: "low",
547
+ execute: (args, ctx) => recallResult(args, ctx)
548
+ };
549
+ }
550
+
551
+ // src/compact/compact.ts
552
+ var COMPACT_SOCKET_NAME = "compact";
553
+ var DEFAULT_MAX_CONSECUTIVE_COMPACTIONS = 3;
554
+ var COMPACT_INPUT_SCHEMA = {
555
+ type: "object",
556
+ properties: {
557
+ summary: {
558
+ type: "string",
559
+ description: "Your summary of the folded conversation: goals and constraints, decisions and why, current state, next steps."
560
+ },
561
+ keep: {
562
+ type: "array",
563
+ items: { type: "string" },
564
+ description: "Facts that must survive verbatim (identifiers, numbers, user constraints). Empty if none."
565
+ },
566
+ keepRecentTurns: {
567
+ type: "integer",
568
+ minimum: 0,
569
+ description: "How many of the most recent model turns (with their tool results) to leave unfolded. Default 0 = fold everything before the current turn."
570
+ }
571
+ },
572
+ required: ["summary", "keep"],
573
+ additionalProperties: false
574
+ };
575
+ var PLACEHOLDER = `The ${COMPACT_TOOL_NAME} tool is present but its Socket is not installed; nothing was folded.`;
576
+ function replaceResult(result, text, isError) {
577
+ return { ...result, payload: { ...result.payload, content: [{ type: "text", text }], isError } };
578
+ }
579
+ function receipt(plan, withRecall) {
580
+ const [from, to] = plan.payload.coversSeq;
581
+ const parts = [`Folded ${plan.folded.length} events (seq ${from}\u2013${to}) into your summary.`];
582
+ if (plan.absorbed.length > 0) parts.push(`${plan.absorbed.length} earlier summary(ies) were absorbed.`);
583
+ if (plan.manifest.length > 0) {
584
+ parts.push(
585
+ `${plan.manifest.length} folded tool result(s) are listed under the summary${withRecall ? ` and can be brought back verbatim with ${RECALL_TOOL_NAME}({ seq })` : ""}.`
586
+ );
587
+ }
588
+ if (plan.payload.pinsKept.length > 0)
589
+ parts.push(
590
+ `${plan.payload.pinsKept.length} item(s) carried over verbatim (pinned notes and the latest user message).`
591
+ );
592
+ parts.push(
593
+ plan.keptTurns > 0 ? `The last ${plan.keptTurns} model turn(s) stay unfolded.` : "Only the current turn stays unfolded."
594
+ );
595
+ parts.push("The originals remain in the session log.");
596
+ return parts.join(" ");
597
+ }
598
+ function compact(opts = {}) {
599
+ const maxConsecutive = opts.maxConsecutive ?? DEFAULT_MAX_CONSECUTIVE_COMPACTIONS;
600
+ if (!Number.isInteger(maxConsecutive) || maxConsecutive < 1) {
601
+ throw new RangeError(`compact.maxConsecutive \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(maxConsecutive)}`);
602
+ }
603
+ const withRecall = opts.recall ?? true;
604
+ const records = /* @__PURE__ */ new WeakMap();
605
+ const recordOf = (ctx) => {
606
+ let r = records.get(ctx);
607
+ if (!r) {
608
+ r = { hadToolCall: false, compactions: 0 };
609
+ records.set(ctx, r);
610
+ }
611
+ return r;
612
+ };
613
+ const tool = {
614
+ name: COMPACT_TOOL_NAME,
615
+ description: COMPACT_TOOL_DESCRIPTION,
616
+ inputSchema: COMPACT_INPUT_SCHEMA,
617
+ validate: parseCompactArgs,
618
+ risk: "low",
619
+ execute: () => PLACEHOLDER
620
+ };
621
+ const socket = {
622
+ name: COMPACT_SOCKET_NAME,
623
+ tools: withRecall ? [tool, recallTool()] : [tool],
624
+ afterModel(ctx, events) {
625
+ recordOf(ctx).hadToolCall = events.some((e) => e.type === "core.tool_call");
626
+ },
627
+ afterTool(ctx, call, result) {
628
+ if (call.payload.name !== COMPACT_TOOL_NAME || result.payload.isError) return void 0;
629
+ let plan;
630
+ try {
631
+ plan = planCompaction(ctx.events, parseCompactArgs(call.payload.args), {
632
+ protectCallId: call.id,
633
+ timeline: ctx.timeline,
634
+ ...opts.manifest !== void 0 ? { manifest: opts.manifest } : {}
635
+ });
636
+ } catch (err) {
637
+ return replaceResult(result, err instanceof Error ? err.message : String(err), true);
638
+ }
639
+ if (!plan.ok) return replaceResult(result, plan.reason, true);
640
+ const payload = plan.payload;
641
+ ctx.emit({
642
+ type: "core.compaction",
643
+ actor: "model",
644
+ parentId: call.id,
645
+ provenance: { source: COMPACT_TOOL_NAME, ref: call.payload.toolCallId },
646
+ payload
647
+ });
648
+ recordOf(ctx).compactions++;
649
+ return replaceResult(result, receipt(plan, withRecall), false);
650
+ },
651
+ onTurnEnd(ctx) {
652
+ const record = records.get(ctx);
653
+ if (!record?.hadToolCall) return void 0;
654
+ const snapshotEnd = ctx.timeline.at(-1)?.seq ?? 0;
655
+ const thresholdThisTurn = ctx.events.filter((e) => isCompaction2(e) && e.seq > snapshotEnd).length;
656
+ const thisTurn = record.compactions + thresholdThisTurn;
657
+ if (thisTurn === 0) return void 0;
658
+ const total = thisTurn + trailingCompactionRun(ctx.timeline);
659
+ if (total < maxConsecutive) return void 0;
660
+ return {
661
+ pause: {
662
+ reason: "budget",
663
+ note: `Context was compacted ${total} times in a row without a turn of progress in between (limit ${maxConsecutive}). Either the window is still too small after folding, or the model is looping on compact. Paused for the host to inspect.`
664
+ }
665
+ };
666
+ }
667
+ };
668
+ if (opts.rules !== false) socket.systemPrompt = opts.rules ?? COMPACT_RULES;
669
+ return socket;
670
+ }
671
+ function isModelCompaction(e) {
672
+ return isCompaction2(e) && e.payload.decidedBy === "model";
673
+ }
674
+
675
+ // src/handoff/handoff.ts
676
+ import { isModelOutput, supersededIds as supersededIds2 } from "@reinsjs/core";
677
+
678
+ // src/handoff/rules.ts
679
+ var HANDOFF_TOOL_NAME = "handoff";
680
+ var HANDOFF_TOOL_DESCRIPTION = [
681
+ "End this session at the end of the current turn and continue the work in a fresh session.",
682
+ "The new session starts with only your `summary`, your `nextSteps`, the pinned notes, and the message it should act on;",
683
+ "nothing else from this session is carried over. Write the summary for a colleague who has seen none of this conversation.",
684
+ "Other tool calls in the same turn still run before the handoff happens."
685
+ ].join(" ");
686
+ var HANDOFF_RULES = `## Handing off to a new session
687
+ You have a \`${HANDOFF_TOOL_NAME}\` tool that ends this session and starts a fresh one carrying only your summary, next steps, and the pinned notes.
688
+ - Hand off when the history is mostly spent context rather than useful memory: a long task has reached a clean phase boundary, or compaction has already happened several times and the summaries are what you actually work from. Prefer compacting while the current context is still worth keeping.
689
+ - Do not hand off in the middle of a step, with tool results you have not read yet, or when the user is waiting for an answer to a direct question. Answer first.
690
+ - The summary is the whole memory of the next session: state the goal in the user's words, what is done and what was decided and why, the exact state of anything half-finished, and identifiers (paths, ids, numbers) the next session will need. Put one concrete action per item in \`nextSteps\`.
691
+ - Outputs stored as blobs in this session are not readable from the new one; copy what matters into the summary.`;
692
+
693
+ // src/handoff/handoff.ts
694
+ var HANDOFF_SOCKET_NAME = "handoff";
695
+ var DEFAULT_HANDOFF_REASON = "model_decision";
696
+ var HANDOFF_INPUT_SCHEMA = {
697
+ type: "object",
698
+ properties: {
699
+ summary: {
700
+ type: "string",
701
+ description: "Everything the next session must know, written for someone who has not seen this conversation: goal in the user's words, what is done, decisions and why, exact state of unfinished work, identifiers it will need."
702
+ },
703
+ nextSteps: {
704
+ type: "array",
705
+ items: { type: "string" },
706
+ description: "Concrete actions for the next session, in order. One action per item."
707
+ },
708
+ triggerMessage: {
709
+ type: "string",
710
+ description: "The message the new session should act on. Omit to reuse the latest user message from this session."
711
+ },
712
+ reason: {
713
+ type: "string",
714
+ description: "Why you are handing off (e.g. context_pressure, phase_boundary). Recorded in the timeline."
715
+ }
716
+ },
717
+ required: ["summary", "nextSteps"],
718
+ additionalProperties: false
719
+ };
720
+ function parseHandoffArgs(raw) {
721
+ if (typeof raw !== "object" || raw === null) throw new RangeError(`${HANDOFF_TOOL_NAME} expects an object`);
722
+ const o = raw;
723
+ if (typeof o.summary !== "string" || o.summary.trim().length === 0) {
724
+ throw new RangeError("`summary` must be a non-empty string");
725
+ }
726
+ if (!Array.isArray(o.nextSteps) || o.nextSteps.some((s) => typeof s !== "string")) {
727
+ throw new RangeError("`nextSteps` must be an array of strings (it may be empty)");
728
+ }
729
+ const out = {
730
+ summary: o.summary.trim(),
731
+ nextSteps: o.nextSteps.map((s) => s.trim()).filter((s) => s.length > 0)
732
+ };
733
+ for (const key of ["triggerMessage", "reason"]) {
734
+ const v = o[key];
735
+ if (v === void 0) continue;
736
+ if (typeof v !== "string" || v.trim().length === 0)
737
+ throw new RangeError(`\`${key}\` must be a non-empty string when given`);
738
+ out[key] = v.trim();
739
+ }
740
+ return out;
741
+ }
742
+ function composeHandoffNote(args) {
743
+ const lines = [
744
+ "Handoff from a previous session. What follows was written by the model before handing off; nothing else from that session is available here.",
745
+ "",
746
+ "## Summary",
747
+ args.summary
748
+ ];
749
+ if (args.nextSteps.length > 0) {
750
+ lines.push("", "## Next steps");
751
+ lines.push(...args.nextSteps.map((step, i) => `${i + 1}. ${step}`));
752
+ }
753
+ return lines.join("\n");
754
+ }
755
+ var isPin = (e) => e.type === "core.system_note" && e.payload.kind === "pin";
756
+ function carriedPins(ctx) {
757
+ const superseded = supersededIds2(ctx.timeline);
758
+ const out = [];
759
+ for (const e of ctx.events) {
760
+ if (!isPin(e) || superseded.has(e.id)) continue;
761
+ const payload = { kind: "pin", text: e.payload.text };
762
+ if (e.payload.meta !== void 0) payload.meta = e.payload.meta;
763
+ out.push({
764
+ type: "core.system_note",
765
+ actor: e.actor,
766
+ payload,
767
+ provenance: { source: HANDOFF_SOCKET_NAME, ref: e.id }
768
+ });
769
+ }
770
+ return out;
771
+ }
772
+ function lastVisibleUserMessage(events) {
773
+ for (let i = events.length - 1; i >= 0; i--) {
774
+ const e = events[i];
775
+ if (e.type !== "core.user_message") continue;
776
+ const text = e.payload.content.map((p) => p.type === "text" ? p.text : "").join("").trim();
777
+ return text.length > 0 ? text : void 0;
778
+ }
779
+ return void 0;
780
+ }
781
+ function unfinishedHandoffArgs(timeline) {
782
+ let receipt2;
783
+ for (let i = timeline.length - 1; i >= 0; i--) {
784
+ const e = timeline[i];
785
+ if (e.type === "core.handoff") return void 0;
786
+ if (isModelOutput(e)) {
787
+ if (receipt2) break;
788
+ return void 0;
789
+ }
790
+ if (e.type === "core.tool_result") {
791
+ const r = e;
792
+ if (r.payload.name === HANDOFF_TOOL_NAME && !r.payload.isError && !receipt2) receipt2 = r;
793
+ }
794
+ }
795
+ if (!receipt2) return void 0;
796
+ const call = timeline.find(
797
+ (e) => e.type === "core.tool_call" && e.payload.toolCallId === receipt2?.payload.toolCallId
798
+ );
799
+ if (!call) return void 0;
800
+ try {
801
+ return parseHandoffArgs(call.payload.args);
802
+ } catch {
803
+ return void 0;
804
+ }
805
+ }
806
+ function replaceResult2(result, text, isError) {
807
+ return { ...result, payload: { ...result.payload, content: [{ type: "text", text }], isError } };
808
+ }
809
+ var PLACEHOLDER2 = `The ${HANDOFF_TOOL_NAME} tool is present but its Socket is not installed; no handoff will happen.`;
810
+ function handoff(opts = {}) {
811
+ const carryPins = opts.carryPins ?? true;
812
+ const intents = /* @__PURE__ */ new WeakMap();
813
+ const tool = {
814
+ name: HANDOFF_TOOL_NAME,
815
+ description: HANDOFF_TOOL_DESCRIPTION,
816
+ inputSchema: HANDOFF_INPUT_SCHEMA,
817
+ validate: parseHandoffArgs,
818
+ risk: "low",
819
+ execute: () => PLACEHOLDER2
820
+ };
821
+ const socket = {
822
+ name: HANDOFF_SOCKET_NAME,
823
+ tools: [tool],
824
+ afterTool(ctx, call, result) {
825
+ if (call.payload.name !== HANDOFF_TOOL_NAME || result.payload.isError) return void 0;
826
+ if (intents.has(ctx)) {
827
+ return replaceResult2(
828
+ result,
829
+ "A handoff is already scheduled for the end of this turn; this call changed nothing.",
830
+ true
831
+ );
832
+ }
833
+ let args;
834
+ try {
835
+ args = parseHandoffArgs(call.payload.args);
836
+ } catch (err) {
837
+ return replaceResult2(result, err instanceof Error ? err.message : String(err), true);
838
+ }
839
+ const { intent, pins: pins2, triggerMessage } = intentOf(ctx, args);
840
+ intents.set(ctx, intent);
841
+ const carried = [
842
+ `${args.nextSteps.length} next step${args.nextSteps.length === 1 ? "" : "s"}`,
843
+ `${pins2.length} pinned note${pins2.length === 1 ? "" : "s"}`,
844
+ triggerMessage !== void 0 ? "the message to act on" : "no message to act on (the host will supply one)"
845
+ ].join(", ");
846
+ return replaceResult2(
847
+ result,
848
+ `Handoff scheduled: this session ends when this turn ends, and a new session starts with your summary, ${carried}. Finish any remaining tool calls of this turn; do not start new work.`,
849
+ false
850
+ );
851
+ },
852
+ onTurnEnd(ctx) {
853
+ const intent = intents.get(ctx);
854
+ if (intent) return { handoff: intent };
855
+ const args = unfinishedHandoffArgs(ctx.timeline);
856
+ return args ? { handoff: intentOf(ctx, args).intent } : void 0;
857
+ }
858
+ };
859
+ function intentOf(ctx, args) {
860
+ const pins2 = carryPins ? carriedPins(ctx) : [];
861
+ const triggerMessage = args.triggerMessage ?? lastVisibleUserMessage(ctx.events);
862
+ const intent = {
863
+ summary: composeHandoffNote(args),
864
+ reason: args.reason ?? DEFAULT_HANDOFF_REASON,
865
+ by: "model",
866
+ ...triggerMessage !== void 0 ? { triggerMessage } : {},
867
+ ...pins2.length > 0 ? { opening: pins2 } : {}
868
+ };
869
+ return { intent, pins: pins2, triggerMessage };
870
+ }
871
+ if (opts.rules !== false) socket.systemPrompt = opts.rules ?? HANDOFF_RULES;
872
+ return socket;
873
+ }
874
+
875
+ // src/shared/view.ts
876
+ var encoder = new TextEncoder();
877
+ var byteLength = (s) => encoder.encode(s).length;
878
+ function humanSize(bytes) {
879
+ if (bytes < 1024) return `${bytes}B`;
880
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}K`;
881
+ return `${(bytes / (1024 * 1024)).toFixed(1)}M`;
882
+ }
883
+ function splitLines(content) {
884
+ if (content.length === 0) return { lines: [], trailingNewline: false };
885
+ const trailingNewline = content.endsWith("\n");
886
+ const body = trailingNewline ? content.slice(0, -1) : content;
887
+ return { lines: body.split("\n"), trailingNewline };
888
+ }
889
+ function numbered(lines, firstLineNo) {
890
+ return lines.map((l, i) => `${String(firstLineNo + i).padStart(6)} ${l}`).join("\n");
891
+ }
892
+ function formatFileView(path, content, opts) {
893
+ const bytes = byteLength(content);
894
+ const { lines } = splitLines(content);
895
+ const total = lines.length;
896
+ let from = 1;
897
+ let to = total;
898
+ const range = opts.range;
899
+ if (range) {
900
+ const [start, end] = range;
901
+ if (start > Math.max(total, 1)) {
902
+ return {
903
+ error: `Invalid \`${opts.rangeField}\`: start_line ${start} is beyond the end of ${path}, which has ${total} lines.`
904
+ };
905
+ }
906
+ from = start;
907
+ to = end === -1 ? total : Math.min(end, total);
908
+ }
909
+ const chosen = lines.slice(from - 1, to);
910
+ let shown = chosen;
911
+ let note = "";
912
+ if (!range || opts.enforceLimit) {
913
+ let chars = 0;
914
+ let count = 0;
915
+ for (const l of chosen) {
916
+ chars += l.length + 1;
917
+ if (chars > opts.maxChars && count > 0) break;
918
+ count++;
919
+ }
920
+ if (count < chosen.length) {
921
+ shown = chosen.slice(0, count);
922
+ const last = from + count - 1;
923
+ note = `
924
+ [Showing lines ${from}-${last} of ${total} (${humanSize(bytes)} total). Use ${opts.rangeField}, e.g. [${last + 1}, -1], to read the rest.]`;
925
+ }
926
+ const first = shown[0];
927
+ if (opts.enforceLimit && first !== void 0 && first.length > opts.maxChars) {
928
+ shown = [first.slice(0, opts.maxChars)];
929
+ note = `
930
+ [Line ${from} is ${first.length} characters long; only the first ${opts.maxChars} are shown. Split long lines in this file to read it fully.]`;
931
+ }
932
+ }
933
+ const header = range ? `Here's the content of ${path} (lines ${from}-${to} of ${total}) with line numbers:` : `Here's the content of ${path} with line numbers:`;
934
+ return { text: `${header}
935
+ ${numbered(shown, from)}${note}` };
936
+ }
937
+
938
+ // src/shared/paths.ts
939
+ var MAX_ROOTED_PATH_LENGTH = 1024;
940
+ function resolveRootedPath(raw, root, field = "path") {
941
+ const reject = (why) => {
942
+ throw new RangeError(`Invalid \`${field}\`: ${why}. Paths must be absolute and stay under ${root}.`);
943
+ };
944
+ if (typeof raw !== "string") return reject("expected a string");
945
+ const p = raw.trim();
946
+ if (p.length === 0) return reject("it is empty");
947
+ if (p.length > MAX_ROOTED_PATH_LENGTH)
948
+ return reject(`it is longer than ${MAX_ROOTED_PATH_LENGTH} characters`);
949
+ if (/[\u0000-\u001f\u007f]/.test(p)) return reject("it contains control characters");
950
+ if (p.includes("\\")) return reject("backslashes are not allowed, use forward slashes");
951
+ if (/%[0-9a-f]{2}/i.test(p)) return reject("percent-encoded sequences are not allowed");
952
+ if (p !== root && !p.startsWith(`${root}/`)) {
953
+ return reject(`it must be ${root} or start with ${root}/`);
954
+ }
955
+ const segments = p.split("/").filter((s) => s.length > 0);
956
+ for (const s of segments) {
957
+ if (s === "." || s === "..") return reject("`.` and `..` segments are not allowed");
958
+ if (s !== s.trim()) return reject("a path segment starts or ends with whitespace");
959
+ }
960
+ return `/${segments.join("/")}`;
961
+ }
962
+ function isUnder(dir, path) {
963
+ return path.startsWith(`${dir}/`);
964
+ }
965
+
966
+ // src/memory/paths.ts
967
+ var MEMORY_ROOT = "/memories";
968
+ var MAX_MEMORY_PATH_LENGTH = MAX_ROOTED_PATH_LENGTH;
969
+ function resolveMemoryPath(raw, field = "path") {
970
+ return resolveRootedPath(raw, MEMORY_ROOT, field);
971
+ }
972
+
973
+ // src/memory/commands.ts
974
+ var MEMORY_COMMANDS = [
975
+ "view",
976
+ "create",
977
+ "str_replace",
978
+ "insert",
979
+ "delete",
980
+ "rename"
981
+ ];
982
+ var MEMORY_INPUT_SCHEMA = {
983
+ type: "object",
984
+ properties: {
985
+ command: {
986
+ type: "string",
987
+ enum: MEMORY_COMMANDS,
988
+ description: "The operation to perform."
989
+ },
990
+ path: {
991
+ type: "string",
992
+ description: "Absolute path under /memories. Used by every command except rename."
993
+ },
994
+ view_range: {
995
+ type: "array",
996
+ items: { type: "integer" },
997
+ minItems: 2,
998
+ maxItems: 2,
999
+ description: "view only: [start_line, end_line], 1-indexed and inclusive; end_line -1 means to the end of the file."
1000
+ },
1001
+ file_text: { type: "string", description: "create: the full content of the file." },
1002
+ old_str: {
1003
+ type: "string",
1004
+ description: "str_replace: the exact text to replace; it must occur exactly once in the file."
1005
+ },
1006
+ new_str: { type: "string", description: "str_replace: the replacement text. Omit to delete old_str." },
1007
+ insert_line: {
1008
+ type: "integer",
1009
+ minimum: 0,
1010
+ description: "insert: insert after this line number; 0 inserts at the top of the file."
1011
+ },
1012
+ insert_text: { type: "string", description: "insert: the text to insert." },
1013
+ old_path: { type: "string", description: "rename: the current path." },
1014
+ new_path: { type: "string", description: "rename: the new path; it must not exist yet." }
1015
+ },
1016
+ required: ["command"],
1017
+ additionalProperties: false
1018
+ };
1019
+ function parseMemoryCommand(raw) {
1020
+ if (typeof raw !== "object" || raw === null)
1021
+ throw new RangeError("memory expects an object with a `command`");
1022
+ const o = raw;
1023
+ const command = o.command;
1024
+ if (typeof command !== "string" || !MEMORY_COMMANDS.includes(command)) {
1025
+ throw new RangeError(
1026
+ `Unknown \`command\` ${JSON.stringify(command)}; expected one of ${MEMORY_COMMANDS.join(", ")}`
1027
+ );
1028
+ }
1029
+ const op = command;
1030
+ const str = (key) => {
1031
+ if (typeof o[key] !== "string")
1032
+ throw new RangeError(`\`${key}\` is required for ${op} and must be a string`);
1033
+ return o[key];
1034
+ };
1035
+ switch (op) {
1036
+ case "view": {
1037
+ const path = resolveMemoryPath(o.path);
1038
+ if (o.view_range === void 0) return { command: op, path };
1039
+ const r = o.view_range;
1040
+ if (!Array.isArray(r) || r.length !== 2 || !r.every((n) => Number.isInteger(n))) {
1041
+ throw new RangeError("`view_range` must be [start_line, end_line] with integer values");
1042
+ }
1043
+ const [start, end] = r;
1044
+ if (start < 1) throw new RangeError("`view_range` start_line must be \u2265 1");
1045
+ if (end !== -1 && end < start)
1046
+ throw new RangeError("`view_range` end_line must be \u2265 start_line, or -1 for the end");
1047
+ return { command: op, path, viewRange: [start, end] };
1048
+ }
1049
+ case "create":
1050
+ return { command: op, path: resolveMemoryPath(o.path), fileText: str("file_text") };
1051
+ case "str_replace": {
1052
+ const oldStr = str("old_str");
1053
+ if (oldStr.length === 0) throw new RangeError("`old_str` must not be empty");
1054
+ if (o.new_str !== void 0 && typeof o.new_str !== "string")
1055
+ throw new RangeError("`new_str` must be a string");
1056
+ return {
1057
+ command: op,
1058
+ path: resolveMemoryPath(o.path),
1059
+ oldStr,
1060
+ newStr: o.new_str ?? ""
1061
+ };
1062
+ }
1063
+ case "insert": {
1064
+ if (!Number.isInteger(o.insert_line) || o.insert_line < 0) {
1065
+ throw new RangeError("`insert_line` is required for insert and must be an integer \u2265 0");
1066
+ }
1067
+ return {
1068
+ command: op,
1069
+ path: resolveMemoryPath(o.path),
1070
+ insertLine: o.insert_line,
1071
+ insertText: str("insert_text")
1072
+ };
1073
+ }
1074
+ case "delete":
1075
+ return { command: op, path: resolveMemoryPath(o.path) };
1076
+ case "rename":
1077
+ return {
1078
+ command: op,
1079
+ oldPath: resolveMemoryPath(o.old_path, "old_path"),
1080
+ newPath: resolveMemoryPath(o.new_path, "new_path")
1081
+ };
1082
+ }
1083
+ }
1084
+ function bindMemoryFs(store, prefix = "") {
1085
+ return {
1086
+ read: (path) => store.read(prefix + path),
1087
+ write: (path, content) => store.write(prefix + path, content),
1088
+ delete: (path) => store.delete(prefix + path),
1089
+ async listUnder(dir) {
1090
+ const keyPrefix = `${prefix}${dir}/`;
1091
+ const keys = await store.list(keyPrefix);
1092
+ return keys.filter((k) => k.startsWith(keyPrefix)).map((k) => k.slice(prefix.length)).sort();
1093
+ }
1094
+ };
1095
+ }
1096
+ function lineOfOffset(content, offset) {
1097
+ let line = 1;
1098
+ for (let i = 0; i < offset; i++) if (content.charCodeAt(i) === 10) line++;
1099
+ return line;
1100
+ }
1101
+ function snippetAround(content, centerLine, spanLines, context = 4) {
1102
+ const { lines } = splitLines(content);
1103
+ const from = Math.max(1, centerLine - context);
1104
+ const to = Math.min(lines.length, centerLine + spanLines - 1 + context);
1105
+ return numbered(lines.slice(from - 1, to), from);
1106
+ }
1107
+ var ok = (text, op) => ({
1108
+ text,
1109
+ isError: false,
1110
+ op
1111
+ });
1112
+ var fail2 = (text) => ({ text, isError: true });
1113
+ var notFound = (path) => fail2(`The path ${path} does not exist. Please provide a valid path.`);
1114
+ async function isDirectory(fs, path) {
1115
+ if (path === MEMORY_ROOT) return true;
1116
+ return (await fs.listUnder(path)).length > 0;
1117
+ }
1118
+ async function readForEdit(fs, path) {
1119
+ const content = await fs.read(path);
1120
+ if (content !== null) return { content };
1121
+ if (await isDirectory(fs, path))
1122
+ return { error: fail2(`Error: The path ${path} is a directory, not a file.`) };
1123
+ return { error: fail2(`Error: The path ${path} does not exist. Please provide a valid path.`) };
1124
+ }
1125
+ function checkSize(path, content, limits) {
1126
+ const size = byteLength(content);
1127
+ if (size <= limits.maxFileBytes) return void 0;
1128
+ return fail2(
1129
+ `Error: The resulting file ${path} would be ${humanSize(size)} (${size} bytes); memory files are limited to ${humanSize(limits.maxFileBytes)}. Split it into smaller files or keep only what a future session will need.`
1130
+ );
1131
+ }
1132
+ async function executeMemoryCommand(fs, cmd, limits) {
1133
+ switch (cmd.command) {
1134
+ case "view":
1135
+ return view(fs, cmd.path, cmd.viewRange, limits);
1136
+ case "create":
1137
+ return create(fs, cmd.path, cmd.fileText, limits);
1138
+ case "str_replace":
1139
+ return strReplace(fs, cmd.path, cmd.oldStr, cmd.newStr, limits);
1140
+ case "insert":
1141
+ return insert(fs, cmd.path, cmd.insertLine, cmd.insertText, limits);
1142
+ case "delete":
1143
+ return remove(fs, cmd.path);
1144
+ case "rename":
1145
+ return rename(fs, cmd.oldPath, cmd.newPath);
1146
+ }
1147
+ }
1148
+ async function view(fs, path, range, limits) {
1149
+ const content = await fs.read(path);
1150
+ if (content === null) {
1151
+ if (!await isDirectory(fs, path)) return notFound(path);
1152
+ return listing(fs, path);
1153
+ }
1154
+ const v = formatFileView(path, content, { range, maxChars: limits.maxViewChars, rangeField: "view_range" });
1155
+ if (v.error !== void 0) return fail2(v.error);
1156
+ return ok(v.text, { op: "view", path, bytes: byteLength(content) });
1157
+ }
1158
+ async function listing(fs, dir) {
1159
+ const files = await fs.listUnder(dir);
1160
+ const sizes = /* @__PURE__ */ new Map();
1161
+ await Promise.all(
1162
+ files.map(async (f) => {
1163
+ sizes.set(f, byteLength(await fs.read(f) ?? ""));
1164
+ })
1165
+ );
1166
+ const entries = /* @__PURE__ */ new Map();
1167
+ let total = 0;
1168
+ for (const f of files) {
1169
+ const size = sizes.get(f) ?? 0;
1170
+ total += size;
1171
+ const rel = f.slice(dir.length + 1).split("/");
1172
+ const first = `${dir}/${rel[0]}`;
1173
+ if (rel.length === 1) {
1174
+ entries.set(first, size);
1175
+ continue;
1176
+ }
1177
+ entries.set(first, (entries.get(first) ?? 0) + size);
1178
+ const second = `${first}/${rel[1]}`;
1179
+ if (rel.length >= 2) entries.set(second, (entries.get(second) ?? 0) + size);
1180
+ }
1181
+ const rows = [`${humanSize(total)} ${dir}`];
1182
+ for (const p of [...entries.keys()].sort()) rows.push(`${humanSize(entries.get(p) ?? 0)} ${p}`);
1183
+ return ok(`Here're the files and directories up to 2 levels deep in ${dir}:
1184
+ ${rows.join("\n")}`, {
1185
+ op: "view",
1186
+ path: dir
1187
+ });
1188
+ }
1189
+ async function create(fs, path, fileText, limits) {
1190
+ if (path === MEMORY_ROOT) return fail2(`Error: ${MEMORY_ROOT} is the memory root directory, not a file.`);
1191
+ const existing = await fs.read(path);
1192
+ if (existing === null && await isDirectory(fs, path)) {
1193
+ return fail2(`Error: ${path} is a directory; choose a file path inside it or elsewhere.`);
1194
+ }
1195
+ const tooBig = checkSize(path, fileText, limits);
1196
+ if (tooBig) return tooBig;
1197
+ await fs.write(path, fileText);
1198
+ const bytes = byteLength(fileText);
1199
+ return ok(
1200
+ existing === null ? `File created successfully at: ${path}` : `File created successfully at: ${path} (replaced the previous content)`,
1201
+ { op: "create", path, bytes }
1202
+ );
1203
+ }
1204
+ async function strReplace(fs, path, oldStr, newStr, limits) {
1205
+ const r = await readForEdit(fs, path);
1206
+ if ("error" in r) return r.error;
1207
+ const { content } = r;
1208
+ const hits = [];
1209
+ for (let i = content.indexOf(oldStr); i !== -1; i = content.indexOf(oldStr, i + oldStr.length)) hits.push(i);
1210
+ if (hits.length === 0) {
1211
+ return fail2(`No replacement was performed, old_str \`${oldStr}\` did not appear verbatim in ${path}.`);
1212
+ }
1213
+ if (hits.length > 1) {
1214
+ const lines = hits.map((h) => lineOfOffset(content, h)).join(", ");
1215
+ return fail2(
1216
+ `No replacement was performed. Multiple occurrences of old_str \`${oldStr}\` in lines: ${lines}. Please ensure it is unique`
1217
+ );
1218
+ }
1219
+ const at = hits[0];
1220
+ const next = content.slice(0, at) + newStr + content.slice(at + oldStr.length);
1221
+ const tooBig = checkSize(path, next, limits);
1222
+ if (tooBig) return tooBig;
1223
+ await fs.write(path, next);
1224
+ const line = lineOfOffset(next, at);
1225
+ const span = Math.max(1, newStr.split("\n").length);
1226
+ return ok(
1227
+ `The memory file has been edited.
1228
+ Here's a snippet of ${path} around the edit:
1229
+ ${snippetAround(next, line, span)}`,
1230
+ { op: "str_replace", path, bytes: byteLength(next) }
1231
+ );
1232
+ }
1233
+ async function insert(fs, path, insertLine, insertText, limits) {
1234
+ const r = await readForEdit(fs, path);
1235
+ if ("error" in r) return r.error;
1236
+ const { lines, trailingNewline } = splitLines(r.content);
1237
+ if (insertLine > lines.length) {
1238
+ return fail2(
1239
+ `Error: Invalid \`insert_line\` parameter: ${insertLine}. It should be within the range of lines of the file: [0, ${lines.length}]`
1240
+ );
1241
+ }
1242
+ const inserted = (insertText.endsWith("\n") ? insertText.slice(0, -1) : insertText).split("\n");
1243
+ lines.splice(insertLine, 0, ...inserted);
1244
+ const next = lines.join("\n") + (trailingNewline || r.content.length === 0 ? "\n" : "");
1245
+ const tooBig = checkSize(path, next, limits);
1246
+ if (tooBig) return tooBig;
1247
+ await fs.write(path, next);
1248
+ return ok(
1249
+ `The file ${path} has been edited.
1250
+ Here's a snippet of ${path} around the edit:
1251
+ ${snippetAround(next, insertLine + 1, inserted.length)}`,
1252
+ { op: "insert", path, bytes: byteLength(next) }
1253
+ );
1254
+ }
1255
+ async function remove(fs, path) {
1256
+ if (path === MEMORY_ROOT) {
1257
+ return fail2(
1258
+ `Error: The memory root ${MEMORY_ROOT} cannot be deleted. Delete individual files or directories under it.`
1259
+ );
1260
+ }
1261
+ const content = await fs.read(path);
1262
+ if (content !== null) {
1263
+ await fs.delete(path);
1264
+ return ok(`Successfully deleted ${path}`, { op: "delete", path, bytes: byteLength(content) });
1265
+ }
1266
+ const children = await fs.listUnder(path);
1267
+ if (children.length === 0) return fail2(`Error: The path ${path} does not exist`);
1268
+ let bytes = 0;
1269
+ for (const child of children) {
1270
+ bytes += byteLength(await fs.read(child) ?? "");
1271
+ await fs.delete(child);
1272
+ }
1273
+ return ok(`Successfully deleted ${path} (${children.length} files)`, { op: "delete", path, bytes });
1274
+ }
1275
+ async function rename(fs, oldPath, newPath) {
1276
+ if (oldPath === MEMORY_ROOT) return fail2(`Error: The memory root ${MEMORY_ROOT} cannot be renamed.`);
1277
+ if (newPath === MEMORY_ROOT) return fail2(`Error: The destination ${MEMORY_ROOT} is the memory root.`);
1278
+ if (oldPath === newPath) return fail2(`Error: old_path and new_path are the same: ${oldPath}`);
1279
+ if (await fs.read(newPath) !== null || await isDirectory(fs, newPath)) {
1280
+ return fail2(`Error: The destination ${newPath} already exists`);
1281
+ }
1282
+ const content = await fs.read(oldPath);
1283
+ if (content !== null) {
1284
+ await fs.write(newPath, content);
1285
+ await fs.delete(oldPath);
1286
+ return ok(`Successfully renamed ${oldPath} to ${newPath}`, {
1287
+ op: "rename",
1288
+ path: oldPath,
1289
+ toPath: newPath,
1290
+ bytes: byteLength(content)
1291
+ });
1292
+ }
1293
+ const children = await fs.listUnder(oldPath);
1294
+ if (children.length === 0) return fail2(`Error: The path ${oldPath} does not exist`);
1295
+ if (isUnder(oldPath, newPath)) return fail2(`Error: Cannot move ${oldPath} into itself (${newPath})`);
1296
+ let bytes = 0;
1297
+ for (const child of children) {
1298
+ const text = await fs.read(child) ?? "";
1299
+ bytes += byteLength(text);
1300
+ await fs.write(newPath + child.slice(oldPath.length), text);
1301
+ await fs.delete(child);
1302
+ }
1303
+ return ok(`Successfully renamed ${oldPath} to ${newPath} (${children.length} files)`, {
1304
+ op: "rename",
1305
+ path: oldPath,
1306
+ toPath: newPath,
1307
+ bytes
1308
+ });
1309
+ }
1310
+
1311
+ // src/memory/rules.ts
1312
+ var MEMORY_TOOL_NAME = "memory";
1313
+ var MEMORY_TOOL_DESCRIPTION = [
1314
+ "Read and write files in your memory directory `/memories`, which persists across sessions.",
1315
+ "Commands: `view` shows a directory listing or a file with line numbers (optional `view_range: [start, end]`, `end` -1 means to the end);",
1316
+ "`create` creates or overwrites a file with `file_text`;",
1317
+ "`str_replace` replaces exactly one occurrence of `old_str` with `new_str` (omit `new_str` to delete it);",
1318
+ "`insert` inserts `insert_text` after line `insert_line` (0 inserts at the top);",
1319
+ "`delete` removes a file or a whole directory; `rename` moves `old_path` to `new_path` (the destination must not exist).",
1320
+ "Every path must start with `/memories`; the root itself cannot be deleted or renamed."
1321
+ ].join(" ");
1322
+ var MEMORY_RULES = `## Memory
1323
+ You have a \`${MEMORY_TOOL_NAME}\` tool: a directory \`/memories\` that persists across sessions, while everything else in this conversation is forgotten when it ends.
1324
+ - Before starting a task, \`view\` \`/memories\` and read the files that look relevant. Earlier sessions may have left progress, decisions, or lessons there.
1325
+ - Record what a future session would need and could not re-derive: the goal in the user's words, decisions and the reasons behind them, open questions, lessons from mistakes, where things are. Do not store what can be read from the code or documents, transient state, or secrets and credentials.
1326
+ - Assume interruption: your context may be reset at any moment. Update memory as you make progress, not only at the end.
1327
+ - Keep it organized: small files with clear names, rewrite a fact when it changes instead of appending a second version, delete what is no longer true.`;
1328
+
1329
+ // src/memory/memory.ts
1330
+ var MEMORY_SOCKET_NAME = "memory";
1331
+ var DEFAULT_MAX_FILE_BYTES = 64 * 1024;
1332
+ var DEFAULT_MAX_VIEW_CHARS = 16e3;
1333
+ function memory(opts = {}) {
1334
+ const limits = {
1335
+ maxFileBytes: opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES,
1336
+ maxViewChars: opts.maxViewChars ?? DEFAULT_MAX_VIEW_CHARS
1337
+ };
1338
+ if (!Number.isInteger(limits.maxFileBytes) || limits.maxFileBytes < 1) {
1339
+ throw new RangeError(`memory.maxFileBytes \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(limits.maxFileBytes)}`);
1340
+ }
1341
+ if (!Number.isInteger(limits.maxViewChars) || limits.maxViewChars < 1) {
1342
+ throw new RangeError(`memory.maxViewChars \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(limits.maxViewChars)}`);
1343
+ }
1344
+ if (opts.namespace !== void 0 && typeof opts.namespace !== "function") {
1345
+ throw new RangeError("memory.namespace \u5FC5\u987B\u662F\u51FD\u6570");
1346
+ }
1347
+ const namespace = opts.namespace ?? (() => "");
1348
+ const warn = opts.warn ?? ((message) => console.warn(message));
1349
+ let warned = false;
1350
+ const tool = {
1351
+ name: MEMORY_TOOL_NAME,
1352
+ description: MEMORY_TOOL_DESCRIPTION,
1353
+ inputSchema: MEMORY_INPUT_SCHEMA,
1354
+ validate: parseMemoryCommand,
1355
+ risk: "low",
1356
+ async execute(cmd, ctx) {
1357
+ if (!ctx.memory) {
1358
+ return {
1359
+ content: [
1360
+ { type: "text", text: "No memory store is configured for this session; memory is unavailable." }
1361
+ ],
1362
+ isError: true
1363
+ };
1364
+ }
1365
+ const fs = bindMemoryFs(ctx.memory, namespace(ctx));
1366
+ const outcome = await executeMemoryCommand(fs, cmd, limits);
1367
+ if (outcome.op) {
1368
+ ctx.emit({
1369
+ type: "core.memory_op",
1370
+ actor: "model",
1371
+ payload: outcome.op,
1372
+ provenance: { source: MEMORY_SOCKET_NAME, ref: ctx.toolCallId }
1373
+ });
1374
+ }
1375
+ return { content: [{ type: "text", text: outcome.text }], isError: outcome.isError };
1376
+ }
1377
+ };
1378
+ const available = (setup) => {
1379
+ if (setup.memory) return true;
1380
+ if (!warned) {
1381
+ warned = true;
1382
+ warn(
1383
+ "[reins/memory] \u6CA1\u6709\u914D\u7F6E MemoryStore\uFF0Cmemory \u5DE5\u5177\u4E0E\u89C4\u5219\u63D0\u793A\u672A\u6CE8\u518C\u3002\u7ED9 runLoop / createAgent \u7684 store \u914D\u4E0A memory \u5373\u53EF\u5F00\u542F\u3002"
1384
+ );
1385
+ }
1386
+ return false;
1387
+ };
1388
+ const socket = {
1389
+ name: MEMORY_SOCKET_NAME,
1390
+ tools: (setup) => available(setup) ? [tool] : void 0
1391
+ };
1392
+ if (opts.rules !== false) {
1393
+ const rules = opts.rules ?? MEMORY_RULES;
1394
+ socket.systemPrompt = (setup) => setup.memory ? rules : void 0;
1395
+ }
1396
+ return socket;
1397
+ }
1398
+
1399
+ // src/perception/reading.ts
1400
+ import { contextTokensOf as contextTokensOf2 } from "@reinsjs/core";
1401
+
1402
+ // src/perception/tiers.ts
1403
+ function assertAscending(name, bounds) {
1404
+ for (let i = 0; i < bounds.length; i++) {
1405
+ const cur = bounds[i];
1406
+ const prev = bounds[i - 1];
1407
+ if (cur === void 0 || !Number.isFinite(cur) || prev !== void 0 && cur <= prev) {
1408
+ throw new RangeError(`${name} \u7684\u6863\u4F4D\u8FB9\u754C\u5FC5\u987B\u662F\u4E25\u683C\u5347\u5E8F\u7684\u6709\u9650\u6570\uFF1A${JSON.stringify(bounds)}`);
1409
+ }
1410
+ }
1411
+ }
1412
+ function rangeTier(value, bounds, fmt2) {
1413
+ let level = 0;
1414
+ while (level < bounds.length && value >= bounds[level]) level++;
1415
+ const lo = bounds[level - 1];
1416
+ const hi = bounds[level];
1417
+ if (lo === void 0) return { level, label: `<${fmt2(hi)}` };
1418
+ if (hi === void 0) return { level, label: `\u2265${fmt2(lo)}` };
1419
+ return { level, label: `${fmt2(lo)}\u2013${fmt2(hi)}` };
1420
+ }
1421
+ function countTier(value, bounds) {
1422
+ let level = 0;
1423
+ while (level < bounds.length && value > bounds[level]) level++;
1424
+ const lo = bounds[level - 1];
1425
+ const hi = bounds[level];
1426
+ if (lo === void 0) return { level, label: `\u2264${hi}` };
1427
+ if (hi === void 0) return { level, label: `>${lo}` };
1428
+ return { level, label: lo + 1 === hi ? `${hi}` : `${lo + 1}\u2013${hi}` };
1429
+ }
1430
+ var percent = (ratio) => `${Math.round(ratio * 100)}%`;
1431
+ function compactNumber(n) {
1432
+ const trim = (x) => String(Number(x.toFixed(1)));
1433
+ if (n >= 1e6) return `${trim(n / 1e6)}M`;
1434
+ if (n >= 1e3) return `${trim(n / 1e3)}k`;
1435
+ return String(n);
1436
+ }
1437
+
1438
+ // src/perception/reading.ts
1439
+ var ASSISTANT_TYPES2 = /* @__PURE__ */ new Set([
1440
+ "core.model_thinking",
1441
+ "core.model_text",
1442
+ "core.tool_call"
1443
+ ]);
1444
+ function countModelTurns(events) {
1445
+ let turns = 0;
1446
+ let inTurn = false;
1447
+ for (const e of events) {
1448
+ const isAssistant = ASSISTANT_TYPES2.has(e.type);
1449
+ if (isAssistant && !inTurn) turns++;
1450
+ inTurn = isAssistant;
1451
+ }
1452
+ return turns;
1453
+ }
1454
+ function sumSessionTokens(timeline) {
1455
+ let n = 0;
1456
+ for (const raw of timeline) {
1457
+ const e = raw;
1458
+ if (e.type !== "core.budget_usage") continue;
1459
+ const t = e.payload.tokens;
1460
+ n += t.input + t.output + (t.cacheRead ?? 0) + (t.cacheWrite ?? 0);
1461
+ }
1462
+ return n;
1463
+ }
1464
+ function contextOverheadOf(timeline) {
1465
+ for (let i = timeline.length - 1; i >= 0; i--) {
1466
+ const e = timeline[i];
1467
+ if (e?.type !== "core.budget_usage" || e.payload.contextEstimate === void 0) continue;
1468
+ return Math.max(0, contextTokensOf2(e.payload.tokens) - e.payload.contextEstimate);
1469
+ }
1470
+ return 0;
1471
+ }
1472
+ function remainingOf(budget2, contextTokens, limits) {
1473
+ const used = {
1474
+ contextTokens,
1475
+ totalTokens: budget2.tokensSpent,
1476
+ turns: budget2.turns,
1477
+ toolCalls: budget2.toolCalls,
1478
+ wallMs: budget2.wallMs
1479
+ };
1480
+ let tightest;
1481
+ for (const dimension of Object.keys(used)) {
1482
+ const limit = limits[dimension];
1483
+ if (limit === void 0 || limit <= 0) continue;
1484
+ const fraction = Math.max(0, 1 - used[dimension] / limit);
1485
+ if (!tightest || fraction < tightest.fraction) tightest = { fraction, dimension };
1486
+ }
1487
+ return tightest;
1488
+ }
1489
+ function readPerception(ctx, thresholds, limits, opts = {}) {
1490
+ const { budget: budget2 } = ctx;
1491
+ const contextOverhead = opts.calibrate === false ? 0 : contextOverheadOf(ctx.timeline);
1492
+ const contextTokens = budget2.used + contextOverhead;
1493
+ const spilled = ctx.events.filter(
1494
+ (e) => e.type === "core.tool_result" && e.payload.spilled
1495
+ ).length;
1496
+ const spilledTier = spillTier(spilled, thresholds.spills);
1497
+ const reading = {
1498
+ contextUsage: rangeTier(contextTokens / budget2.contextLimit, thresholds.usage, percent),
1499
+ contextOverhead,
1500
+ autoFoldAt: percent(budget2.targetTokens / budget2.contextLimit),
1501
+ unfoldedTurns: countTier(countModelTurns(ctx.events), thresholds.turns),
1502
+ compactions: ctx.timeline.filter((e) => e.type === "core.compaction").length,
1503
+ sessionTokens: rangeTier(sumSessionTokens(ctx.timeline), thresholds.tokens, compactNumber),
1504
+ spilledResults: spilledTier
1505
+ };
1506
+ const remaining = limits ? remainingOf(budget2, contextTokens, limits) : void 0;
1507
+ if (remaining) {
1508
+ reading.budgetRemaining = {
1509
+ ...rangeTier(remaining.fraction, thresholds.remaining, percent),
1510
+ tightest: remaining.dimension
1511
+ };
1512
+ }
1513
+ return reading;
1514
+ }
1515
+ function spillTier(n, bounds) {
1516
+ if (n === 0) return { level: 0, label: "0" };
1517
+ const t = countTier(n, bounds);
1518
+ const first = bounds[0];
1519
+ const label = t.level === 0 && first !== void 0 ? first === 1 ? "1" : `1\u2013${first}` : t.label;
1520
+ return { level: t.level + 1, label };
1521
+ }
1522
+
1523
+ // src/perception/render.ts
1524
+ function foldedNote(compactions) {
1525
+ return compactions === 0 ? "(nothing has been folded; everything above is verbatim)" : "(only the ranges those summaries replaced are gone; every tool result still shown above is verbatim)";
1526
+ }
1527
+ function renderPerception(r) {
1528
+ const lines = [
1529
+ "Runtime context status (from the harness, not from the user):",
1530
+ `- Context window used: ${r.contextUsage.label} (the harness auto-folds the oldest turns at ${r.autoFoldAt})`,
1531
+ `- Unfolded history: ${r.unfoldedTurns.label} turns; compactions so far: ${r.compactions} ${foldedNote(r.compactions)}`,
1532
+ `- Session tokens used: ${r.sessionTokens.label}`
1533
+ ];
1534
+ if (r.budgetRemaining) {
1535
+ lines.push(`- Run budget remaining: ${r.budgetRemaining.label} (tightest: ${r.budgetRemaining.tightest})`);
1536
+ }
1537
+ if (r.spilledResults.level > 0) {
1538
+ lines.push(`- Tool results spilled out of the context: ${r.spilledResults.label}`);
1539
+ }
1540
+ return lines.join("\n");
1541
+ }
1542
+
1543
+ // src/perception/perception.ts
1544
+ var DEFAULT_PERCEPTION_THRESHOLDS = {
1545
+ usage: [0.5, 0.7, 0.85],
1546
+ turns: [5, 15, 40],
1547
+ tokens: [1e4, 5e4, 2e5, 1e6],
1548
+ spills: [3, 10],
1549
+ remaining: [0.05, 0.2, 0.5]
1550
+ };
1551
+ var PERCEPTION_SOCKET_NAME = "perception";
1552
+ function lastVisiblePerceptionNote(visible) {
1553
+ for (let i = visible.length - 1; i >= 0; i--) {
1554
+ const e = visible[i];
1555
+ if (e?.type === "core.system_note" && e.payload.kind === "perception") return e;
1556
+ }
1557
+ return void 0;
1558
+ }
1559
+ function perception(opts = {}) {
1560
+ const thresholds = {
1561
+ usage: opts.usageTiers ?? DEFAULT_PERCEPTION_THRESHOLDS.usage,
1562
+ turns: opts.turnTiers ?? DEFAULT_PERCEPTION_THRESHOLDS.turns,
1563
+ tokens: opts.tokenTiers ?? DEFAULT_PERCEPTION_THRESHOLDS.tokens,
1564
+ spills: opts.spillTiers ?? DEFAULT_PERCEPTION_THRESHOLDS.spills,
1565
+ remaining: opts.remainingTiers ?? DEFAULT_PERCEPTION_THRESHOLDS.remaining
1566
+ };
1567
+ for (const [name, bounds] of Object.entries(thresholds)) assertAscending(`perception.${name}`, bounds);
1568
+ const render = opts.render ?? renderPerception;
1569
+ return {
1570
+ name: PERCEPTION_SOCKET_NAME,
1571
+ beforeModel(ctx) {
1572
+ const reading = readPerception(ctx, thresholds, opts.limits, {
1573
+ ...opts.calibrate !== void 0 ? { calibrate: opts.calibrate } : {}
1574
+ });
1575
+ const text = render(reading);
1576
+ if (lastVisiblePerceptionNote(ctx.events)?.payload.text === text) return void 0;
1577
+ ctx.emit({
1578
+ type: "core.system_note",
1579
+ actor: "system",
1580
+ payload: { kind: "perception", text, meta: { reading } }
1581
+ });
1582
+ return void 0;
1583
+ }
1584
+ };
1585
+ }
1586
+
1587
+ // src/pins/pins.ts
1588
+ var PINS_SOCKET_NAME = "pins";
1589
+ var DEFAULT_MAX_PIN_TEXT_LENGTH = 500;
1590
+ var DEFAULT_PIN_OVERSHOOT_TOLERANCE = 0.2;
1591
+ function pinInputSchema(maxTextLength) {
1592
+ return {
1593
+ type: "object",
1594
+ properties: {
1595
+ text: {
1596
+ type: "string",
1597
+ maxLength: maxTextLength,
1598
+ description: `The note to pin, one or two sentences (at most ${maxTextLength} characters). It will be shown verbatim after every future summary.`
1599
+ },
1600
+ replaces: {
1601
+ type: "string",
1602
+ description: "Exact text of one of your earlier pinned notes that this one supersedes. Omit to add a new note."
1603
+ }
1604
+ },
1605
+ required: ["text"],
1606
+ additionalProperties: false
1607
+ };
1608
+ }
1609
+ var PIN_INPUT_SCHEMA = {
1610
+ type: "object",
1611
+ properties: {
1612
+ text: {
1613
+ type: "string",
1614
+ description: "The note to pin, one or two sentences. It will be shown verbatim after every future summary."
1615
+ },
1616
+ replaces: {
1617
+ type: "string",
1618
+ description: "Exact text of one of your earlier pinned notes that this one supersedes. Omit to add a new note."
1619
+ }
1620
+ },
1621
+ required: ["text"],
1622
+ additionalProperties: false
1623
+ };
1624
+ function parsePinArgs(raw, maxTextLength = DEFAULT_MAX_PIN_TEXT_LENGTH, overshootTolerance = DEFAULT_PIN_OVERSHOOT_TOLERANCE) {
1625
+ if (typeof raw !== "object" || raw === null) throw new RangeError(`${PIN_TOOL_NAME} expects an object`);
1626
+ const o = raw;
1627
+ if (typeof o.text !== "string" || o.text.trim().length === 0) {
1628
+ throw new RangeError("`text` must be a non-empty string");
1629
+ }
1630
+ const text = o.text.trim();
1631
+ if (text.length > Math.ceil(maxTextLength * (1 + overshootTolerance))) {
1632
+ throw new RangeError(
1633
+ `\`text\` is ${text.length} characters; pins are limited to ${maxTextLength}. Split it across several notes or put it in your compact summary instead.`
1634
+ );
1635
+ }
1636
+ if (o.replaces !== void 0 && (typeof o.replaces !== "string" || o.replaces.trim().length === 0)) {
1637
+ throw new RangeError("`replaces` must be a non-empty string when given");
1638
+ }
1639
+ return typeof o.replaces === "string" ? { text, replaces: o.replaces.trim() } : { text };
1640
+ }
1641
+ function isPinNoteEvent(e) {
1642
+ return e.type === "core.system_note" && e.payload.kind === "pin";
1643
+ }
1644
+ function pinMetaOf(e) {
1645
+ const m = e.payload.meta?.pin;
1646
+ if (typeof m !== "object" || m === null) return void 0;
1647
+ const source = m.source;
1648
+ if (source !== "host" && source !== "model") return void 0;
1649
+ const spec = m.spec;
1650
+ return typeof spec === "string" ? { source, spec } : { source };
1651
+ }
1652
+ function lastHostPin(events, spec) {
1653
+ for (let i = events.length - 1; i >= 0; i--) {
1654
+ const e = events[i];
1655
+ if (!isPinNoteEvent(e)) continue;
1656
+ const meta = pinMetaOf(e);
1657
+ if (meta?.source === "host" && meta.spec === spec) return e;
1658
+ }
1659
+ return void 0;
1660
+ }
1661
+ function findModelPin(events, text) {
1662
+ for (let i = events.length - 1; i >= 0; i--) {
1663
+ const e = events[i];
1664
+ if (isPinNoteEvent(e) && pinMetaOf(e)?.source === "model" && e.payload.text === text) return e;
1665
+ }
1666
+ return void 0;
1667
+ }
1668
+ function normalizeSpecs(specs) {
1669
+ const out = [];
1670
+ const names = /* @__PURE__ */ new Set();
1671
+ for (const spec of specs) {
1672
+ const n = typeof spec === "string" ? { name: spec, text: spec } : "text" in spec ? { name: spec.name, text: spec.text } : { name: spec.name, extract: spec.extract };
1673
+ if (n.name.trim().length === 0) throw new RangeError("pins\uFF1Aspec \u540D\u5B57\u4E0D\u80FD\u4E3A\u7A7A");
1674
+ if (names.has(n.name)) throw new RangeError(`pins\uFF1Aspec \u540D\u5B57\u91CD\u590D\uFF1A${JSON.stringify(n.name)}`);
1675
+ if (n.text !== void 0 && n.text.trim().length === 0) {
1676
+ throw new RangeError(`pins\uFF1A\u9759\u6001 pin ${JSON.stringify(n.name)} \u7684\u6587\u5B57\u4E0D\u80FD\u4E3A\u7A7A`);
1677
+ }
1678
+ if (n.extract !== void 0 && typeof n.extract !== "function") {
1679
+ throw new RangeError(`pins\uFF1Aspec ${JSON.stringify(n.name)} \u7684 extract \u5FC5\u987B\u662F\u51FD\u6570`);
1680
+ }
1681
+ names.add(n.name);
1682
+ out.push(n);
1683
+ }
1684
+ return out;
1685
+ }
1686
+ function pinDraft(text, meta, actor, extra) {
1687
+ const payload = { kind: "pin", text, meta: { pin: meta } };
1688
+ if (extra.supersedes !== void 0) payload.supersedes = [extra.supersedes];
1689
+ const draft = {
1690
+ type: "core.system_note",
1691
+ actor,
1692
+ payload,
1693
+ provenance: extra.provenanceRef !== void 0 ? { source: PINS_SOCKET_NAME, ref: extra.provenanceRef } : { source: PINS_SOCKET_NAME }
1694
+ };
1695
+ if (extra.parentId !== void 0) draft.parentId = extra.parentId;
1696
+ return draft;
1697
+ }
1698
+ function replaceResult3(result, text, isError) {
1699
+ return { ...result, payload: { ...result.payload, content: [{ type: "text", text }], isError } };
1700
+ }
1701
+ var PLACEHOLDER3 = `The ${PIN_TOOL_NAME} tool is present but its Socket is not installed; nothing was pinned.`;
1702
+ function pins(opts = {}) {
1703
+ const specs = normalizeSpecs(opts.pins ?? []);
1704
+ const withTool = opts.tool ?? true;
1705
+ const maxTextLength = opts.maxTextLength ?? DEFAULT_MAX_PIN_TEXT_LENGTH;
1706
+ if (!Number.isInteger(maxTextLength) || maxTextLength < 1) {
1707
+ throw new RangeError(`pins.maxTextLength \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(maxTextLength)}`);
1708
+ }
1709
+ const tolerance = opts.overshootTolerance ?? DEFAULT_PIN_OVERSHOOT_TOLERANCE;
1710
+ if (!(tolerance >= 0 && tolerance < 1)) {
1711
+ throw new RangeError(`pins.overshootTolerance \u5FC5\u987B\u5728 [0, 1) \u5185\uFF1A${String(tolerance)}`);
1712
+ }
1713
+ if (specs.length === 0 && !withTool) {
1714
+ throw new RangeError("pins\uFF1A\u65E2\u6CA1\u6709\u5BBF\u4E3B pin \u4E5F\u4E0D\u7ED9\u6A21\u578B\u5DE5\u5177\uFF0C\u8FD9\u4E2A Socket \u4EC0\u4E48\u90FD\u4E0D\u505A");
1715
+ }
1716
+ const tool = {
1717
+ name: PIN_TOOL_NAME,
1718
+ description: pinToolDescription(maxTextLength),
1719
+ inputSchema: pinInputSchema(maxTextLength),
1720
+ validate: (raw) => parsePinArgs(raw, maxTextLength, tolerance),
1721
+ risk: "low",
1722
+ execute: () => PLACEHOLDER3
1723
+ };
1724
+ const socket = {
1725
+ name: PINS_SOCKET_NAME,
1726
+ beforeModel(ctx) {
1727
+ for (const spec of specs) {
1728
+ const raw = spec.text ?? spec.extract?.(ctx);
1729
+ const text = raw?.trim();
1730
+ if (!text) continue;
1731
+ const visible = lastHostPin(ctx.events, spec.name);
1732
+ if (visible?.payload.text === text) continue;
1733
+ const previous = lastHostPin(ctx.timeline, spec.name);
1734
+ const extra = { provenanceRef: spec.name };
1735
+ if (previous) extra.supersedes = previous.id;
1736
+ ctx.emit(pinDraft(text, { source: "host", spec: spec.name }, "system", extra));
1737
+ }
1738
+ return void 0;
1739
+ },
1740
+ afterTool(ctx, call, result) {
1741
+ if (!withTool || call.payload.name !== PIN_TOOL_NAME || result.payload.isError) return void 0;
1742
+ let args;
1743
+ try {
1744
+ args = parsePinArgs(call.payload.args, maxTextLength, tolerance);
1745
+ } catch (err) {
1746
+ return replaceResult3(result, err instanceof Error ? err.message : String(err), true);
1747
+ }
1748
+ let replaced;
1749
+ if (args.replaces !== void 0) {
1750
+ replaced = findModelPin(ctx.events, args.replaces);
1751
+ if (!replaced) {
1752
+ const hostHit = ctx.events.find(
1753
+ (e) => isPinNoteEvent(e) && e.payload.text === args.replaces && pinMetaOf(e)?.source === "host"
1754
+ );
1755
+ return replaceResult3(
1756
+ result,
1757
+ hostHit ? "That note was pinned by the host and cannot be replaced." : "No note pinned by you matches `replaces` exactly. Check the visible pinned notes and pass the text verbatim.",
1758
+ true
1759
+ );
1760
+ }
1761
+ if (replaced.payload.text === args.text) {
1762
+ return replaceResult3(
1763
+ result,
1764
+ "That note is already pinned with the same text; nothing changed.",
1765
+ false
1766
+ );
1767
+ }
1768
+ } else if (findModelPin(ctx.events, args.text)) {
1769
+ return replaceResult3(result, "Already pinned; nothing changed.", false);
1770
+ }
1771
+ const extra = {
1772
+ parentId: call.id,
1773
+ provenanceRef: call.payload.toolCallId
1774
+ };
1775
+ if (replaced) extra.supersedes = replaced.id;
1776
+ ctx.emit(pinDraft(args.text, { source: "model" }, "model", extra));
1777
+ return replaceResult3(
1778
+ result,
1779
+ replaced ? "Pinned, replacing the earlier note. The old note will not survive the next compaction." : "Pinned. This note will survive compaction verbatim until you replace it.",
1780
+ false
1781
+ );
1782
+ }
1783
+ };
1784
+ if (withTool) socket.tools = [tool];
1785
+ if (withTool && opts.rules !== false) socket.systemPrompt = opts.rules ?? PIN_RULES;
1786
+ return socket;
1787
+ }
1788
+
1789
+ // src/skills/frontmatter.ts
1790
+ var MAX_SKILL_DESCRIPTION_CHARS = 1024;
1791
+ function unquote(v) {
1792
+ if (v.length >= 2) {
1793
+ const a = v[0];
1794
+ const b = v[v.length - 1];
1795
+ if (a === '"' && b === '"' || a === "'" && b === "'") return v.slice(1, -1);
1796
+ }
1797
+ return v;
1798
+ }
1799
+ function stripInlineComment(v) {
1800
+ if (/^["'].*["']$/.test(v)) return v;
1801
+ const m = /\s#/.exec(v);
1802
+ return m ? v.slice(0, m.index).trimEnd() : v;
1803
+ }
1804
+ function parseSkillMarkdown(content) {
1805
+ let text = content.replace(/\r\n/g, "\n");
1806
+ if (text.charCodeAt(0) === 65279) text = text.slice(1);
1807
+ if (!text.startsWith("---\n"))
1808
+ return { ok: false, reason: "SKILL.md must start with a `---` frontmatter block" };
1809
+ const closeAt = text.indexOf("\n---", 3);
1810
+ if (closeAt === -1) return { ok: false, reason: "frontmatter is not closed with a `---` line" };
1811
+ const afterClose = closeAt + 4;
1812
+ if (afterClose < text.length && text[afterClose] !== "\n") {
1813
+ return { ok: false, reason: "frontmatter is not closed with a `---` line" };
1814
+ }
1815
+ const header = text.slice(4, closeAt);
1816
+ const body = text.slice(Math.min(text.length, afterClose + 1));
1817
+ const fields = /* @__PURE__ */ new Map();
1818
+ const lines = header.split("\n");
1819
+ for (let i = 0; i < lines.length; i++) {
1820
+ const line = lines[i];
1821
+ if (line.trim().length === 0 || line.trimStart().startsWith("#")) continue;
1822
+ if (/^\s/.test(line)) continue;
1823
+ const colon = line.indexOf(":");
1824
+ if (colon <= 0) continue;
1825
+ const key = line.slice(0, colon).trim();
1826
+ const rawValue = stripInlineComment(line.slice(colon + 1).trim());
1827
+ if (rawValue === ">" || rawValue === "|" || rawValue === ">-" || rawValue === "|-") {
1828
+ const parts = [];
1829
+ while (i + 1 < lines.length && (/^\s/.test(lines[i + 1]) || lines[i + 1].trim() === "")) {
1830
+ i++;
1831
+ parts.push(lines[i].trim());
1832
+ }
1833
+ while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
1834
+ fields.set(key, rawValue.startsWith(">") ? parts.join(" ") : parts.join("\n"));
1835
+ continue;
1836
+ }
1837
+ fields.set(key, unquote(rawValue));
1838
+ }
1839
+ const name = fields.get("name");
1840
+ if (name === void 0 || name.length === 0) return { ok: false, reason: "frontmatter has no `name`" };
1841
+ if (!SKILL_NAME_RE.test(name)) {
1842
+ return {
1843
+ ok: false,
1844
+ reason: `\`name\` ${JSON.stringify(name)} must match ${SKILL_NAME_RE.source} (lowercase letters, digits, hyphens; at most 64 characters)`
1845
+ };
1846
+ }
1847
+ const description = fields.get("description");
1848
+ if (description === void 0 || description.length === 0) {
1849
+ return { ok: false, reason: "frontmatter has no `description`" };
1850
+ }
1851
+ if (description.length > MAX_SKILL_DESCRIPTION_CHARS) {
1852
+ return {
1853
+ ok: false,
1854
+ reason: `\`description\` is ${description.length} characters; at most ${MAX_SKILL_DESCRIPTION_CHARS} allowed`
1855
+ };
1856
+ }
1857
+ return { ok: true, skill: { name, description, body } };
1858
+ }
1859
+
1860
+ // src/skills/inline.ts
1861
+ function inlineSkills(skills2, opts = {}) {
1862
+ const root = opts.root ?? DEFAULT_SKILLS_ROOT;
1863
+ const files = /* @__PURE__ */ new Map();
1864
+ for (const [name, skill] of Object.entries(skills2)) {
1865
+ if (!SKILL_NAME_RE.test(name)) {
1866
+ throw new RangeError(
1867
+ `inlineSkills\uFF1A\u6280\u80FD\u952E ${JSON.stringify(name)} \u4E0D\u662F\u5408\u6CD5\u6280\u80FD\u540D\uFF08\u987B\u5339\u914D ${SKILL_NAME_RE.source}\uFF0C\u4E14\u4E0E SKILL.md \u5934\u90E8\u7684 name \u4E00\u81F4\uFF09`
1868
+ );
1869
+ }
1870
+ if (typeof skill === "string") {
1871
+ files.set(`${root}/${name}/${SKILL_FILE_NAME}`, skill);
1872
+ continue;
1873
+ }
1874
+ for (const [rel, content] of Object.entries(skill)) {
1875
+ const segments = rel.split("/").filter((s) => s.length > 0);
1876
+ if (segments.length === 0 || segments.some((s) => s === "." || s === "..")) {
1877
+ throw new RangeError(
1878
+ `inlineSkills\uFF1A\u6280\u80FD ${name} \u7684\u6587\u4EF6\u8DEF\u5F84 ${JSON.stringify(rel)} \u4E0D\u5408\u6CD5\uFF08\u76F8\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u542B . / ..\uFF09`
1879
+ );
1880
+ }
1881
+ files.set(`${root}/${name}/${segments.join("/")}`, content);
1882
+ }
1883
+ }
1884
+ return {
1885
+ async list(prefix) {
1886
+ return [...files.keys()].filter((k) => k.startsWith(prefix)).sort();
1887
+ },
1888
+ async read(path) {
1889
+ return files.get(path) ?? null;
1890
+ }
1891
+ };
1892
+ }
1893
+
1894
+ // src/skills/rules.ts
1895
+ var SKILL_READ_TOOL_NAME = "skill_read";
1896
+ var SKILL_READ_TOOL_DESCRIPTION = [
1897
+ "Read a skill: an instruction document the host prepared for a kind of task.",
1898
+ "`name` is the skill's name from the Skills list; `path` (default `SKILL.md`) selects a supporting file the skill refers to, relative to the skill's folder.",
1899
+ "Long files are shown from the top with line numbers and a note on how much is left; pass `range: [start_line, end_line]` (1-indexed, `end_line` -1 means to the end) to read the rest."
1900
+ ].join(" ");
1901
+ var SKILL_RULES = `## Skills
1902
+ Skills are instruction documents the host wrote for specific kinds of work. Each entry below is only a name and a one-line description; the instructions themselves are not loaded until you read them.
1903
+ - Before starting on a task a skill covers, read it with \`${SKILL_READ_TOOL_NAME}({ name })\` and follow it. Read a skill's supporting files (\`path\`) only when the skill points you to them.
1904
+ - A skill you have already read in this conversation stays in your context; do not read it again unless it has been folded away.
1905
+ - Do not guess what an unread skill says. If no skill fits the task, proceed without one.`;
1906
+ function renderSkillMenu(entries) {
1907
+ const lines = entries.map((e) => `- ${e.name}: ${e.description.replace(/\s*\n\s*/g, " ")}`);
1908
+ return `Available skills:
1909
+ ${lines.join("\n")}`;
1910
+ }
1911
+ var SKILL_READ_INPUT_SCHEMA = {
1912
+ type: "object",
1913
+ properties: {
1914
+ name: { type: "string", description: "The skill's name, exactly as listed under Skills." },
1915
+ path: {
1916
+ type: "string",
1917
+ description: "File to read inside the skill's folder, relative to it. Default SKILL.md."
1918
+ },
1919
+ range: {
1920
+ type: "array",
1921
+ items: { type: "integer" },
1922
+ minItems: 2,
1923
+ maxItems: 2,
1924
+ description: "[start_line, end_line], 1-indexed and inclusive; end_line -1 means to the end of the file."
1925
+ }
1926
+ },
1927
+ required: ["name"],
1928
+ additionalProperties: false
1929
+ };
1930
+
1931
+ // src/skills/skills.ts
1932
+ var SKILLS_SOCKET_NAME = "skills";
1933
+ var DEFAULT_SKILL_READ_CHARS = 4e4;
1934
+ async function loadSkillMenu(source, root = DEFAULT_SKILLS_ROOT) {
1935
+ const prefix = `${root}/`;
1936
+ const keys = (await source.list(prefix)).filter((k) => k.startsWith(prefix));
1937
+ const skillFile = new RegExp(`^${escapeRegExp(prefix)}([^/]+)/${escapeRegExp(SKILL_FILE_NAME)}$`);
1938
+ const menu = { skills: [], rejected: [] };
1939
+ for (const key of keys) {
1940
+ const m = skillFile.exec(key);
1941
+ if (!m) continue;
1942
+ const dir = m[1];
1943
+ const content = await source.read(key);
1944
+ if (content === null) continue;
1945
+ const parsed = parseSkillMarkdown(content);
1946
+ if (!parsed.ok) {
1947
+ menu.rejected.push({ path: key, reason: parsed.reason });
1948
+ continue;
1949
+ }
1950
+ if (parsed.skill.name !== dir) {
1951
+ menu.rejected.push({
1952
+ path: key,
1953
+ reason: `frontmatter \`name\` ${JSON.stringify(parsed.skill.name)} does not match its folder ${JSON.stringify(dir)}`
1954
+ });
1955
+ continue;
1956
+ }
1957
+ menu.skills.push({ name: parsed.skill.name, description: parsed.skill.description, path: key });
1958
+ }
1959
+ menu.skills.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1960
+ return menu;
1961
+ }
1962
+ function parseSkillReadInput(raw, root = DEFAULT_SKILLS_ROOT) {
1963
+ if (typeof raw !== "object" || raw === null)
1964
+ throw new RangeError("skill_read expects an object with a `name`");
1965
+ const o = raw;
1966
+ if (typeof o.name !== "string" || !SKILL_NAME_RE.test(o.name)) {
1967
+ throw new RangeError("`name` must be a skill name exactly as listed under Skills");
1968
+ }
1969
+ const name = o.name;
1970
+ const skillRoot = `${root}/${name}`;
1971
+ let rel = SKILL_FILE_NAME;
1972
+ if (o.path !== void 0) {
1973
+ if (typeof o.path !== "string") throw new RangeError("`path` must be a string");
1974
+ const resolved = resolveRootedPath(`${skillRoot}/${o.path}`, skillRoot);
1975
+ if (resolved === skillRoot)
1976
+ throw new RangeError("`path` must name a file inside the skill, not the skill itself");
1977
+ rel = resolved.slice(skillRoot.length + 1);
1978
+ }
1979
+ const out = { name, path: rel };
1980
+ if (o.range !== void 0) {
1981
+ const r = o.range;
1982
+ if (!Array.isArray(r) || r.length !== 2 || !r.every((n) => Number.isInteger(n))) {
1983
+ throw new RangeError("`range` must be [start_line, end_line] with integer values");
1984
+ }
1985
+ const [start, end] = r;
1986
+ if (start < 1) throw new RangeError("`range` start_line must be \u2265 1");
1987
+ if (end !== -1 && end < start)
1988
+ throw new RangeError("`range` end_line must be \u2265 start_line, or -1 for the end");
1989
+ out.range = [start, end];
1990
+ }
1991
+ return out;
1992
+ }
1993
+ function assertSkillsRoot(root) {
1994
+ const segments = root.split("/");
1995
+ const bad = !root.startsWith("/") || segments.length < 2 || segments.slice(1).some((s) => s.length === 0 || s === "." || s === ".." || /\s/.test(s));
1996
+ if (bad) {
1997
+ throw new RangeError(
1998
+ `skills.root \u5FC5\u987B\u662F "/" \u8D77\u3001\u4E0D\u4EE5 "/" \u6536\u3001\u4E0D\u542B\u7A7A\u6BB5\u4E0E . / .. \u7684\u89C4\u8303\u8DEF\u5F84\uFF1A${JSON.stringify(root)}`
1999
+ );
2000
+ }
2001
+ if (root === MEMORY_ROOT || root.startsWith(`${MEMORY_ROOT}/`) || MEMORY_ROOT.startsWith(`${root}/`)) {
2002
+ throw new RangeError(
2003
+ `skills.root ${JSON.stringify(root)} \u4E0E\u8BB0\u5FC6\u6839 ${MEMORY_ROOT} \u91CD\u53E0\uFF1A\u6A21\u578B\u80FD\u7528 memory \u5DE5\u5177\u5199\u8FDB\u53BB\u7684\u4E1C\u897F\u4E0D\u80FD\u5F53\u6280\u80FD\uFF08system \u4FE1\u4EFB\uFF09`
2004
+ );
2005
+ }
2006
+ }
2007
+ function skills(opts = {}) {
2008
+ const root = opts.root ?? DEFAULT_SKILLS_ROOT;
2009
+ assertSkillsRoot(root);
2010
+ const maxReadChars = opts.maxReadChars ?? DEFAULT_SKILL_READ_CHARS;
2011
+ if (!Number.isInteger(maxReadChars) || maxReadChars < 1) {
2012
+ throw new RangeError(`skills.maxReadChars \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(maxReadChars)}`);
2013
+ }
2014
+ const source = opts.source;
2015
+ const warn = opts.warn ?? ((message) => console.warn(message));
2016
+ const warned = /* @__PURE__ */ new Set();
2017
+ const warnOnce = (key, message) => {
2018
+ if (warned.has(key)) return;
2019
+ warned.add(key);
2020
+ warn(message);
2021
+ };
2022
+ const menus = /* @__PURE__ */ new WeakMap();
2023
+ const menuFor = (setup) => {
2024
+ let p = menus.get(setup);
2025
+ if (!p) {
2026
+ p = (async () => {
2027
+ if (!source) {
2028
+ warnOnce(
2029
+ "no-source",
2030
+ "[reins/skills] \u6CA1\u6709\u7ED9 source\uFF0Cskill_read \u5DE5\u5177\u4E0E\u6280\u80FD\u83DC\u5355\u672A\u6CE8\u518C\u3002\u4F20 skills({ source }) \u5373\u53EF\u5F00\u542F\uFF08\u4EFB\u4F55 MemoryStore\u3001fsSkillSource\u3001inlineSkills \u90FD\u884C\uFF09\u3002"
2031
+ );
2032
+ return void 0;
2033
+ }
2034
+ if (setup.hostTools.some((t) => t.name === SKILL_READ_TOOL_NAME)) {
2035
+ warnOnce(
2036
+ "host-tool",
2037
+ `[reins/skills] \u5BBF\u4E3B\u5DE5\u5177\u8868\u91CC\u5DF2\u6709\u540C\u540D\u5DE5\u5177 ${SKILL_READ_TOOL_NAME}\uFF0C\u672C\u6A21\u5757\u7684\u5DE5\u5177\u4E0E\u83DC\u5355\u672A\u6CE8\u518C\u3002\u6362\u6389\u5BBF\u4E3B\u90A3\u4E2A\u5DE5\u5177\u7684\u540D\u5B57\u5373\u53EF\u3002`
2038
+ );
2039
+ return void 0;
2040
+ }
2041
+ const menu = await loadSkillMenu(source, root);
2042
+ for (const r of menu.rejected) {
2043
+ warnOnce(`rejected:${r.path}:${r.reason}`, `[reins/skills] \u8DF3\u8FC7\u4E0D\u5408\u89C4\u7684\u6280\u80FD ${r.path}\uFF1A${r.reason}`);
2044
+ }
2045
+ if (menu.skills.length === 0) {
2046
+ warnOnce(
2047
+ "empty",
2048
+ `[reins/skills] source \u5728 ${root}/ \u4E0B\u6CA1\u6709\u4EFB\u4F55\u5408\u89C4\u7684 SKILL.md\uFF0Cskill_read \u5DE5\u5177\u4E0E\u6280\u80FD\u83DC\u5355\u672A\u6CE8\u518C\u3002\u68C0\u67E5\uFF1A\u2460 \u8F7D\u4F53\u7684 root \u662F\u5426\u4E0E skills({ root }) \u4E00\u81F4\uFF08\u90FD\u7F3A\u7701 ${DEFAULT_SKILLS_ROOT}\uFF09\uFF1B\u2461 \u76EE\u5F55\u5E03\u5C40\u987B\u662F <root>/<name>/${SKILL_FILE_NAME}\uFF08fsSkillSource \u7684 dir \u6309 process.cwd() \u89E3\u6790\uFF0C\u6700\u597D\u4F20\u7EDD\u5BF9\u8DEF\u5F84\uFF09\uFF1B\u2462 \u5934\u90E8\u7684 name \u987B\u4E0E\u76EE\u5F55\u540D\u4E00\u81F4\u3002`
2049
+ );
2050
+ return void 0;
2051
+ }
2052
+ return menu;
2053
+ })();
2054
+ menus.set(setup, p);
2055
+ }
2056
+ return p;
2057
+ };
2058
+ const tool = {
2059
+ name: SKILL_READ_TOOL_NAME,
2060
+ description: SKILL_READ_TOOL_DESCRIPTION,
2061
+ inputSchema: SKILL_READ_INPUT_SCHEMA,
2062
+ validate: (raw) => parseSkillReadInput(raw, root),
2063
+ risk: "low",
2064
+ // 技能是宿主写的说明书,视同系统提示可信,不套 untrusted 标记(DECISIONS 2026-09-13)
2065
+ resultTrust: "system",
2066
+ // spill 永远不该把技能正文换成预览 + fetch_blob(那等于让模型再翻一次,且取回来的是 untrusted)。
2067
+ // 视图有硬上限(enforceLimit):正文 ≤ maxReadChars 字符 + 每行 7 个 ASCII 行号字符 + 一行表头 / 提示;
2068
+ // core 粗估 ASCII 4 字 1 token、非 ASCII 1 字 1 token,行数 ≤ maxReadChars / 2(每行至少一字加换行),
2069
+ // 所以 token 上界 = maxReadChars(正文全是非 ASCII 的最坏情形)+ 2 × (maxReadChars / 2)(行号)+ 表头 ≤ 2 × maxReadChars + 256。
2070
+ // 发前审查:此前按"token ≤ 字符"取 maxReadChars,中文技能会被外溢
2071
+ resultPolicy: { maxTokens: 2 * maxReadChars + 256, overflow: "spill" },
2072
+ async execute(input) {
2073
+ if (!source) {
2074
+ return {
2075
+ content: [{ type: "text", text: "No skill source is configured; skills are unavailable." }],
2076
+ isError: true
2077
+ };
2078
+ }
2079
+ const key = `${root}/${input.name}/${input.path}`;
2080
+ let content;
2081
+ try {
2082
+ content = await source.read(key);
2083
+ } catch (err) {
2084
+ warnOnce(`read-failed:${String(err)}`, `[reins/skills] \u8BFB\u53D6 ${key} \u5931\u8D25\uFF1A${String(err)}`);
2085
+ return {
2086
+ content: [
2087
+ { type: "text", text: `Skill file ${input.name}/${input.path} could not be read right now.` }
2088
+ ],
2089
+ isError: true
2090
+ };
2091
+ }
2092
+ if (content === null) {
2093
+ return {
2094
+ content: [{ type: "text", text: `Skill file ${input.name}/${input.path} does not exist.` }],
2095
+ isError: true
2096
+ };
2097
+ }
2098
+ const view2 = formatFileView(`${input.name}/${input.path}`, content, {
2099
+ range: input.range,
2100
+ maxChars: maxReadChars,
2101
+ rangeField: "range",
2102
+ enforceLimit: true
2103
+ });
2104
+ if (view2.error !== void 0) return { content: [{ type: "text", text: view2.error }], isError: true };
2105
+ return { content: [{ type: "text", text: view2.text }] };
2106
+ }
2107
+ };
2108
+ const socket = {
2109
+ name: SKILLS_SOCKET_NAME,
2110
+ tools: async (setup) => await menuFor(setup) ? [tool] : void 0
2111
+ };
2112
+ if (opts.rules !== false) {
2113
+ const rules = opts.rules ?? SKILL_RULES;
2114
+ socket.systemPrompt = async (setup) => {
2115
+ const menu = await menuFor(setup);
2116
+ return menu ? `${rules}
2117
+
2118
+ ${renderSkillMenu(menu.skills)}` : void 0;
2119
+ };
2120
+ }
2121
+ return socket;
2122
+ }
2123
+ function escapeRegExp(s) {
2124
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2125
+ }
2126
+
2127
+ // src/spill/preview.ts
2128
+ import { estimateTextTokens } from "@reinsjs/core";
2129
+ var defaultTextTokens = estimateTextTokens;
2130
+ function measureText(text, estimate = defaultTextTokens) {
2131
+ return { chars: text.length, lines: countLines(text), tokens: estimate(text) };
2132
+ }
2133
+ function countLines(text) {
2134
+ if (text.length === 0) return 0;
2135
+ let n = 1;
2136
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
2137
+ if (text.charCodeAt(text.length - 1) === 10) n--;
2138
+ return n;
2139
+ }
2140
+ function clipEndByTokens(text, maxTokens) {
2141
+ let ascii = 0;
2142
+ let other = 0;
2143
+ for (let i = 0; i < text.length; i++) {
2144
+ if (text.charCodeAt(i) < 128) ascii++;
2145
+ else other++;
2146
+ if (Math.ceil(ascii / 4) + other > maxTokens) return i;
2147
+ }
2148
+ return text.length;
2149
+ }
2150
+ function offsetAfterLines(text, n) {
2151
+ let pos = 0;
2152
+ for (let i = 0; i < n; i++) {
2153
+ const nl = text.indexOf("\n", pos);
2154
+ if (nl < 0) return text.length;
2155
+ pos = nl + 1;
2156
+ }
2157
+ return pos;
2158
+ }
2159
+ function offsetBeforeLastLines(text, n) {
2160
+ let pos = text.length > 0 && text.charCodeAt(text.length - 1) === 10 ? text.length - 1 : text.length;
2161
+ for (let i = 0; i < n; i++) {
2162
+ const nl = text.lastIndexOf("\n", pos - 1);
2163
+ if (nl < 0) return 0;
2164
+ pos = nl;
2165
+ }
2166
+ return pos < text.length ? pos + 1 : pos;
2167
+ }
2168
+ function previewOf(text, opts) {
2169
+ const headEnd = Math.min(offsetAfterLines(text, opts.lines), opts.chars);
2170
+ const tailStart = Math.max(offsetBeforeLastLines(text, opts.lines), text.length - opts.chars);
2171
+ if (tailStart <= headEnd) {
2172
+ return { head: text, tail: "", omitted: { chars: 0, lines: 0 } };
2173
+ }
2174
+ const middle = text.slice(headEnd, tailStart);
2175
+ return {
2176
+ head: text.slice(0, headEnd),
2177
+ tail: text.slice(tailStart),
2178
+ omitted: { chars: middle.length, lines: countLines(middle) }
2179
+ };
2180
+ }
2181
+ function fmt(n) {
2182
+ return n.toLocaleString("en-US");
2183
+ }
2184
+
2185
+ // src/spill/spill.ts
2186
+ import {
2187
+ StoreError
2188
+ } from "@reinsjs/core";
2189
+ var SPILL_SOCKET_NAME = "spill";
2190
+ var DEFAULT_MAX_RESULT_TOKENS = 16e3;
2191
+ var DEFAULT_PREVIEW_LINES = 20;
2192
+ var DEFAULT_PREVIEW_CHARS = 2e3;
2193
+ var SPILL_BLOB_MIME = "text/plain; charset=utf-8";
2194
+ var FETCH_BLOB_INPUT_SCHEMA = {
2195
+ type: "object",
2196
+ properties: {
2197
+ id: { type: "string", description: "The blob id shown in the tool result preview." },
2198
+ start: {
2199
+ type: "integer",
2200
+ minimum: 0,
2201
+ description: "0-based character offset to start from. Omit to start at the beginning."
2202
+ },
2203
+ end: {
2204
+ type: "integer",
2205
+ minimum: 1,
2206
+ description: "Character offset to stop before (exclusive). Omit to read as much as fits."
2207
+ }
2208
+ },
2209
+ required: ["id"],
2210
+ additionalProperties: false
2211
+ };
2212
+ function parseFetchBlobArgs(raw) {
2213
+ if (typeof raw !== "object" || raw === null)
2214
+ throw new RangeError(`${FETCH_BLOB_TOOL_NAME} expects an object`);
2215
+ const o = raw;
2216
+ if (typeof o.id !== "string" || o.id.trim().length === 0)
2217
+ throw new RangeError("`id` must be a non-empty string");
2218
+ const out = { id: o.id.trim() };
2219
+ if (o.start !== void 0) {
2220
+ if (!Number.isInteger(o.start) || o.start < 0)
2221
+ throw new RangeError("`start` must be an integer \u2265 0");
2222
+ out.start = o.start;
2223
+ }
2224
+ if (o.end !== void 0) {
2225
+ if (!Number.isInteger(o.end) || o.end < 1)
2226
+ throw new RangeError("`end` must be an integer \u2265 1");
2227
+ out.end = o.end;
2228
+ }
2229
+ if (out.start !== void 0 && out.end !== void 0 && out.end <= out.start) {
2230
+ throw new RangeError("`end` must be greater than `start`");
2231
+ }
2232
+ return out;
2233
+ }
2234
+ function isTextMime(mime) {
2235
+ const m = mime.toLowerCase().split(";")[0]?.trim() ?? "";
2236
+ if (m.startsWith("text/")) return true;
2237
+ if (/^application\/(json|xml|yaml|x-yaml|javascript|x-ndjson|ld\+json)$/.test(m)) return true;
2238
+ return m.endsWith("+json") || m.endsWith("+xml");
2239
+ }
2240
+ function splitContent(content) {
2241
+ const texts = [];
2242
+ const rest = [];
2243
+ for (const p of content) {
2244
+ if (p.type === "text") texts.push(p.text);
2245
+ else rest.push(p);
2246
+ }
2247
+ return { text: texts.join("\n\n"), rest };
2248
+ }
2249
+ function renderPreview(preview) {
2250
+ if (preview.tail.length === 0) return preview.head;
2251
+ const head = preview.head.endsWith("\n") ? preview.head : `${preview.head}
2252
+ `;
2253
+ return `${head}[... ${fmt(preview.omitted.chars)} characters (${fmt(preview.omitted.lines)} lines) omitted ...]
2254
+ ${preview.tail}`;
2255
+ }
2256
+ function spill(opts = {}) {
2257
+ const maxTokens = opts.maxResultTokens ?? DEFAULT_MAX_RESULT_TOKENS;
2258
+ if (!Number.isInteger(maxTokens) || maxTokens < 1) {
2259
+ throw new RangeError(`spill.maxResultTokens \u5FC5\u987B\u662F \u22651 \u7684\u6574\u6570\uFF1A${String(maxTokens)}`);
2260
+ }
2261
+ const previewLines = opts.previewLines ?? DEFAULT_PREVIEW_LINES;
2262
+ if (!Number.isInteger(previewLines) || previewLines < 0) {
2263
+ throw new RangeError(`spill.previewLines \u5FC5\u987B\u662F \u22650 \u7684\u6574\u6570\uFF1A${String(previewLines)}`);
2264
+ }
2265
+ const previewChars = opts.previewChars ?? Math.min(DEFAULT_PREVIEW_CHARS, Math.floor(maxTokens / 4));
2266
+ if (!Number.isInteger(previewChars) || previewChars < 0) {
2267
+ throw new RangeError(`spill.previewChars \u5FC5\u987B\u662F \u22650 \u7684\u6574\u6570\uFF1A${String(previewChars)}`);
2268
+ }
2269
+ const estimate = opts.estimate ?? defaultTextTokens;
2270
+ const withTool = opts.tool ?? true;
2271
+ const warn = opts.warn ?? ((message) => console.warn(message));
2272
+ let warnedNoBlobs = false;
2273
+ const limitFor = (tool) => ({
2274
+ maxTokens: tool?.resultPolicy?.maxTokens ?? maxTokens,
2275
+ overflow: tool?.resultPolicy?.overflow ?? "spill"
2276
+ });
2277
+ const fetchBlob = {
2278
+ name: FETCH_BLOB_TOOL_NAME,
2279
+ description: FETCH_BLOB_TOOL_DESCRIPTION,
2280
+ inputSchema: FETCH_BLOB_INPUT_SCHEMA,
2281
+ validate: parseFetchBlobArgs,
2282
+ risk: "low",
2283
+ execute: (args, ctx) => readBlobSlice(args, ctx, maxTokens)
2284
+ };
2285
+ const socket = {
2286
+ name: SPILL_SOCKET_NAME,
2287
+ async afterTool(ctx, call, result) {
2288
+ const name = call.payload.name;
2289
+ if (name === FETCH_BLOB_TOOL_NAME) return void 0;
2290
+ const policy = limitFor(ctx.tools.find((t) => t.name === name));
2291
+ const { text, rest } = splitContent(result.payload.content);
2292
+ const measure = measureText(text, estimate);
2293
+ if (measure.tokens <= policy.maxTokens) return void 0;
2294
+ const preview = previewOf(text, { lines: previewLines, chars: previewChars });
2295
+ const size = `~${fmt(measure.tokens)} tokens (${fmt(measure.chars)} characters, ${fmt(measure.lines)} lines)`;
2296
+ const shown = preview.tail.length === 0 ? "The preview below is the beginning of the output." : `Below: the first ${previewLines} lines and the last ${previewLines} lines.`;
2297
+ if (policy.overflow === "truncate") {
2298
+ const header2 = `[Output of \`${name}\` was truncated: ${size} exceeds the inline limit of ${fmt(policy.maxTokens)} tokens, and this tool is configured to truncate rather than store the full output, so the omitted middle cannot be recovered. ${shown}]`;
2299
+ return replaceContent(result, [
2300
+ { type: "text", text: `${header2}
2301
+ ${renderPreview(preview)}` },
2302
+ ...rest
2303
+ ]);
2304
+ }
2305
+ if (!ctx.blobs) {
2306
+ if (!warnedNoBlobs) {
2307
+ warnedNoBlobs = true;
2308
+ warn(
2309
+ `[reins/spill] \u6CA1\u6709\u914D\u7F6E BlobStore\uFF0C\u7ED3\u679C\u5916\u6EA2\u5DF2\u5173\u95ED\uFF1A\`${name}\` \u8FD4\u56DE\u4E86 ${size}\uFF0C\u5C06\u539F\u6837\u8FDB\u5165\u4E0A\u4E0B\u6587\u3002\u7ED9 runLoop / createAgent \u914D\u4E0A blobs \u5373\u53EF\u5F00\u542F\u3002`
2310
+ );
2311
+ }
2312
+ return void 0;
2313
+ }
2314
+ const { id } = await ctx.blobs.put(text, { mime: SPILL_BLOB_MIME, sessionId: ctx.session.id });
2315
+ const firstSliceEnd = clipEndByTokens(text, policy.maxTokens);
2316
+ const header = `[Output of \`${name}\` is too large to show inline: ${size}; the inline limit is ${fmt(policy.maxTokens)} tokens. The complete output is stored verbatim as blob "${id}". Read it with ${FETCH_BLOB_TOOL_NAME}({ id: "${id}", start: 0, end: ${fmt(firstSliceEnd).replace(/,/g, "")} }); offsets are characters, and the header of each fetch tells you where to continue. ${shown}]`;
2317
+ const summary = `${size} from \`${name}\`, stored as blob ${id}`;
2318
+ return {
2319
+ ...result,
2320
+ payload: {
2321
+ ...result.payload,
2322
+ content: [{ type: "text", text: `${header}
2323
+ ${renderPreview(preview)}` }, ...rest],
2324
+ spilled: { blobId: id, summary }
2325
+ }
2326
+ };
2327
+ }
2328
+ };
2329
+ if (withTool) socket.tools = [fetchBlob];
2330
+ if (withTool && opts.rules !== false) socket.systemPrompt = opts.rules ?? SPILL_RULES;
2331
+ return socket;
2332
+ }
2333
+ function replaceContent(result, content) {
2334
+ return { ...result, payload: { ...result.payload, content } };
2335
+ }
2336
+ var fail3 = (text) => ({ content: [{ type: "text", text }], isError: true });
2337
+ async function readBlobSlice(args, ctx, maxTokens) {
2338
+ if (!ctx.blobs)
2339
+ return fail3("No blob store is configured for this session, so stored outputs cannot be read.");
2340
+ if (!await referencedHere(ctx, args.id)) return fail3(`No blob with id "${args.id}" in this session.`);
2341
+ const blob = await loadReferencedBlob(ctx.blobs, args.id);
2342
+ if (!blob) return fail3(`No blob with id "${args.id}" in this session.`);
2343
+ if (!isTextMime(blob.mime)) {
2344
+ return fail3(
2345
+ `Blob "${args.id}" is ${blob.mime} (${fmt(blob.size)} bytes), not text; it cannot be shown inline.`
2346
+ );
2347
+ }
2348
+ const text = new TextDecoder("utf-8").decode(blob.bytes);
2349
+ const total = text.length;
2350
+ const start = args.start ?? 0;
2351
+ if (start >= total) {
2352
+ return fail3(
2353
+ `start ${fmt(start)} is at or beyond the end of blob "${args.id}" (${fmt(total)} characters).`
2354
+ );
2355
+ }
2356
+ const requestedEnd = Math.min(args.end ?? total, total);
2357
+ const requested = text.slice(start, requestedEnd);
2358
+ const clipAt = clipEndByTokens(requested, maxTokens);
2359
+ const clipped = clipAt < requested.length;
2360
+ const slice = clipped ? requested.slice(0, clipAt) : requested;
2361
+ const shownEnd = start + slice.length;
2362
+ const lines = measureText(text).lines;
2363
+ const next = shownEnd < total ? `Continue with start: ${fmt(shownEnd).replace(/,/g, "")}.` : "This is the end of the output.";
2364
+ const header = `[blob "${args.id}": characters ${fmt(start)}\u2013${fmt(shownEnd)} of ${fmt(total)} (${fmt(lines)} lines total)${clipped ? `; clipped to fit ${fmt(maxTokens)} tokens` : ""}. ${next}]`;
2365
+ return { content: [{ type: "text", text: `${header}
2366
+ ${slice}` }], isError: false };
2367
+ }
2368
+ async function referencedHere(ctx, id) {
2369
+ for await (const e of ctx.log.read(ctx.sessionId)) {
2370
+ if (e.type !== "core.tool_result") continue;
2371
+ const spilled = e.payload.spilled;
2372
+ if (spilled?.blobId === id) return true;
2373
+ }
2374
+ return false;
2375
+ }
2376
+ async function loadReferencedBlob(blobs, id) {
2377
+ try {
2378
+ const { bytes, meta } = await blobs.get(id);
2379
+ return { bytes, mime: meta.mime, size: meta.size };
2380
+ } catch (err) {
2381
+ if (err instanceof StoreError && err.code === "not_found") return void 0;
2382
+ throw err;
2383
+ }
2384
+ }
2385
+ export {
2386
+ APPROVAL_POLICY_IDS,
2387
+ APPROVAL_RULES,
2388
+ APPROVAL_SOCKET_NAME,
2389
+ BUDGET_SOCKET_NAME,
2390
+ COMPACT_INPUT_SCHEMA,
2391
+ COMPACT_RULES,
2392
+ COMPACT_SOCKET_NAME,
2393
+ COMPACT_TOOL_DESCRIPTION,
2394
+ COMPACT_TOOL_NAME,
2395
+ DEFAULT_HANDOFF_REASON,
2396
+ DEFAULT_MAX_CONSECUTIVE_COMPACTIONS,
2397
+ DEFAULT_MAX_FILE_BYTES,
2398
+ DEFAULT_MAX_PIN_TEXT_LENGTH,
2399
+ DEFAULT_MAX_RESULT_TOKENS,
2400
+ DEFAULT_MAX_SUMMARY_CHARS,
2401
+ DEFAULT_MAX_VIEW_CHARS,
2402
+ DEFAULT_PERCEPTION_THRESHOLDS,
2403
+ DEFAULT_PIN_OVERSHOOT_TOLERANCE,
2404
+ DEFAULT_PREVIEW_CHARS,
2405
+ DEFAULT_PREVIEW_LINES,
2406
+ DEFAULT_SKILLS_ROOT,
2407
+ DEFAULT_SKILL_READ_CHARS,
2408
+ FETCH_BLOB_INPUT_SCHEMA,
2409
+ FETCH_BLOB_TOOL_DESCRIPTION,
2410
+ FETCH_BLOB_TOOL_NAME,
2411
+ HANDOFF_INPUT_SCHEMA,
2412
+ HANDOFF_RULES,
2413
+ HANDOFF_SOCKET_NAME,
2414
+ HANDOFF_TOOL_DESCRIPTION,
2415
+ HANDOFF_TOOL_NAME,
2416
+ MANIFEST_DEFAULT_EXCLUDE,
2417
+ MANIFEST_HEADING,
2418
+ MAX_MEMORY_PATH_LENGTH,
2419
+ MAX_SKILL_DESCRIPTION_CHARS,
2420
+ MEMORY_COMMANDS,
2421
+ MEMORY_INPUT_SCHEMA,
2422
+ MEMORY_ROOT,
2423
+ MEMORY_RULES,
2424
+ MEMORY_SOCKET_NAME,
2425
+ MEMORY_TOOL_DESCRIPTION,
2426
+ MEMORY_TOOL_NAME,
2427
+ PERCEPTION_SOCKET_NAME,
2428
+ PINS_SOCKET_NAME,
2429
+ PIN_INPUT_SCHEMA,
2430
+ PIN_RULES,
2431
+ PIN_TOOL_DESCRIPTION,
2432
+ PIN_TOOL_NAME,
2433
+ RECALL_INPUT_SCHEMA,
2434
+ RECALL_TOOL_DESCRIPTION,
2435
+ RECALL_TOOL_NAME,
2436
+ SKILLS_SOCKET_NAME,
2437
+ SKILL_FILE_NAME,
2438
+ SKILL_NAME_RE,
2439
+ SKILL_READ_INPUT_SCHEMA,
2440
+ SKILL_READ_TOOL_DESCRIPTION,
2441
+ SKILL_READ_TOOL_NAME,
2442
+ SKILL_RULES,
2443
+ SPILL_BLOB_MIME,
2444
+ SPILL_RULES,
2445
+ SPILL_SOCKET_NAME,
2446
+ approval,
2447
+ assertAscending,
2448
+ assertLimits,
2449
+ assertSkillsRoot,
2450
+ bindMemoryFs,
2451
+ budget,
2452
+ budgetUsedOf,
2453
+ byteLength,
2454
+ carriedPins,
2455
+ checkBudget,
2456
+ clipEndByTokens,
2457
+ compact,
2458
+ compactNumber,
2459
+ composeHandoffNote,
2460
+ contextOverheadOf,
2461
+ countLines,
2462
+ countModelTurns,
2463
+ countTier,
2464
+ defaultBudgetNote,
2465
+ defaultSummary,
2466
+ defaultTextTokens,
2467
+ evaluatePolicy,
2468
+ executeMemoryCommand,
2469
+ findModelPin,
2470
+ fmt,
2471
+ globToRegExp,
2472
+ handoff,
2473
+ humanSize,
2474
+ inlineSkills,
2475
+ isModelCompaction,
2476
+ isPinNoteEvent,
2477
+ isTextMime,
2478
+ isUnder,
2479
+ lastHostPin,
2480
+ lastVisiblePerceptionNote,
2481
+ lastVisibleUserMessage,
2482
+ loadSkillMenu,
2483
+ measureText,
2484
+ memory,
2485
+ normalizeRule,
2486
+ parseCompactArgs,
2487
+ parseFetchBlobArgs,
2488
+ parseHandoffArgs,
2489
+ parseMemoryCommand,
2490
+ parsePinArgs,
2491
+ parseRecallArgs,
2492
+ parseSkillMarkdown,
2493
+ parseSkillReadInput,
2494
+ percent,
2495
+ perception,
2496
+ pinInputSchema,
2497
+ pinMetaOf,
2498
+ pinToolDescription,
2499
+ pins,
2500
+ planCompaction,
2501
+ previewOf,
2502
+ rangeTier,
2503
+ readPerception,
2504
+ recallResult,
2505
+ recallTool,
2506
+ renderCompactionSummary,
2507
+ renderPerception,
2508
+ renderSkillMenu,
2509
+ resolveMemoryPath,
2510
+ segmentTimelineByTurn,
2511
+ skills,
2512
+ spill,
2513
+ sumSessionTokens,
2514
+ trailingCompactionRun,
2515
+ unfinishedHandoffArgs
2516
+ };
2517
+ //# sourceMappingURL=index.js.map