@reinsjs/core 0.9.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/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
 
@@ -1120,6 +1199,35 @@ function inputDrafts(input) {
1120
1199
  }
1121
1200
  return [checkInputDraft(input)];
1122
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
+ }
1123
1231
  function isInputArray(input) {
1124
1232
  return Array.isArray(input);
1125
1233
  }
@@ -1157,14 +1265,44 @@ async function* runLoop(cfg) {
1157
1265
  lastSeq += events.length;
1158
1266
  return events;
1159
1267
  };
1160
- const pause = async (reason, interruptions) => {
1161
- const events = await append([{ type: "core.run_paused", actor: "system", payload: { reason } }]);
1268
+ const settleStopped = async (texts) => {
1269
+ const timeline = await readTimeline(log, sessionId, { registry });
1270
+ const pending = pendingToolCalls(timeline);
1271
+ if (pending.length === 0) return [];
1272
+ const started = startedToolCallIds(timeline);
1273
+ return append(
1274
+ pending.map((call) => {
1275
+ const { toolCallId, name } = call.payload;
1276
+ const tool = baseTools.find((t) => t.name === name);
1277
+ const text = !started.has(toolCallId) ? texts.notExecuted : tool !== void 0 && isReplayable(tool) ? texts.inProgress : OUTCOME_UNKNOWN_TEXT;
1278
+ return {
1279
+ type: "core.tool_result",
1280
+ actor: "tool",
1281
+ parentId: call.id,
1282
+ provenance: { source: name },
1283
+ payload: { toolCallId, name, content: [{ type: "text", text }], isError: true }
1284
+ };
1285
+ })
1286
+ );
1287
+ };
1288
+ const pause = async (requested, requestedInterruptions) => {
1289
+ const stopped = isStopped(cfg.signal);
1290
+ const texts = stopped ? stopTextsOf(cfg.signal?.reason) : void 0;
1291
+ const reason = texts ? "host" : requested;
1292
+ const interruptions = texts ? [{ kind: "host", note: texts.note }] : requestedInterruptions;
1293
+ const settled = texts ? await settleStopped(texts) : [];
1294
+ const events = [
1295
+ ...settled,
1296
+ ...await append([{ type: "core.run_paused", actor: "system", payload: { reason } }])
1297
+ ];
1162
1298
  const pending = pendingToolCalls(await readTimeline(log, sessionId, { registry }));
1163
1299
  const state = await serializeRunState({
1164
1300
  sessionId,
1165
1301
  lastSeq,
1166
1302
  pending,
1167
1303
  configHash,
1304
+ model,
1305
+ tools: baseTools,
1168
1306
  ...cfg.secret !== void 0 ? { secret: cfg.secret } : {}
1169
1307
  });
1170
1308
  return { events, result: { status: "paused", sessionId, lastSeq, reason, interruptions, state } };
@@ -1192,6 +1330,8 @@ async function* runLoop(cfg) {
1192
1330
  sessionId,
1193
1331
  timeline,
1194
1332
  configHash,
1333
+ model,
1334
+ tools: baseTools,
1195
1335
  ...cfg.secret !== void 0 ? { secret: cfg.secret } : {},
1196
1336
  ...cfg.allowConfigDrift !== void 0 ? { allowConfigDrift: cfg.allowConfigDrift } : {}
1197
1337
  });
@@ -1228,18 +1368,72 @@ async function* runLoop(cfg) {
1228
1368
  }))
1229
1369
  );
1230
1370
  }
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
- );
1371
+ if (!cfg.signal?.aborted) {
1372
+ yield* await append(
1373
+ toolsBoundDrafts({
1374
+ timeline: await readTimeline(log, sessionId, { registry }),
1375
+ toolNames: baseTools.map((t) => t.name),
1376
+ configHash,
1377
+ announce: cfg.announceToolChanges ?? true
1378
+ })
1379
+ );
1380
+ }
1239
1381
  yield* await append(input.map((d) => withResultTrust(d, baseTools)));
