@reinsjs/core 0.10.0 → 0.11.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,11 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.11.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b79d193: Add `pullInput` for input that arrives while a run is going. The loop calls it before every model call (not on a turn that only finishes leftover tool calls, not once `maxTurns` is reached) and appends the returned drafts ahead of that turn's socket notes. Only `core.user_message`, `core.system_note` and `ext.*` are accepted; a malformed return value ends the run with `status: "error"` (`core.error` category `input`) and writes none of the batch; a throwing callback is recorded as a model-invisible `core.error` (category `host`) and the run carries on; drafts pulled after an abort are not written. `agent.run()` passes it through. It is per run: `AgentDefinition` (and so `createAgent` options) now omits `pullInput`, so the HTTP handler and `asTool` sub-agents never pull.
8
+
3
9
  ## 0.10.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -61,6 +61,42 @@ runLoop({ ...config, input: briefedInput("Ticket #12 was edited by Ana an hour a
61
61
 
62
62
  Every draft goes through the same checks — type whitelist (`core.user_message`, `core.tool_result`, `core.system_note`, `ext.*`), a valid actor, the basic payload shape of the three core types, and registration in your registry — and one bad draft rejects the whole batch before anything is written; content parts cannot be mixed with drafts. The envelope (`actor`, `trust`) and the shape of your own `ext.*` payloads are yours to get right: in-process input is trusted host code. Keep one user message per batch: compaction keeps only the most recent one verbatim, while background notes fold like any other note (put what must stay in a pin). Lowering keeps the order on Chat and Responses; on Anthropic models that accept mid-conversation system messages the note lands right after the user message, because a system message may not come first or follow an assistant one. The HTTP handler in `@reinsjs/server` does not accept draft arrays — this is for in-process hosts.
63
63
 
64
+ ## Input that arrives mid-run
65
+
66
+ A run can take minutes. Messages that reach your host meanwhile (a teammate changed direction, someone signed off a plan) can be handed to the model before its next call instead of waiting for the run to end. Pass `pullInput`: the loop calls it before every model call — not on a turn that only finishes leftover tool calls, and not once `maxTurns` is reached — and appends whatever drafts it returns, ahead of that turn's socket notes. Your queue stays the source of truth: offer what is waiting, and claim a delivery only when its event comes back out of the loop.
67
+
68
+ ```ts
69
+ /** A host mailbox: offer everything unclaimed at each gap; claim when the loop has written it. */
70
+ function mailbox() {
71
+ const waiting = new Map<string, string>()
72
+ return {
73
+ post(id: string, text: string) {
74
+ waiting.set(id, text)
75
+ },
76
+ pullInput: (): EventDraft[] =>
77
+ [...waiting].map(([id, text]) => ({
78
+ type: "core.user_message",
79
+ actor: "user",
80
+ provenance: { source: "mailbox", ref: id },
81
+ payload: { content: [{ type: "text", text }] },
82
+ })),
83
+ claim(event: Event) {
84
+ if (event.provenance?.source === "mailbox" && event.provenance.ref) waiting.delete(event.provenance.ref)
85
+ },
86
+ }
87
+ }
88
+
89
+ const box = mailbox()
90
+ for await (const event of runLoop({ ...config, input: "Plan the shoot.", pullInput: box.pullInput })) box.claim(event)
91
+ ```
92
+
93
+ - Claim while handling the event, before asking the loop for the next one. If you only claim later, the next gap offers the same drafts again and they are written twice.
94
+ - Only `core.user_message`, `core.system_note` and `ext.*` are accepted here (no `core.tool_result`: there is no open call to answer at that point). A return value that is not an array, or holds anything else, ends the run with `status: "error"` and writes none of the batch. If the callback throws, the loop records a `core.error` the model cannot see and carries on; the messages are still in your queue. If the run is aborted while you were pulling, the drafts are not written.
95
+ - Anything that arrives after the last pull is not part of this run: check your queue once more when the run returns. A callback that never settles stalls the run, so put your own timeout on it.
96
+ - A run that absorbs follow-ups lives longer: per-run budget limits (turns, wall time, tokens) trip sooner.
97
+ - On Anthropic models that accept mid-conversation system messages, a mid-run `system_note` follows a tool result, so it becomes a real system message placed after the user message; at the start of a run it usually follows an assistant reply and is sent as tagged user text instead.
98
+ - `pullInput` is per run: `runLoop` and `agent.run()` take it; agent definitions, the HTTP handler and `asTool` sub-agents do not.
99
+
64
100
  ## Tools
