@reinsjs/brain 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @reinsjs/brain
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 54fed37: Sockets can now see the current tool batch. `TurnContext.batch` (`ToolBatch`) lists the batch's tool calls, the results logged so far (in `beforeTool`, only those of earlier calls), the ids left waiting for approval, a client result or a paused sub-agent, and `resumed` when the batch is one a previous run left unfinished. It is one object updated in place during the turn. core also exports `ToolResultEvent` and `toolBatchOf(timeline, pending)`, which locates the batch of leftover calls. **`batch` is a required field**: a host that builds `TurnContext` objects itself (for example in socket unit tests) or runs its own copy of `runLoop` must fill it.
8
+
9
+ brain adds two opt-in sockets. `haltOnFailure({ counts?, applies? })` holds back the later calls of a batch once an earlier one failed or is still waiting: each gets an error result naming that call, and nothing runs. Register it first. `stopAfter({ tools })` ends the run (`done`) at the end of a turn in which the model successfully called one of `tools`, when nothing else in the batch failed or is pending. A batch resumed after an approval also ends the run, unless the resumed run brought new user input. Register it after `handoff()` and before `compact()` / `budget()`.
10
+
11
+ adapter-tanstack-ai fills `ctx.batch`. Because the engine checks a whole batch before running any of it, `beforeTool` sees no results from the same batch and `held` stays empty. A resumed batch gets no `onTurnEnd` on this path.
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [54fed37]
16
+ - @reinsjs/core@0.8.0
17
+
3
18
  ## 0.7.3
4
19
 
5
20
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @reinsjs/brain
2
2
 
3
- Pre-packaged driving experience for [reins](../../README.md) agents: ten `Socket` modules that make a model good at long tasks — seeing its own context, tidying it, keeping constraints, spilling large results, handing off, remembering, asking before dangerous actions, stopping at a budget, reading the host's skills when a task calls for them, and loading tools from a large table only when it needs them. Each module is optional, individually configurable, and only depends on the contracts in `@reinsjs/core`. None of them decides *for* the model; they let it see, give it means, set bounds, and leave a record.
3
+ Pre-packaged driving experience for [reins](../../README.md) agents: twelve `Socket` modules that make a model good at long tasks — seeing its own context, tidying it, keeping constraints, spilling large results, handing off, remembering, asking before dangerous actions, stopping at a budget, reading the host's skills when a task calls for them, loading tools from a large table only when it needs them, holding back the rest of a batch when an earlier call failed, and ending a run when the model calls its wrap-up tool. Each module is optional, individually configurable, and only depends on the contracts in `@reinsjs/core`. None of them decides *for* the model; they let it see, give it means, set bounds, and leave a record.
4
4
 