1240
1382
  while (true) {
1383
+ if (cfg.signal?.aborted) {
1384
+ const { events, result } = await pause("host", [
1385
+ { kind: "host", note: "host aborted before this turn started" }
1386
+ ]);
1387
+ yield* events;
1388
+ return result;
1389
+ }
1241
1390
  const turnStartedAt = now();
1242
- 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
+ }
1243
1437
  const lastUsage = lastBudgetUsage(timeline)?.payload.tokens;
1244
1438
  const projected = project({
1245
1439
  timeline,
@@ -1290,13 +1484,6 @@ async function* runLoop(cfg) {
1290
1484
  const events = await append(emitted.splice(0));
1291
1485
  return events;
1292
1486
  };
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
1487
  const pending = pendingToolCalls(timeline);
1301
1488
  if (pending.length > 0) {
1302
1489
  const located = toolBatchOf(timeline, pending);
@@ -1313,7 +1500,7 @@ async function* runLoop(cfg) {
1313
1500
  batch
1314
1501
  });
1315
1502
  toolCallsTotal += settled.executed;
1316
- if (settled.interruptions.length > 0) {
1503
+ if (settled.interruptions.length > 0 || isStopped(cfg.signal)) {
1317
1504
  const reason = pauseReasonOf(settled.interruptions);
1318
1505
  const { events, result } = await pause(reason, settled.interruptions);
1319
1506
  yield* events;
@@ -1403,6 +1590,13 @@ async function* runLoop(cfg) {
1403
1590
  message: failure.message,
1404
1591
  detail: { usage: outcome?.usage }
1405
1592
  };
1593
+ if (!canRetry && cfg.signal?.aborted) {
1594
+ const { events, result } = await pause("host", [
1595
+ { kind: "host", note: "host aborted the model request" }
1596
+ ]);
1597
+ yield* events;
1598
+ return result;
1599
+ }
1406
1600
  if (!canRetry) {
1407
1601
  const { events, result } = await fail({
1408
1602
  ...base,
@@ -1478,7 +1672,7 @@ async function* runLoop(cfg) {
1478
1672
  }
1479
1673
  }
1480
1674
  ]);
1481
- if (interruptions.length > 0) {
1675
+ if (interruptions.length > 0 || calls.length > 0 && isStopped(cfg.signal)) {
1482
1676
  const { events, result } = await pause(pauseReasonOf(interruptions), interruptions);
1483
1677
  yield* events;
1484
1678
  return result;
@@ -1573,6 +1767,7 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1573
1767
  };
1574
1768
  const decisions = /* @__PURE__ */ new Map();
1575
1769
  const requested = /* @__PURE__ */ new Set();
1770
+ const started = startedToolCallIds(timeline);
1576
1771
  for (const raw of timeline) {
1577
1772
  const e = raw;
1578
1773
  if (e.type === "core.approval_decision") decisions.set(e.payload.toolCallId, e.payload);
@@ -1593,6 +1788,10 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1593
1788
  provenance: { source: name },
1594
1789
  payload: { toolCallId, name, content: [{ type: "text", text }], isError: true }
1595
1790
  });
1791
+ if (started.has(toolCallId) && (tool === void 0 || !isReplayable(tool))) {
1792
+ yield* await settle(errorResult(OUTCOME_UNKNOWN_TEXT));
1793
+ continue;
1794
+ }
1596
1795
  const decided = decisions.get(toolCallId);
1597
1796
  if (decided && !decided.approved) {
1598
1797
  yield* await append([errorResult(`Approval denied${decided.reason ? `: ${decided.reason}` : ""}`)]);
@@ -1665,11 +1864,23 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1665
1864
  batch.held.push(toolCallId);
1666
1865
  continue;
1667
1866
  }
1867
+ if (cfg.signal?.aborted) break;
1868
+ const replayable = isReplayable(tool);
1869
+ const markStarted = async function* () {
1870
+ if (started.has(toolCallId)) return;
1871
+ started.add(toolCallId);
1872
+ yield* await flush();
1873
+ yield* await append([
1874
+ { type: "core.tool_started", actor: "system", parentId: call.id, payload: { toolCallId } }
1875
+ ]);
1876
+ };
1877
+ if (!replayable) yield* markStarted();
1668
1878
  let result;
1669
1879
  try {
1670
1880
  summary.executed++;
1671
1881
  const out = await tool.execute(args, toolCtx);
1672
1882
  if (isSubagentPause(out)) {
1883
+ yield* markStarted();
1673
1884
  summary.interruptions.push({ kind: "subagent", toolCallId, call: call.payload, ...out.detail });
1674
1885
  batch.held.push(toolCallId);
1675
1886
  if (cfg.signal?.aborted) break;
@@ -1686,7 +1897,9 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1686
1897
  payload: { toolCallId, name, content: normalized.content, isError: normalized.isError ?? false }
1687
1898
  };
1688
1899
  } catch (err) {
1689
- result = errorResult(`Tool execution failed: ${errorMessageOf(err)}`);
1900
+ result = errorResult(
1901
+ !replayable && cfg.signal?.aborted ? OUTCOME_UNKNOWN_TEXT : `Tool execution failed: ${errorMessageOf(err)}`
1902
+ );
1690
1903
  }
1691
1904
  for (const s of sockets) {
1692
1905
  const replaced = await s.afterTool?.(ctx, call, result);
@@ -1970,7 +2183,7 @@ function memoryStore() {
1970
2183
  }
1971
2184
 
1972
2185
  // src/index.ts
1973
- var REINS_VERSION = "0.9.0";
2186
+ var REINS_VERSION = "0.11.0";
1974
2187
  export {
1975
2188
  BUILTIN_APPROVAL_POLICY,
1976
2189
  CORE_SCHEMAS,
@@ -1984,13 +2197,20 @@ export {
1984
2197
  DEFAULT_TRUST,
1985
2198
  EventSchemaRegistry,
1986
2199
  INPUT_DRAFT_TYPES,
2200
+ INTERRUPTED_IN_PROGRESS_TEXT,
2201
+ INTERRUPTED_NOT_EXECUTED_TEXT,
1987
2202
  InMemoryBlobStore,
1988
2203
  InMemoryEventLog,
1989
2204
  InMemoryMemoryStore,
1990
2205
  InMemoryRunLease,
1991
2206
  LoweringError,
2207
+ OUTCOME_UNKNOWN_TEXT,
1992
2208
  REINS_VERSION,
1993
2209
  RunStateError,
2210
+ RunStop,
2211
+ STOPPED_IN_PROGRESS_TEXT,
2212
+ STOPPED_NOTE,
2213
+ STOPPED_NOT_EXECUTED_TEXT,
1994
2214
  SchemaError,
1995
2215
  StoreError,
1996
2216
  UNTRUSTED_CLOSE_TAG,
@@ -1999,7 +2219,9 @@ export {
1999
2219
  backoffDelayMs,
2000
2220
  budgetTruncate,
2001
2221
  computeConfigHash,
2222
+ computeModelDigest,
2002
2223
  computePendingDigest,
2224
+ computePendingToolsDigest,
2003
2225
  contextOverheadOf,
2004
2226
  contextTokensOf,
2005
2227
  covers,
@@ -2027,6 +2249,9 @@ export {
2027
2249
  isContentPart,
2028
2250
  isModelOutput,
2029
2251
  isPinNote,
2252
+ isReplayable,
2253
+ isStopReason,
2254
+ isStopped,
2030
2255
  isSubagentPause,
2031
2256
  isTransientFailure,
2032
2257
  keptBy,
@@ -2053,7 +2278,9 @@ export {
2053
2278
  serializeRunState,
2054
2279
  signRunState,
2055
2280
  splitTurns,
2281
+ startedToolCallIds,
2056
2282
  statusFromMessage,
2283
+ stopTextsOf,
2057
2284
  subagentPause,
2058
2285
  supersededIds,
2059
2286
  toolBatchOf,