65
101
 
66
102
  ```ts
package/dist/index.d.ts CHANGED
@@ -492,6 +492,12 @@ type RunResult = {
492
492
  error: CoreEventOf<"core.error">;
493
493
  };
494
494
  type ErrorEventPayload = ErrorPayload;
495
+ /** `LoopConfig.pullInput` 的参数 */
496
+ interface PullInputContext {
497
+ sessionId: string;
498
+ /** 将要进行的轮次(本 run 内从 1 起):拉到的输入就给这一轮的模型看 */
499
+ turn: number;
500
+ }
495
501
  interface LoopConfig {
496
502
  sessionId: string;
497
503
  log: EventLog;
@@ -510,6 +516,18 @@ interface LoopConfig {
510
516
  * 缺省不追加(续跑:日志里有未完成的工具调用就先补齐,再问模型)。
511
517
  */
512
518
  input?: string | ContentPart[] | EventDraft | readonly EventDraft[];
519
+ /**
520
+ * run 进行中的新输入(拉,OnSet 建议 13)。循环在每次调模型前调一次——补跑 pending 的那轮与已触顶 `maxTurns` 时不调;
521
+ * 返回非空即一次 append 写入时间线,排在本轮 beforeModel 说明之前,空数组表示没有。
522
+ * 只收 `core.user_message` / `core.system_note` / `ext.*`(比 `input` 窄:拉取点上没有可回答的 pending 调用,不收 tool_result)。
523
+ * - 返回值不合规(非数组、白名单外类型、未登记的 ext.*):run 以 error 结束(`core.error` category "input"),这一批一条不写。
524
+ * - 回调抛错:记一条模型不可见的 `core.error`(category "host"),当这次没有、run 照跑(fail-open:消息还在宿主队列里)。
525
+ * - 拉完发现已中止:拉到的不写,按"本轮开始前中止"暂停。
526
+ * 宿主须在处理到写入事件时(await 完)完成认领再继续迭代,否则下一次会再拉到同一批;推荐草稿带 `provenance.ref` 记投递 id。
527
+ * 最后一次拉取到 run 结束之间来的消息不会进本 run:run 结束后宿主仍须查一次队列。回调挂住不返回 run 就挂住,超时由宿主自带。
528
+ * 每次 run 的字段:不进 `AgentDefinition`(HTTP run、asTool 子 run 不拉)。
529
+ */
530
+ pullInput?: (ctx: PullInputContext) => MaybePromise<readonly EventDraft[]>;
513
531
  principal?: Principal;
514
532
  projection?: {
515
533
  strategies?: readonly ProjectionStrategy[];
@@ -1345,6 +1363,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1345
1363
  */
1346
1364
 
1347
1365
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1348
- declare const REINS_VERSION = "0.10.0";
1366
+ declare const REINS_VERSION = "0.11.0";
1349
1367
 
1350
- export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DecodedToolArguments, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, OUTCOME_UNKNOWN_TEXT, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, type StopTexts, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolBatch, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, type ToolResultEvent, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, startedToolCallIds, statusFromMessage, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };
1368
+ export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DecodedToolArguments, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, OUTCOME_UNKNOWN_TEXT, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, type PullInputContext, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, type StopTexts, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolBatch, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, type ToolResultEvent, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, startedToolCallIds, statusFromMessage, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };
package/dist/index.js CHANGED
@@ -1199,6 +1199,35 @@ function inputDrafts(input) {
1199
1199
  }
1200
1200
  return [checkInputDraft(input)];
1201
1201
  }
1202
+ var PULLED_DRAFT_TYPES = /* @__PURE__ */ new Set(["core.user_message", "core.system_note"]);
1203
+ function checkPulledDrafts(value, registry) {
1204
+ if (!Array.isArray(value)) {
1205
+ throw new RangeError(`pullInput must return an array of event drafts, got ${describe(value)}`);
1206
+ }
1207
+ return value.map((raw) => {
1208
+ const draft = typeof raw === "object" && raw !== null ? raw : {};
1209
+ const type = draft.type;
1210
+ if (typeof type !== "string" || !PULLED_DRAFT_TYPES.has(type) && !type.startsWith("ext.")) {
1211
+ throw new RangeError(
1212
+ `pullInput draft rejects event type ${String(type)}: only core.user_message, core.system_note or ext.* are accepted`
1213
+ );
1214
+ }
1215
+ checkInputDraft(draft);
1216
+ if (!registry.has(type)) throw new RangeError(`pullInput draft type ${type} is not registered`);
1217
+ return draft;
1218
+ });
1219
+ }
1220
+ function describeThrown(value) {
1221
+ if (value instanceof Error) return value.message;
1222
+ try {
1223
+ return String(value);
1224
+ } catch {
1225
+ return "a value that cannot be printed";
1226
+ }
1227
+ }
1228
+ function describe(value) {
1229
+ return value === null ? "null" : typeof value;
1230
+ }
1202
1231
  function isInputArray(input) {
1203
1232
  return Array.isArray(input);
1204
1233
  }
@@ -1359,7 +1388,52 @@ async function* runLoop(cfg) {
1359
1388
  return result;
1360
1389
  }
1361
1390
  const turnStartedAt = now();
1362
- const timeline = await readTimeline(log, sessionId, { registry });
1391
+ let timeline = await readTimeline(log, sessionId, { registry });
1392
+ if (cfg.pullInput !== void 0 && turns < maxTurns && pendingToolCalls(timeline).length === 0) {
1393
+ let raw = [];
1394
+ let thrown;
1395
+ try {
1396
+ raw = await cfg.pullInput({ sessionId, turn: turns + 1 });
1397
+ } catch (err) {
1398
+ thrown = { value: err };
1399
+ }
1400
+ if (cfg.signal?.aborted) continue;
1401
+ if (thrown !== void 0) {
1402
+ const errors = await append([
1403
+ {
1404
+ type: "core.error",
1405
+ actor: "system",
1406
+ payload: {
1407
+ category: "host",
1408
+ message: `pullInput threw: ${describeThrown(thrown.value)}`,
1409
+ retryable: true,
1410
+ detail: { phase: "pullInput" }
1411
+ }
1412
+ }
1413
+ ]);
1414
+ yield* errors;
1415
+ timeline = [...timeline, ...errors];
1416
+ } else {
1417
+ let pulled;
1418
+ try {
1419
+ pulled = checkPulledDrafts(raw, registry);
1420
+ } catch (err) {
1421
+ const { events, result } = await fail({
1422
+ category: "input",
1423
+ message: describeThrown(err),
1424
+ retryable: false,
1425
+ detail: { phase: "pullInput" }
1426
+ });
1427
+ yield* events;
1428
+ return result;
1429
+ }
1430
+ if (pulled.length > 0) {
1431
+ const written = await append(pulled);
1432
+ yield* written;
1433
+ timeline = [...timeline, ...written];
1434
+ }
1435
+ }
1436
+ }
1363
1437
  const lastUsage = lastBudgetUsage(timeline)?.payload.tokens;
1364
1438
  const projected = project({
1365
1439
  timeline,
@@ -2109,7 +2183,7 @@ function memoryStore() {
2109
2183
  }
2110
2184
 
2111
2185
  // src/index.ts
2112
- var REINS_VERSION = "0.10.0";
2186
+ var REINS_VERSION = "0.11.0";
2113
2187
  export {
2114
2188
  BUILTIN_APPROVAL_POLICY,
2115
2189
  CORE_SCHEMAS,