@reinsjs/core 0.9.0 → 0.10.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 CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  createEvent,
9
9
  renderToolReference,
10
10
  uuidv7
11
- } from "./chunk-GWU2JSFA.js";
11
+ } from "./chunk-3QMUURRG.js";
12
12
 
13
13
  // src/events/core.ts
14
14
  function contextTokensOf(usage) {
@@ -34,7 +34,8 @@ var DEFAULT_MODEL_INVISIBLE_TYPES = /* @__PURE__ */ new Set([
34
34
  "core.memory_op",
35
35
  "core.handoff",
36
36
  "core.error",
37
- "core.tools_bound"
37
+ "core.tools_bound",
38
+ "core.tool_started"
38
39
  ]);
39
40
  function visibilityFilter(opts = {}) {
40
41
  const invisible = opts.invisibleTypes ? new Set(opts.invisibleTypes) : DEFAULT_MODEL_INVISIBLE_TYPES;
@@ -626,6 +627,48 @@ var LoweringError = class extends Error {
626
627
  context;
627
628
  };
628
629
 
630
+ // src/loop/stop.ts
631
+ var STOPPED_NOTE = "stopped by the user";
632
+ var STOPPED_NOT_EXECUTED_TEXT = "Not executed: the run was stopped by the user before this call started.";
633
+ var STOPPED_IN_PROGRESS_TEXT = "Interrupted: the run was stopped by the user while this call was in progress; it may have partly taken effect.";
634
+ var INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: an earlier run was interrupted before this call started.";
635
+ var INTERRUPTED_IN_PROGRESS_TEXT = "Interrupted: an earlier run was interrupted while this call was in progress; it may have partly taken effect.";
636
+ var OUTCOME_UNKNOWN_TEXT = "Execution was interrupted before a result was recorded; the outcome is unknown. Check the current state before retrying.";
637
+ var RunStop = class extends Error {
638
+ by;
639
+ constructor(by = "user") {
640
+ super(
641
+ by === "user" ? "the run was stopped by the user" : "the host closed calls left by an interrupted run"
642
+ );
643
+ this.name = "RunStop";
644
+ this.by = by;
645
+ }
646
+ };
647
+ function stopTextsOf(reason) {
648
+ return reason?.by === "host" ? {
649
+ notExecuted: INTERRUPTED_NOT_EXECUTED_TEXT,
650
+ inProgress: INTERRUPTED_IN_PROGRESS_TEXT,
651
+ note: "closed calls left by an interrupted run"
652
+ } : { notExecuted: STOPPED_NOT_EXECUTED_TEXT, inProgress: STOPPED_IN_PROGRESS_TEXT, note: STOPPED_NOTE };
653
+ }
654
+ function isStopReason(reason) {
655
+ return typeof reason === "object" && reason !== null && reason.name === "RunStop";
656
+ }
657
+ function isStopped(signal) {
658
+ return signal?.aborted === true && isStopReason(signal.reason);
659
+ }
660
+ function isReplayable(tool) {
661
+ return tool.replayable ?? tool.risk === "low";
662
+ }
663
+ function startedToolCallIds(timeline) {
664
+ const started = /* @__PURE__ */ new Set();
665
+ for (const raw of timeline) {
666
+ const e = raw;
667
+ if (e.type === "core.tool_started") started.add(e.payload.toolCallId);
668
+ }
669
+ return started;
670
+ }
671
+
629
672
  // src/loop/retry.ts
630
673
  var DEFAULT_RETRY_MAX_ATTEMPTS = 3;
631
674
  var DEFAULT_RETRY_BASE_DELAY_MS = 1e3;
@@ -667,7 +710,7 @@ var CONNECTION_ERROR_NAMES = /* @__PURE__ */ new Set([
667
710
  function isDefinitelyPermanent(err) {
668
711
  if (err instanceof LoweringError) return true;
669
712
  const name = err?.name;
670
- return name === "AbortError" || name === "APIUserAbortError";
713
+ return name === "AbortError" || name === "APIUserAbortError" || isStopReason(err);
671
714
  }
672
715
  function statusFromMessage(message) {
673
716
  const m = /^\s*(\d{3})\b/.exec(message) ?? /\b(?:status(?:\s+code)?|HTTP)[\s:=]+(\d{3})\b/i.exec(message);
@@ -787,6 +830,20 @@ async function computeConfigHash(input) {
787
830
  })
788
831
  );
789
832
  }
833
+ async function computeModelDigest(model) {
834
+ return sha256(JSON.stringify(model));
835
+ }
836
+ async function computePendingToolsDigest(calls, tools) {
837
+ const names = [...new Set(calls.map((c) => c.payload.name))].sort();
838
+ return sha256(
839
+ JSON.stringify(
840
+ names.map((name) => {
841
+ const t = tools.find((x) => x.name === name);
842
+ return t ? [name, t.description, t.inputSchema] : [name, null];
843
+ })
844
+ )
845
+ );
846
+ }
790
847
  async function computePendingDigest(calls) {
791
848
  return sha256(
792
849
  JSON.stringify(calls.map((c) => [c.payload.toolCallId, c.payload.name, c.payload.args ?? null]))
@@ -799,19 +856,26 @@ async function serializeRunState(input) {
799
856
  lastSeq: input.lastSeq,
800
857
  pendingToolCallIds: input.pending.map((c) => c.payload.toolCallId),
801
858
  configHash: input.configHash,
802
- pendingDigest: await computePendingDigest(input.pending)
859
+ pendingDigest: await computePendingDigest(input.pending),
860
+ ...input.model !== void 0 && input.tools !== void 0 ? {
861
+ modelDigest: await computeModelDigest(input.model),
862
+ pendingToolsDigest: await computePendingToolsDigest(input.pending, input.tools)
863
+ } : {}
803
864
  };
804
865
  return input.secret === void 0 ? state : signRunState(state, input.secret);
805
866
  }
806
867
  function signingMaterial(state) {
807
- return JSON.stringify([
868
+ const fields = [
808
869
  state.v,
809
870
  state.sessionId,
810
871
  state.lastSeq,
811
872
  state.pendingToolCallIds,
812
873
  state.configHash,
813
874
  state.pendingDigest
814
- ]);
875
+ ];
876
+ if (state.modelDigest !== void 0 || state.pendingToolsDigest !== void 0)
877
+ fields.push(state.modelDigest ?? null, state.pendingToolsDigest ?? null);
878
+ return JSON.stringify(fields);
815
879
  }
816
880
  async function hmac(secret, material) {
817
881
  const key = await crypto.subtle.importKey(
@@ -850,7 +914,7 @@ var RunStateError = class extends Error {
850
914
  };
851
915
  function assertRunStateShape(raw) {
852
916
  const s = raw;
853
- const ok = typeof s === "object" && s !== null && s.v === 1 && typeof s.sessionId === "string" && Number.isInteger(s.lastSeq) && Array.isArray(s.pendingToolCallIds) && s.pendingToolCallIds.every((id) => typeof id === "string") && typeof s.configHash === "string" && typeof s.pendingDigest === "string" && (s.sig === void 0 || typeof s.sig === "string");
917
+ const ok = typeof s === "object" && s !== null && s.v === 1 && typeof s.sessionId === "string" && Number.isInteger(s.lastSeq) && Array.isArray(s.pendingToolCallIds) && s.pendingToolCallIds.every((id) => typeof id === "string") && typeof s.configHash === "string" && typeof s.pendingDigest === "string" && (s.modelDigest === void 0 || typeof s.modelDigest === "string") && (s.pendingToolsDigest === void 0 || typeof s.pendingToolsDigest === "string") && (s.sig === void 0 || typeof s.sig === "string");
854
918
  if (!ok) throw new RunStateError("malformed", "run state is not in the v1 shape");
855
919
  }
856
920
  async function validateResume(input) {
@@ -879,7 +943,14 @@ async function validateResume(input) {
879
943
  );
880
944
  }
881
945
  }
882
- if (state.configHash !== input.configHash && !input.allowConfigDrift) {
946
+ const narrowed = state.modelDigest !== void 0 && state.pendingToolsDigest !== void 0 && input.model !== void 0 && input.tools !== void 0;
947
+ if (narrowed && !input.allowConfigDrift) {
948
+ if (await computeModelDigest(input.model) !== state.modelDigest) {
949
+ throw new RunStateError("config_mismatch", "the model differs from when the run paused", {
950
+ part: "model"
951
+ });
952
+ }
953
+ } else if (state.configHash !== input.configHash && !input.allowConfigDrift) {
883
954
  throw new RunStateError(
884
955
  "config_mismatch",
885
956
  "model, tool set or system prompt differs from when the run paused; pass allowConfigDrift if this is intended",
@@ -908,6 +979,14 @@ async function validateResume(input) {
908
979
  got: ids
909
980
  });
910
981
  }
982
+ if (narrowed && !input.allowConfigDrift && await computePendingToolsDigest(pending, input.tools) !== state.pendingToolsDigest) {
983
+ const names = [...new Set(pending.map((c) => c.payload.name))].sort();
984
+ throw new RunStateError(
985
+ "config_mismatch",
986
+ `the definition of pending tool ${names.join(", ")} differs from when the run paused; pass allowConfigDrift if this is intended`,
987
+ { part: "pendingTools", tools: names }
988
+ );
989
+ }
911
990
  return pending;
912
991
  }
913
992
 
@@ -1157,14 +1236,44 @@ async function* runLoop(cfg) {
1157
1236
  lastSeq += events.length;
1158
1237
  return events;
1159
1238
  };
1160
- const pause = async (reason, interruptions) => {
1161
- const events = await append([{ type: "core.run_paused", actor: "system", payload: { reason } }]);
1239
+ const settleStopped = async (texts) => {
1240
+ const timeline = await readTimeline(log, sessionId, { registry });
1241
+ const pending = pendingToolCalls(timeline);
1242
+ if (pending.length === 0) return [];
1243
+ const started = startedToolCallIds(timeline);
1244
+ return append(
1245
+ pending.map((call) => {
1246
+ const { toolCallId, name } = call.payload;
1247
+ const tool = baseTools.find((t) => t.name === name);
1248
+ const text = !started.has(toolCallId) ? texts.notExecuted : tool !== void 0 && isReplayable(tool) ? texts.inProgress : OUTCOME_UNKNOWN_TEXT;
1249
+ return {
1250
+ type: "core.tool_result",
1251
+ actor: "tool",
1252
+ parentId: call.id,
1253
+ provenance: { source: name },
1254
+ payload: { toolCallId, name, content: [{ type: "text", text }], isError: true }
1255
+ };
1256
+ })
1257
+ );
1258
+ };
1259
+ const pause = async (requested, requestedInterruptions) => {
1260
+ const stopped = isStopped(cfg.signal);
1261
+ const texts = stopped ? stopTextsOf(cfg.signal?.reason) : void 0;
1262
+ const reason = texts ? "host" : requested;
1263
+ const interruptions = texts ? [{ kind: "host", note: texts.note }] : requestedInterruptions;
1264
+ const settled = texts ? await settleStopped(texts) : [];
1265
+ const events = [
1266
+ ...settled,
1267
+ ...await append([{ type: "core.run_paused", actor: "system", payload: { reason } }])
1268
+ ];
1162
1269
  const pending = pendingToolCalls(await readTimeline(log, sessionId, { registry }));
1163
1270
  const state = await serializeRunState({
1164
1271
  sessionId,
1165
1272
  lastSeq,
1166
1273
  pending,
1167
1274
  configHash,
1275
+ model,
1276
+ tools: baseTools,
1168
1277
  ...cfg.secret !== void 0 ? { secret: cfg.secret } : {}
1169
1278
  });
1170
1279
  return { events, result: { status: "paused", sessionId, lastSeq, reason, interruptions, state } };
@@ -1192,6 +1301,8 @@ async function* runLoop(cfg) {
1192
1301
  sessionId,
1193
1302
  timeline,
1194
1303
  configHash,
1304
+ model,
1305
+ tools: baseTools,
1195
1306
  ...cfg.secret !== void 0 ? { secret: cfg.secret } : {},
1196
1307
  ...cfg.allowConfigDrift !== void 0 ? { allowConfigDrift: cfg.allowConfigDrift } : {}
1197
1308
  });
@@ -1228,16 +1339,25 @@ async function* runLoop(cfg) {
1228
1339
  }))
1229
1340
  );
1230
1341
  }
1231
- yield* await append(
1232
- toolsBoundDrafts({
1233
- timeline: await readTimeline(log, sessionId, { registry }),
1234
- toolNames: baseTools.map((t) => t.name),
1235
- configHash,
1236
- announce: cfg.announceToolChanges ?? true
1237
- })
1238
- );
1342
+ if (!cfg.signal?.aborted) {
1343
+ yield* await append(
1344
+ toolsBoundDrafts({
1345
+ timeline: await readTimeline(log, sessionId, { registry }),
1346
+ toolNames: baseTools.map((t) => t.name),
1347
+ configHash,
1348
+ announce: cfg.announceToolChanges ?? true
1349
+ })
1350
+ );
1351
+ }
1239
1352
  yield* await append(input.map((d) => withResultTrust(d, baseTools)));
1240
1353
  while (true) {
1354
+ if (cfg.signal?.aborted) {
1355
+ const { events, result } = await pause("host", [
1356
+ { kind: "host", note: "host aborted before this turn started" }
1357
+ ]);
1358
+ yield* events;
1359
+ return result;
1360
+ }
1241
1361
  const turnStartedAt = now();
1242
1362
  const timeline = await readTimeline(log, sessionId, { registry });
1243
1363
  const lastUsage = lastBudgetUsage(timeline)?.payload.tokens;
@@ -1290,13 +1410,6 @@ async function* runLoop(cfg) {
1290
1410
  const events = await append(emitted.splice(0));
1291
1411
  return events;
1292
1412
  };
1293
- if (cfg.signal?.aborted) {
1294
- const { events, result } = await pause("host", [
1295
- { kind: "host", note: "host aborted before this turn started" }
1296
- ]);
1297
- yield* events;
1298
- return result;
1299
- }
1300
1413
  const pending = pendingToolCalls(timeline);
1301
1414
  if (pending.length > 0) {
1302
1415
  const located = toolBatchOf(timeline, pending);
@@ -1313,7 +1426,7 @@ async function* runLoop(cfg) {
1313
1426
  batch
1314
1427
  });
1315
1428
  toolCallsTotal += settled.executed;
1316
- if (settled.interruptions.length > 0) {
1429
+ if (settled.interruptions.length > 0 || isStopped(cfg.signal)) {
1317
1430
  const reason = pauseReasonOf(settled.interruptions);
1318
1431
  const { events, result } = await pause(reason, settled.interruptions);
1319
1432
  yield* events;
@@ -1403,6 +1516,13 @@ async function* runLoop(cfg) {
1403
1516
  message: failure.message,
1404
1517
  detail: { usage: outcome?.usage }
1405
1518
  };
1519
+ if (!canRetry && cfg.signal?.aborted) {
1520
+ const { events, result } = await pause("host", [
1521
+ { kind: "host", note: "host aborted the model request" }
1522
+ ]);
1523
+ yield* events;
1524
+ return result;
1525
+ }
1406
1526
  if (!canRetry) {
1407
1527
  const { events, result } = await fail({
1408
1528
  ...base,
@@ -1478,7 +1598,7 @@ async function* runLoop(cfg) {
1478
1598
  }
1479
1599
  }
1480
1600
  ]);
1481
- if (interruptions.length > 0) {
1601
+ if (interruptions.length > 0 || calls.length > 0 && isStopped(cfg.signal)) {
1482
1602
  const { events, result } = await pause(pauseReasonOf(interruptions), interruptions);
1483
1603
  yield* events;
1484
1604
  return result;
@@ -1573,6 +1693,7 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1573
1693
  };
1574
1694
  const decisions = /* @__PURE__ */ new Map();
1575
1695
  const requested = /* @__PURE__ */ new Set();
1696
+ const started = startedToolCallIds(timeline);
1576
1697
  for (const raw of timeline) {
1577
1698
  const e = raw;
1578
1699
  if (e.type === "core.approval_decision") decisions.set(e.payload.toolCallId, e.payload);
@@ -1593,6 +1714,10 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1593
1714
  provenance: { source: name },
1594
1715
  payload: { toolCallId, name, content: [{ type: "text", text }], isError: true }
1595
1716
  });
1717
+ if (started.has(toolCallId) && (tool === void 0 || !isReplayable(tool))) {
1718
+ yield* await settle(errorResult(OUTCOME_UNKNOWN_TEXT));
1719
+ continue;
1720
+ }
1596
1721
  const decided = decisions.get(toolCallId);
1597
1722
  if (decided && !decided.approved) {
1598
1723
  yield* await append([errorResult(`Approval denied${decided.reason ? `: ${decided.reason}` : ""}`)]);
@@ -1665,11 +1790,23 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1665
1790
  batch.held.push(toolCallId);
1666
1791
  continue;
1667
1792
  }
1793
+ if (cfg.signal?.aborted) break;
1794
+ const replayable = isReplayable(tool);
1795
+ const markStarted = async function* () {
1796
+ if (started.has(toolCallId)) return;
1797
+ started.add(toolCallId);
1798
+ yield* await flush();
1799
+ yield* await append([
1800
+ { type: "core.tool_started", actor: "system", parentId: call.id, payload: { toolCallId } }
1801
+ ]);
1802
+ };
1803
+ if (!replayable) yield* markStarted();
1668
1804
  let result;
1669
1805
  try {
1670
1806
  summary.executed++;
1671
1807
  const out = await tool.execute(args, toolCtx);
1672
1808
  if (isSubagentPause(out)) {
1809
+ yield* markStarted();
1673
1810
  summary.interruptions.push({ kind: "subagent", toolCallId, call: call.payload, ...out.detail });
1674
1811
  batch.held.push(toolCallId);
1675
1812
  if (cfg.signal?.aborted) break;
@@ -1686,7 +1823,9 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1686
1823
  payload: { toolCallId, name, content: normalized.content, isError: normalized.isError ?? false }
1687
1824
  };
1688
1825
  } catch (err) {
1689
- result = errorResult(`Tool execution failed: ${errorMessageOf(err)}`);
1826
+ result = errorResult(
1827
+ !replayable && cfg.signal?.aborted ? OUTCOME_UNKNOWN_TEXT : `Tool execution failed: ${errorMessageOf(err)}`
1828
+ );
1690
1829
  }
1691
1830
  for (const s of sockets) {
1692
1831
  const replaced = await s.afterTool?.(ctx, call, result);
@@ -1970,7 +2109,7 @@ function memoryStore() {
1970
2109
  }
1971
2110
 
1972
2111
  // src/index.ts
1973
- var REINS_VERSION = "0.9.0";
2112
+ var REINS_VERSION = "0.10.0";
1974
2113
  export {
1975
2114
  BUILTIN_APPROVAL_POLICY,
1976
2115
  CORE_SCHEMAS,
@@ -1984,13 +2123,20 @@ export {
1984
2123
  DEFAULT_TRUST,
1985
2124
  EventSchemaRegistry,
1986
2125
  INPUT_DRAFT_TYPES,
2126
+ INTERRUPTED_IN_PROGRESS_TEXT,
2127
+ INTERRUPTED_NOT_EXECUTED_TEXT,
1987
2128
  InMemoryBlobStore,
1988
2129
  InMemoryEventLog,
1989
2130
  InMemoryMemoryStore,
1990
2131
  InMemoryRunLease,
1991
2132
  LoweringError,
2133
+ OUTCOME_UNKNOWN_TEXT,
1992
2134
  REINS_VERSION,
1993
2135
  RunStateError,
2136
+ RunStop,
2137
+ STOPPED_IN_PROGRESS_TEXT,
2138
+ STOPPED_NOTE,
2139
+ STOPPED_NOT_EXECUTED_TEXT,
1994
2140
  SchemaError,
1995
2141
  StoreError,
1996
2142
  UNTRUSTED_CLOSE_TAG,
@@ -1999,7 +2145,9 @@ export {
1999
2145
  backoffDelayMs,
2000
2146
  budgetTruncate,
2001
2147
  computeConfigHash,
2148
+ computeModelDigest,
2002
2149
  computePendingDigest,
2150
+ computePendingToolsDigest,
2003
2151
  contextOverheadOf,
2004
2152
  contextTokensOf,
2005
2153
  covers,
@@ -2027,6 +2175,9 @@ export {
2027
2175
  isContentPart,
2028
2176
  isModelOutput,
2029
2177
  isPinNote,
2178
+ isReplayable,
2179
+ isStopReason,
2180
+ isStopped,
2030
2181
  isSubagentPause,
2031
2182
  isTransientFailure,
2032
2183
  keptBy,
@@ -2053,7 +2204,9 @@ export {
2053
2204
  serializeRunState,
2054
2205
  signRunState,
2055
2206
  splitTurns,
2207
+ startedToolCallIds,
2056
2208
  statusFromMessage,
2209
+ stopTextsOf,
2057
2210
  subagentPause,
2058
2211
  supersededIds,
2059
2212
  toolBatchOf,