5
5
  ```bash
6
6
  pnpm add @reinsjs/brain
@@ -44,6 +44,25 @@ const agent = createAgent({
44
44
  | `budget()` | Five limits — `contextTokens`, `totalTokens`, `turns`, `toolCalls`, `wallMs` — checked in `onTurnEnd`. Hitting one while the model wants to continue pauses the run with `reason: "budget"`; resuming starts a fresh run budget. `totalTokens` includes what sub-agents spent through `asTool`. | nothing |
45
45
  | `skills()` | [Agent Skills](https://agentskills.io) with progressive disclosure: the system prompt carries only a menu (each `SKILL.md`'s `name` + `description`); the model reads a skill, or one of its supporting files, with `skill_read({ name, path?, range? })`, and the text lands in the timeline as a `tool_result` — so compaction, `recall` and spill apply to it unchanged. Skills are host-authored, so `skill_read` results are trusted like the system prompt (no `<untrusted>` marker). Skills that fail the spec (bad `name`, missing `description`) are skipped with one warning; no `source`, no valid skill, or a host tool already named `skill_read` means nothing is registered (one warning). **Opt-in**: give it a `source`. | a `SkillSource` — the read-only half of any `MemoryStore` (see below), `fsSkillSource(dir)` from `@reinsjs/brain/node` for a folder of `<name>/SKILL.md`, or `inlineSkills({ "code-review": "---\nname: code-review\ndescription: How we review PRs.\n---\n\n1. …" })` for bundled strings (Workers) — the object key must equal the frontmatter `name` |
46
46
  | `lazyTools()` | Tool discovery for large tool tables — the consumer of `Tool.lazy`. Tools marked `lazy: true` appear in the system prompt only as a menu (`name: one-line summary`, first line of the description by default); the model loads the ones a task needs with `tool_find({ names })`, which returns each tool's full description and input schema, and from the next turn on those tools are in the request's tool list. Which tools are loaded is rebuilt from the timeline (the `tool_find` calls and their non-error results), so pause / resume, later runs on the same session and process restarts agree. Calling a listed-but-unloaded tool is blocked with a pointer to `tool_find`. The menu is built from the tools bound *before* this socket — the host's and those of sockets registered earlier, e.g. `mcpTools({ override: (t, info) => info.annotations?.readOnlyHint ? { ...t, lazy: true } : false })` — so register `lazyTools()` last; `lazy` tools from later sockets are never hidden, one warning names them. No `lazy` tool bound before it, or a tool already named `tool_find`: nothing registered, one warning. **Opt-in**: install it. | `summarize(tool)` to replace the default summary, `summaryChars` (160), `maxPerCall` (20), `rules`, `warn` |
47
+ | `haltOnFailure()` | Models put several calls in one reply to save round trips, and the order is often a dependency: update the item, *then* tell the team it is ready. The model cannot make the second call conditional on the first — it does not see results inside one reply. With this module, once a call in the batch has failed (or is still waiting for approval or a client result), the calls after it are not run: each gets an error result naming the earlier call and asking the model to handle it first. Tool call ids stay one-to-one, nothing is executed, nothing counts toward the `toolCalls` budget. `counts(result)` picks which failures matter, `applies(call, tool)` which later calls to hold back (e.g. let `risk: "low"` reads run). Register it **first**. **Opt-in.** | nothing |
48
+ | `stopAfter({ tools })` | Ends the run (`done`) at the end of a turn in which the model successfully called one of `tools` — a wrap-up tool such as `end_run({ note })` placed in the same reply as the last actions, which saves the extra request for a closing message. It does not stop if anything in that batch failed or is still pending (the model sees the failure next turn), and a call left over from a paused run does not end a resumed run that brought new user input. Register it **after `handoff()` and before `compact()` / `budget()`**: the first socket with an opinion decides the turn. **Opt-in.** | nothing |
49
+
50
+ ### Act, then announce
51
+
52
+ `haltOnFailure` and `stopAfter` read `ctx.batch` — the calls of the current batch, the results logged so far, the calls left waiting, and whether this is a resumed batch — and work together:
53
+
54
+ ```ts
55
+ const sockets = [
56
+ haltOnFailure({ applies: (_call, tool) => tool?.risk !== "low" }), // first: a held-back call never reaches the others
57
+ handoff(),
58
+ stopAfter({ tools: ["end_run"] }), // after handoff, before compact / budget
59
+ compact(),
60
+ budget({ limits: { turns: 30 } }),
61
+ approval({ ask: ["deploy"], allow: ["board_update", "chat_send", "end_run"] }), // last, as always
62
+ ]
63
+ ```
64
+
65
+ If `board_update` fails in `[board_update, chat_send, end_run]`, `chat_send` and `end_run` are held back, so the run does not stop and the model sees the failure on the next turn. With TanStack AI (`@reinsjs/adapter-tanstack-ai`) the engine checks a whole batch before running any of it, so `haltOnFailure` only sees failures from earlier runs of a resumed batch; and a resumed batch gets no `onTurnEnd` there, so a wrap-up tool left waiting behind an approval costs one more model request.
47
66
 
48
67
  ### Skills from a database
49
68
 
@@ -71,7 +90,7 @@ The snapshot is taken when a segment starts: the first turn of the session, and
71
90
 
72
91
  ## Things that are deliberate
73
92
 
74
- - **Sockets run in order, and order matters.** `approval()` belongs last so it judges the arguments after any `rewrite`; `perception()` appends its note at the end of the visible events so the model reads it last.
93
+ - **Sockets run in order, and order matters.** `approval()` belongs last so it judges the arguments after any `rewrite`; `perception()` appends its note at the end of the visible events so the model reads it last; `haltOnFailure()` goes first; in `onTurnEnd` the first socket with an opinion decides, so `handoff()` → `stopAfter()` → `compact()` / `budget()`.
75
94
  - **Nothing is hidden from the log.** A note the model sees, a summary it wrote, a memory it changed — each is an event you can replay.
76
95
  - **Defaults come from measurements, not taste.** `compact` is recommended-on and `memory` / `handoff` are off because `examples/eval` says so. If you change a default, rerun the eval.
77
96
  - **Skills are read, not executed.** A skill's `scripts/` are not run by the library — a child process would break the zero-Node-builtins rule of `@reinsjs/brain` — expose what a skill needs as ordinary tools. Only `@reinsjs/brain/node` touches the file system.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Tool, TurnContext, MaybePromise, Socket, Event, CompactionPayload, FoldedToolResult, ToolContext, ContentPart, EventDraft, ToolReferencePart, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
1
+ import { Tool, TurnContext, MaybePromise, Socket, Event, CompactionPayload, FoldedToolResult, ToolContext, ContentPart, ToolResultEvent, ToolCallEvent, EventDraft, ToolReferencePart, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
2
2
  export { contextOverheadOf } from '@reinsjs/core';
3
3
 
4
4
  /**
@@ -496,6 +496,36 @@ declare const RECALL_TOOL_DESCRIPTION: string;
496
496
  declare const COMPACT_REQUEST_RULE = "- If the window gets close to full and you have not compacted, the harness will ask you to. Compact then, before anything else: that is the point where your own summary still beats a mechanical one.";
497
497
  declare const COMPACT_RULES = "## Managing your context window\nYou have a `compact` tool that folds earlier conversation into a summary you write. Status notes from the harness, if present, tell you how full the window is.\n- 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.\n- 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.\n- 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.\n- 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.\n- Nothing folded is lost for good: under each summary the harness lists the folded tool results as `seq N tool(arguments)`, and `recall({ 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.\n- If the window gets close to full and you have not compacted, the harness will ask you to. Compact then, before anything else: that is the point where your own summary still beats a mechanical one.\n- 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.";
498
498
 
499
+ /**
500
+ * halt-on-failure —— 同批前一个调用失败时拦下后面的(2026-11-02,OnSet 建议 9)。
501
+ *
502
+ * 模型一次回复里排出的顺序往往就是先后关系(先 `board_update` 置待确认,再 `chat_send` 说"已交,请看"),
503
+ * 但它结构上做不到"后一个以前一个的结果为条件"——一次回复里看不见结果。循环逐个执行,前一个失败后面照常执行,
504
+ * 于是"状态没改成、通知已发出"。本模块是宿主给的边界(缺省不装):同批排在前面的调用失败了、或还挂着
505
+ * (等审批 / 等客户端回填 / 子代理暂停),后面的就以 block 落一条 isError 结果,说明原因、请模型处理完再调。
506
+ * 调用顺序仍由模型排;被拦的调用 toolCallId 一一对应,历史完整(宪法一 / 二)。
507
+ *
508
+ * 判据只读 `ctx.batch`(循环随落随更,beforeTool 处理第 k 个调用时只看得见前面已落的结果),无状态、不进系统提示、不加工具。
509
+ * 被拦的调用不执行、不计 `ctx.budget.toolCalls`(`budget_usage.toolCalls` 仍按模型发出的条数记)。
510
+ *
511
+ * 注册顺序:推荐放在最前——block 短路,后面的 Socket(approval 等)就看不到被拦的调用;不在最前也正确,只是前面的先看到。
512
+ * TanStack 路径:适配器在 beforeTools 边界对整批一次性跑 beforeTool,那时同批都还没执行,本模块只看得见补跑时预置的失败
513
+ * (刻意不对称清单)。
514
+ */
515
+
516
+ declare const HALT_ON_FAILURE_SOCKET_NAME = "halt-on-failure";
517
+ interface HaltOnFailureOptions {
518
+ /** 哪些失败结果算数(只会拿 isError 的结果来问);缺省全算。例:只读查询失败不拦后续 */
519
+ counts?: (result: ToolResultEvent) => boolean;
520
+ /** 哪些后续调用要拦;缺省全拦。例:`(_call, tool) => tool?.risk !== "low"`,让同批的只读查询、pin、recall 照跑 */
521
+ applies?: (call: ToolCallEvent, tool: Tool | undefined) => boolean;
522
+ /** 告警出口(当前调用不在本批里——pending 跨批等罕见情形),每个原因只告一次。缺省 console.warn */
523
+ warn?: (message: string) => void;
524
+ }
525
+ /** 拦下时给模型的说明;`name` / `id` 是最初失败或挂起的那个调用(不是前一个被拦的) */
526
+ declare function haltedText(name: string, id: string, why: "failed" | "waiting"): string;
527
+ declare function haltOnFailure(opts?: HaltOnFailureOptions): Socket;
528
+
499
529
  /**
500
530
  * handoff —— 会话交接模块(技术方案 §9.5,B5)。
501
531
  *
@@ -1528,4 +1558,33 @@ declare function parseFetchBlobArgs(raw: unknown): FetchBlobArgs;
1528
1558
  declare function isTextMime(mime: string): boolean;
1529
1559
  declare function spill(opts?: SpillOptions): Socket;
1530
1560
 
1531
- export { APPROVAL_EXPIRY_RULE, APPROVAL_POLICY_IDS, APPROVAL_RULES, APPROVAL_SOCKET_NAME, type ApprovalOptions, BUDGET_SOCKET_NAME, type BudgetDimension, type BudgetHit, type BudgetLimits, type BudgetOptions, COMPACT_INPUT_SCHEMA, COMPACT_REQUEST_RULE, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_TOOL_DESCRIPTION, COMPACT_TOOL_NAME, type CompactArgs, type CompactOptions, type CompactPlan, type CompactRequestInfo, DEFAULT_FORCE_AT, DEFAULT_HANDOFF_REASON, DEFAULT_LAZY_SUMMARY_CHARS, DEFAULT_MAX_CONSECUTIVE_COMPACTIONS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_PIN_TEXT_LENGTH, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_MAX_SUMMARY_CHARS, DEFAULT_MAX_VIEW_CHARS, DEFAULT_PERCEPTION_THRESHOLDS, DEFAULT_PIN_OVERSHOOT_TOLERANCE, DEFAULT_PREVIEW_CHARS, DEFAULT_PREVIEW_LINES, DEFAULT_SKILLS_ROOT, DEFAULT_SKILL_READ_CHARS, DEFAULT_TOOL_FIND_MAX, type ExpiredApproval, FETCH_BLOB_INPUT_SCHEMA, FETCH_BLOB_TOOL_DESCRIPTION, FETCH_BLOB_TOOL_NAME, type FetchBlobArgs, type ForceOptions, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HandoffArgs, type HandoffOptions, type InlineSkill, type InlineSkillsOptions, LAZY_TOOLS_SOCKET_NAME, LAZY_TOOL_RULES, type LazyToolMenu, type LazyToolMenuEntry, type LazyToolsOptions, type LimitDimension, type LoadedSkill, MANIFEST_DEFAULT_EXCLUDE, MANIFEST_HEADING, MAX_MEMORY_PATH_LENGTH, MAX_SKILL_DESCRIPTION_CHARS, MEMORY_COMMANDS, MEMORY_INPUT_SCHEMA, MEMORY_ROOT, MEMORY_RULES, MEMORY_SOCKET_NAME, MEMORY_TOOL_DESCRIPTION, MEMORY_TOOL_NAME, type ManifestOptions, type MemoryCommand, type MemoryFs, type MemoryLimits, type MemoryOp, type MemoryOptions, type MemoryOutcome, PERCEPTION_SOCKET_NAME, PINS_SOCKET_NAME, PIN_INPUT_SCHEMA, PIN_RULES, PIN_TOOL_DESCRIPTION, PIN_TOOL_NAME, type ParsedSkill, type PerceptionLimits, type PerceptionOptions, type PerceptionReading, type PinArgs, type PinMeta, type PinNote, type PinSpec, type PinsOptions, type PlanOptions, type PolicyCall, type PolicyOutcome, type PolicyRule, type PolicyRuleSpec, type PolicyVerdict, type Preview, type PreviewOptions, RECALL_INPUT_SCHEMA, RECALL_TOOL_DESCRIPTION, RECALL_TOOL_NAME, type ReadingOptions, type ReadingThresholds, type RecallArgs, SKILLS_SOCKET_NAME, SKILL_FILE_NAME, SKILL_NAME_RE, SKILL_READ_INPUT_SCHEMA, SKILL_READ_TOOL_DESCRIPTION, SKILL_READ_TOOL_NAME, SKILL_RULES, SPILL_BLOB_MIME, SPILL_RULES, SPILL_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, TOOL_FIND_INPUT_SCHEMA, TOOL_FIND_TOOL_DESCRIPTION, TOOL_FIND_TOOL_NAME, type TextMeasure, type TextTokenEstimator, type Tier, type ToolFindInput, approval, assertAscending, assertLimits, assertSkillsRoot, bindMemoryFs, budget, budgetUsedOf, byteLength, carriedPins, checkBudget, clipEndByTokens, compact, compactNumber, compactRequestedSinceLastCompaction, compactRequestsSinceLastCompaction, composeHandoffNote, contextUsageRatio, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, expandMemoryDirectories, findExpiredApproval, findModelPin, fmt, globToRegExp, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isSnapshotPin, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, lazyMenuOf, lazyTools, loadSkillMenu, measureText, memory, modelActedSinceLastCompaction, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, parseToolFindInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactRequest, renderCompactionSummary, renderLazyToolMenu, renderLoadedTool, renderPerception, renderSkillMenu, renderToolFindResult, resolveMemoryPath, revealedLazyTools, segmentTimelineByTurn, skills, spill, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
1561
+ /**
1562
+ * stop-after —— 调成功某个工具,本轮结束即停(2026-11-02,OnSet 建议 10)。
1563
+ *
1564
+ * "交差即停":分支的 `fork_done`、主会话的 `end_run({ note })` 把最后一批动作和收尾放在同一次回复里,
1565
+ * 本轮结束 run 就以 done 收场,省掉"做完再请求一轮写收尾文字"那一轮。是不是收尾由模型决定(调不调这个工具),
1566
+ * 本模块只兑现(宪法一)。工具本身(把 note 当最后发言等)归宿主。
1567
+ *
1568
+ * `onTurnEnd` 返回 "stop" 的条件全部成立:
1569
+ * 1. 本批(`ctx.batch`)里有名单工具的成功结果(以真正落日志的那条为准,afterTool 替换之后);
1570
+ * 2. 同批没有 isError 结果、没有挂起的、每个调用都有结果——同批有失败就让模型下一轮看到再决定;
1571
+ * 3. 补跑轮(续跑补齐上次遗留的调用)另要求本批之后时间线上没有新的用户消息:
1572
+ * `[action 需审批, end_run]` 批准续跑、无新输入时照样收尾(与 handoff 从日志重建意图同理);
1573
+ * 但遗留的收尾不能吞掉新 run 带来的新输入。
1574
+ *
1575
+ * 注册顺序:onTurnEnd 第一个给意见的说了算。推荐 handoff → stopAfter → compact / budget:
1576
+ * 排在 handoff 前会让 `[handoff, end_run]` 吞掉交接——模型已收到"Handoff scheduled",框架却不兑现;
1577
+ * 排在 budget 后则触顶的那轮会以暂停收场而不是收尾。
1578
+ * 与 compact:模型在被请整理的那轮直接收尾,run 以 done 结束,那一级请求已用掉,下一个 run 不再请(阈值兜底仍在)。
1579
+ */
1580
+
1581
+ declare const STOP_AFTER_SOCKET_NAME = "stop-after";
1582
+ interface StopAfterOptions {
1583
+ /** 调成功即收尾的工具名 */
1584
+ tools: readonly string[];
1585
+ /** 告警出口(名单里的工具不在本轮工具表——多半是拼错),每个名字只告一次。缺省 console.warn */
1586
+ warn?: (message: string) => void;
1587
+ }
1588
+ declare function stopAfter(opts: StopAfterOptions): Socket;
1589
+
1590
+ export { APPROVAL_EXPIRY_RULE, APPROVAL_POLICY_IDS, APPROVAL_RULES, APPROVAL_SOCKET_NAME, type ApprovalOptions, BUDGET_SOCKET_NAME, type BudgetDimension, type BudgetHit, type BudgetLimits, type BudgetOptions, COMPACT_INPUT_SCHEMA, COMPACT_REQUEST_RULE, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_TOOL_DESCRIPTION, COMPACT_TOOL_NAME, type CompactArgs, type CompactOptions, type CompactPlan, type CompactRequestInfo, DEFAULT_FORCE_AT, DEFAULT_HANDOFF_REASON, DEFAULT_LAZY_SUMMARY_CHARS, DEFAULT_MAX_CONSECUTIVE_COMPACTIONS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_PIN_TEXT_LENGTH, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_MAX_SUMMARY_CHARS, DEFAULT_MAX_VIEW_CHARS, DEFAULT_PERCEPTION_THRESHOLDS, DEFAULT_PIN_OVERSHOOT_TOLERANCE, DEFAULT_PREVIEW_CHARS, DEFAULT_PREVIEW_LINES, DEFAULT_SKILLS_ROOT, DEFAULT_SKILL_READ_CHARS, DEFAULT_TOOL_FIND_MAX, type ExpiredApproval, FETCH_BLOB_INPUT_SCHEMA, FETCH_BLOB_TOOL_DESCRIPTION, FETCH_BLOB_TOOL_NAME, type FetchBlobArgs, type ForceOptions, HALT_ON_FAILURE_SOCKET_NAME, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HaltOnFailureOptions, type HandoffArgs, type HandoffOptions, type InlineSkill, type InlineSkillsOptions, LAZY_TOOLS_SOCKET_NAME, LAZY_TOOL_RULES, type LazyToolMenu, type LazyToolMenuEntry, type LazyToolsOptions, type LimitDimension, type LoadedSkill, MANIFEST_DEFAULT_EXCLUDE, MANIFEST_HEADING, MAX_MEMORY_PATH_LENGTH, MAX_SKILL_DESCRIPTION_CHARS, MEMORY_COMMANDS, MEMORY_INPUT_SCHEMA, MEMORY_ROOT, MEMORY_RULES, MEMORY_SOCKET_NAME, MEMORY_TOOL_DESCRIPTION, MEMORY_TOOL_NAME, type ManifestOptions, type MemoryCommand, type MemoryFs, type MemoryLimits, type MemoryOp, type MemoryOptions, type MemoryOutcome, PERCEPTION_SOCKET_NAME, PINS_SOCKET_NAME, PIN_INPUT_SCHEMA, PIN_RULES, PIN_TOOL_DESCRIPTION, PIN_TOOL_NAME, type ParsedSkill, type PerceptionLimits, type PerceptionOptions, type PerceptionReading, type PinArgs, type PinMeta, type PinNote, type PinSpec, type PinsOptions, type PlanOptions, type PolicyCall, type PolicyOutcome, type PolicyRule, type PolicyRuleSpec, type PolicyVerdict, type Preview, type PreviewOptions, RECALL_INPUT_SCHEMA, RECALL_TOOL_DESCRIPTION, RECALL_TOOL_NAME, type ReadingOptions, type ReadingThresholds, type RecallArgs, SKILLS_SOCKET_NAME, SKILL_FILE_NAME, SKILL_NAME_RE, SKILL_READ_INPUT_SCHEMA, SKILL_READ_TOOL_DESCRIPTION, SKILL_READ_TOOL_NAME, SKILL_RULES, SPILL_BLOB_MIME, SPILL_RULES, SPILL_SOCKET_NAME, STOP_AFTER_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, type StopAfterOptions, TOOL_FIND_INPUT_SCHEMA, TOOL_FIND_TOOL_DESCRIPTION, TOOL_FIND_TOOL_NAME, type TextMeasure, type TextTokenEstimator, type Tier, type ToolFindInput, approval, assertAscending, assertLimits, assertSkillsRoot, bindMemoryFs, budget, budgetUsedOf, byteLength, carriedPins, checkBudget, clipEndByTokens, compact, compactNumber, compactRequestedSinceLastCompaction, compactRequestsSinceLastCompaction, composeHandoffNote, contextUsageRatio, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, expandMemoryDirectories, findExpiredApproval, findModelPin, fmt, globToRegExp, haltOnFailure, haltedText, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isSnapshotPin, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, lazyMenuOf, lazyTools, loadSkillMenu, measureText, memory, modelActedSinceLastCompaction, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, parseToolFindInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactRequest, renderCompactionSummary, renderLazyToolMenu, renderLoadedTool, renderPerception, renderSkillMenu, renderToolFindResult, resolveMemoryPath, revealedLazyTools, segmentTimelineByTurn, skills, spill, stopAfter, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
package/dist/index.js CHANGED
@@ -860,6 +860,56 @@ function isModelCompaction(e) {
860
860
  return isCompaction4(e) && e.payload.decidedBy === "model";
861
861
  }
862
862
 
863
+ // src/shared/batch.ts
864
+ function batchOf(ctx, module) {
865
+ const batch = ctx.batch;
866
+ if (batch === void 0) {
867
+ throw new Error(`${module} requires a loop that fills TurnContext.batch (@reinsjs/core >= 0.8.0)`);
868
+ }
869
+ return batch;
870
+ }
871
+
872
+ // src/halt-on-failure/halt-on-failure.ts
873
+ var HALT_ON_FAILURE_SOCKET_NAME = "halt-on-failure";
874
+ function haltedText(name, id, why) {
875
+ return why === "failed" ? `An earlier call in this batch (${name}, ${id}) failed, so this call was not run. Handle that first, then call again if still needed.` : `An earlier call in this batch (${name}, ${id}) is still waiting (for approval or a client result), so this call was not run. Once it has completed, call again if still needed.`;
876
+ }
877
+ function haltOnFailure(opts = {}) {
878
+ const counts = opts.counts ?? (() => true);
879
+ const applies = opts.applies ?? (() => true);
880
+ const warn = opts.warn ?? ((message) => console.warn(message));
881
+ const warned = /* @__PURE__ */ new Set();
882
+ return {
883
+ name: HALT_ON_FAILURE_SOCKET_NAME,
884
+ beforeTool(ctx, call, tool) {
885
+ const batch = batchOf(ctx, "haltOnFailure");
886
+ const id = call.payload.toolCallId;
887
+ const at = batch.calls.findIndex((c) => c.payload.toolCallId === id);
888
+ if (at < 0) {
889
+ if (!warned.has("not-in-batch")) {
890
+ warned.add("not-in-batch");
891
+ warn(
892
+ `haltOnFailure: call ${id} is not in the current batch (pending calls span batches?); not checked`
893
+ );
894
+ }
895
+ return void 0;
896
+ }
897
+ if (!applies(call, tool)) return void 0;
898
+ const results = new Map(batch.results.map((r) => [r.payload.toolCallId, r]));
899
+ const held = new Set(batch.held);
900
+ for (const earlier of batch.calls.slice(0, at)) {
901
+ const earlierId = earlier.payload.toolCallId;
902
+ const result = results.get(earlierId);
903
+ if (result?.payload.isError && counts(result)) {
904
+ return { block: haltedText(earlier.payload.name, earlierId, "failed") };
905
+ }
906
+ if (held.has(earlierId)) return { block: haltedText(earlier.payload.name, earlierId, "waiting") };
907
+ }
908
+ return void 0;
909
+ }
910
+ };
911
+ }
912
+
863
913
  // src/handoff/handoff.ts
864
914
  import { isModelOutput, supersededIds as supersededIds2 } from "@reinsjs/core";
865
915
 
@@ -2861,6 +2911,52 @@ async function loadReferencedBlob(blobs, id) {
2861
2911
  throw err;
2862
2912
  }
2863
2913
  }
2914
+
2915
+ // src/stop-after/stop-after.ts
2916
+ var STOP_AFTER_SOCKET_NAME = "stop-after";
2917
+ function stopAfter(opts) {
2918
+ const names = opts.tools;
2919
+ if (!Array.isArray(names) || names.length === 0) {
2920
+ throw new RangeError(
2921
+ `stopAfter.tools must be a non-empty array of tool names, got ${JSON.stringify(names)}`
2922
+ );
2923
+ }
2924
+ for (const n of names) {
2925
+ if (typeof n !== "string" || n.length === 0) {
2926
+ throw new RangeError(`stopAfter.tools must contain non-empty strings, got ${JSON.stringify(n)}`);
2927
+ }
2928
+ }
2929
+ const stopping = new Set(names);
2930
+ const warn = opts.warn ?? ((message) => console.warn(message));
2931
+ const warned = /* @__PURE__ */ new Set();
2932
+ return {
2933
+ name: STOP_AFTER_SOCKET_NAME,
2934
+ beforeModel(ctx) {
2935
+ for (const name of stopping) {
2936
+ if (warned.has(name) || ctx.tools.some((t) => t.name === name)) continue;
2937
+ warned.add(name);
2938
+ warn(`stopAfter: tool "${name}" is not in this run's tool list; it can never end a turn`);
2939
+ }
2940
+ return void 0;
2941
+ },
2942
+ onTurnEnd(ctx) {
2943
+ const batch = batchOf(ctx, "stopAfter");
2944
+ if (batch.calls.length === 0 || batch.held.length > 0) return void 0;
2945
+ const answered = new Set(batch.results.map((r) => r.payload.toolCallId));
2946
+ if (!batch.calls.every((c) => answered.has(c.payload.toolCallId))) return void 0;
2947
+ if (batch.results.some((r) => r.payload.isError)) return void 0;
2948
+ if (!batch.results.some((r) => stopping.has(r.payload.name))) return void 0;
2949
+ if (batch.resumed) {
2950
+ const lastCallSeq = Math.max(...batch.calls.map((c) => c.seq));
2951
+ const newInput = ctx.timeline.some(
2952
+ (e) => e.seq > lastCallSeq && e.type === "core.user_message"
2953
+ );
2954
+ if (newInput) return void 0;
2955
+ }
2956
+ return "stop";
2957
+ }
2958
+ };
2959
+ }
2864
2960
  export {
2865
2961
  APPROVAL_EXPIRY_RULE,
2866
2962
  APPROVAL_POLICY_IDS,
@@ -2892,6 +2988,7 @@ export {
2892
2988
  FETCH_BLOB_INPUT_SCHEMA,
2893
2989
  FETCH_BLOB_TOOL_DESCRIPTION,
2894
2990
  FETCH_BLOB_TOOL_NAME,
2991
+ HALT_ON_FAILURE_SOCKET_NAME,
2895
2992
  HANDOFF_INPUT_SCHEMA,
2896
2993
  HANDOFF_RULES,
2897
2994
  HANDOFF_SOCKET_NAME,
@@ -2929,6 +3026,7 @@ export {
2929
3026
  SPILL_BLOB_MIME,
2930
3027
  SPILL_RULES,
2931
3028
  SPILL_SOCKET_NAME,
3029
+ STOP_AFTER_SOCKET_NAME,
2932
3030
  TOOL_FIND_INPUT_SCHEMA,
2933
3031
  TOOL_FIND_TOOL_DESCRIPTION,
2934
3032
  TOOL_FIND_TOOL_NAME,
@@ -2963,6 +3061,8 @@ export {
2963
3061
  findModelPin,
2964
3062
  fmt,
2965
3063
  globToRegExp,
3064
+ haltOnFailure,
3065
+ haltedText,
2966
3066
  handoff,
2967
3067
  humanSize,
2968
3068
  inlineSkills,
@@ -3015,6 +3115,7 @@ export {
3015
3115
  segmentTimelineByTurn,
3016
3116
  skills,
3017
3117
  spill,
3118
+ stopAfter,
3018
3119
  sumSessionTokens,
3019
3120
  summarizeTool,
3020
3121
  timelineSoFar,