@reinsjs/core 0.13.0 → 0.14.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-3QMUURRG.js";
11
+ } from "./chunk-DFXHUJV4.js";
12
12
 
13
13
  // src/events/core.ts
14
14
  function contextTokensOf(usage) {
@@ -35,7 +35,8 @@ var DEFAULT_MODEL_INVISIBLE_TYPES = /* @__PURE__ */ new Set([
35
35
  "core.handoff",
36
36
  "core.error",
37
37
  "core.tools_bound",
38
- "core.tool_started"
38
+ "core.tool_started",
39
+ "core.run_ended"
39
40
  ]);
40
41
  function visibilityFilter(opts = {}) {
41
42
  const invisible = opts.invisibleTypes ? new Set(opts.invisibleTypes) : DEFAULT_MODEL_INVISIBLE_TYPES;
@@ -813,6 +814,159 @@ async function readTimeline(log, sessionId, opts) {
813
814
  return out;
814
815
  }
815
816
 
817
+ // src/loop/tools.ts
818
+ function toolResultTrust(tool, isError) {
819
+ if (!tool || tool.resultTrust === void 0 || isError) return void 0;
820
+ return tool.resultTrust;
821
+ }
822
+ function isClientTool(tool) {
823
+ return !tool.execute || tool.side === "client";
824
+ }
825
+ function defineTool(tool) {
826
+ return tool;
827
+ }
828
+ function toolSpecOf(tool) {
829
+ return { name: tool.name, description: tool.description, inputSchema: tool.inputSchema };
830
+ }
831
+ function deferredToolSpecOf(tool, deferred) {
832
+ return deferred ? { ...toolSpecOf(tool), deferLoading: true } : toolSpecOf(tool);
833
+ }
834
+ function isDuration(x) {
835
+ return x === void 0 || typeof x === "number" && Number.isFinite(x) && x > 0;
836
+ }
837
+ function isContentPart(x) {
838
+ if (typeof x !== "object" || x === null) return false;
839
+ const p = x;
840
+ switch (p.type) {
841
+ case "text":
842
+ return typeof p.text === "string";
843
+ case "image":
844
+ return typeof p.mime === "string" && typeof p.data === "string";
845
+ case "video":
846
+ case "audio":
847
+ return typeof p.mime === "string" && p.mime.startsWith(`${p.type}/`) && typeof p.data === "string" && isDuration(p.durationSec);
848
+ case "tool_reference":
849
+ return typeof p.name === "string" && typeof p.description === "string" && typeof p.inputSchema === "object" && p.inputSchema !== null && !Array.isArray(p.inputSchema);
850
+ default:
851
+ return false;
852
+ }
853
+ }
854
+ function isToolResult(x) {
855
+ if (typeof x !== "object" || x === null) return false;
856
+ const r = x;
857
+ return Array.isArray(r.content) && r.content.every(isContentPart) && (r.isError === void 0 || typeof r.isError === "boolean");
858
+ }
859
+ function normalizeToolOutput(output) {
860
+ if (typeof output === "string") return { content: [{ type: "text", text: output }] };
861
+ if (output === void 0 || output === null) return { content: [{ type: "text", text: "" }] };
862
+ if (Array.isArray(output) && output.every(isContentPart)) return { content: output };
863
+ if (isToolResult(output)) return output;
864
+ const json = JSON.stringify(output);
865
+ return { content: [{ type: "text", text: typeof json === "string" ? json : String(output) }] };
866
+ }
867
+ function errorMessageOf(err) {
868
+ if (err instanceof Error) return err.message;
869
+ return typeof err === "string" ? err : JSON.stringify(err) ?? String(err);
870
+ }
871
+
872
+ // src/loop/run-status.ts
873
+ var RUN_MARKER_TYPES = ["core.tools_bound", "core.run_paused", "core.run_ended"];
874
+ var MARKER_SET = new Set(RUN_MARKER_TYPES);
875
+ function lastRunMarker(events) {
876
+ for (let i = events.length - 1; i >= 0; i--) {
877
+ const e = events[i];
878
+ if (e !== void 0 && MARKER_SET.has(e.type)) return e;
879
+ }
880
+ return void 0;
881
+ }
882
+ function awaitingOf(input) {
883
+ const requestedAt = /* @__PURE__ */ new Map();
884
+ const decided = /* @__PURE__ */ new Set();
885
+ for (const raw of input.timeline) {
886
+ const id = raw.payload?.toolCallId;
887
+ if (typeof id !== "string") continue;
888
+ if (raw.type === "core.approval_request" && !requestedAt.has(id)) requestedAt.set(id, raw.at);
889
+ if (raw.type === "core.approval_decision") decided.add(id);
890
+ }
891
+ const awaiting = [];
892
+ for (const call of input.pending) {
893
+ const { toolCallId, name } = call.payload;
894
+ const at = requestedAt.get(toolCallId);
895
+ if (at !== void 0 && !decided.has(toolCallId)) {
896
+ awaiting.push({ kind: "approval", toolCallId, name, requestedAt: at });
897
+ continue;
898
+ }
899
+ const tool = input.tools.find((t) => t.name === name);
900
+ if (tool !== void 0 && isClientTool(tool)) {
901
+ awaiting.push({ kind: "client_tool", toolCallId, name });
902
+ continue;
903
+ }
904
+ const sub = input.interruptions.find((i) => i.kind === "subagent" && i.toolCallId === toolCallId);
905
+ if (sub?.kind === "subagent") {
906
+ awaiting.push({
907
+ kind: "subagent",
908
+ toolCallId,
909
+ name,
910
+ childSessionId: sub.childSessionId,
911
+ reason: sub.reason
912
+ });
913
+ }
914
+ }
915
+ return awaiting;
916
+ }
917
+ var PAUSE_REASONS = /* @__PURE__ */ new Set(["approval", "budget", "host"]);
918
+ var isNonEmptyString = (x) => typeof x === "string" && x !== "";
919
+ function isAwaitingCall(x) {
920
+ if (typeof x !== "object" || x === null) return false;
921
+ const a = x;
922
+ if (!isNonEmptyString(a.toolCallId) || typeof a.name !== "string") return false;
923
+ if (a.kind === "approval") return typeof a.requestedAt === "number" && Number.isFinite(a.requestedAt);
924
+ if (a.kind === "client_tool") return true;
925
+ if (a.kind === "subagent")
926
+ return isNonEmptyString(a.childSessionId) && typeof a.reason === "string" && PAUSE_REASONS.has(a.reason);
927
+ return false;
928
+ }
929
+ function runStatusOf(input) {
930
+ if (input.held) return { state: "running" };
931
+ if (input.lastMarker === void 0) return { state: "idle" };
932
+ let marker;
933
+ try {
934
+ marker = (input.registry ?? createCoreRegistry()).read(input.lastMarker);
935
+ } catch {
936
+ return { state: "unknown" };
937
+ }
938
+ const p = typeof marker.payload === "object" && marker.payload !== null ? marker.payload : {};
939
+ const { seq, at } = marker;
940
+ switch (marker.type) {
941
+ case "core.tools_bound":
942
+ return p.marksEnd === true ? { state: "interrupted", seq, startedAt: at } : { state: "unknown" };
943
+ case "core.run_paused": {
944
+ if (typeof p.reason !== "string" || !PAUSE_REASONS.has(p.reason)) return { state: "unknown" };
945
+ if (p.stopped !== void 0 && p.stopped !== true) return { state: "unknown" };
946
+ if (p.awaiting !== void 0 && !(Array.isArray(p.awaiting) && p.awaiting.every(isAwaitingCall)))
947
+ return { state: "unknown" };
948
+ return {
949
+ state: "paused",
950
+ seq,
951
+ endedAt: at,
952
+ reason: p.reason,
953
+ stopped: p.stopped === true,
954
+ awaiting: p.awaiting
955
+ };
956
+ }
957
+ case "core.run_ended": {
958
+ if (p.status === "done") return { state: "done", seq, endedAt: at };
959
+ if (p.status === "handoff" && isNonEmptyString(p.toSessionId))
960
+ return { state: "handoff", seq, endedAt: at, toSessionId: p.toSessionId };
961
+ if (p.status === "error" && typeof p.category === "string")
962
+ return { state: "error", seq, endedAt: at, category: p.category };
963
+ return { state: "unknown" };
964
+ }
965
+ default:
966
+ return { state: "unknown" };
967
+ }
968
+ }
969
+
816
970
  // src/loop/state.ts
817
971
  function pendingToolCalls(timeline) {
818
972
  const answered = /* @__PURE__ */ new Set();
@@ -1058,58 +1212,6 @@ function isSubagentPause(value) {
1058
1212
  return typeof value === "object" && value !== null && value[SUBAGENT_PAUSE] === true;
1059
1213
  }
1060
1214
 
1061
- // src/loop/tools.ts
1062
- function toolResultTrust(tool, isError) {
1063
- if (!tool || tool.resultTrust === void 0 || isError) return void 0;
1064
- return tool.resultTrust;
1065
- }
1066
- function defineTool(tool) {
1067
- return tool;
1068
- }
1069
- function toolSpecOf(tool) {
1070
- return { name: tool.name, description: tool.description, inputSchema: tool.inputSchema };
1071
- }
1072
- function deferredToolSpecOf(tool, deferred) {
1073
- return deferred ? { ...toolSpecOf(tool), deferLoading: true } : toolSpecOf(tool);
1074
- }
1075
- function isDuration(x) {
1076
- return x === void 0 || typeof x === "number" && Number.isFinite(x) && x > 0;
1077
- }
1078
- function isContentPart(x) {
1079
- if (typeof x !== "object" || x === null) return false;
1080
- const p = x;
1081
- switch (p.type) {
1082
- case "text":
1083
- return typeof p.text === "string";
1084
- case "image":
1085
- return typeof p.mime === "string" && typeof p.data === "string";
1086
- case "video":
1087
- case "audio":
1088
- return typeof p.mime === "string" && p.mime.startsWith(`${p.type}/`) && typeof p.data === "string" && isDuration(p.durationSec);
1089
- case "tool_reference":
1090
- return typeof p.name === "string" && typeof p.description === "string" && typeof p.inputSchema === "object" && p.inputSchema !== null && !Array.isArray(p.inputSchema);
1091
- default:
1092
- return false;
1093
- }
1094
- }
1095
- function isToolResult(x) {
1096
- if (typeof x !== "object" || x === null) return false;
1097
- const r = x;
1098
- return Array.isArray(r.content) && r.content.every(isContentPart) && (r.isError === void 0 || typeof r.isError === "boolean");
1099
- }
1100
- function normalizeToolOutput(output) {
1101
- if (typeof output === "string") return { content: [{ type: "text", text: output }] };
1102
- if (output === void 0 || output === null) return { content: [{ type: "text", text: "" }] };
1103
- if (Array.isArray(output) && output.every(isContentPart)) return { content: output };
1104
- if (isToolResult(output)) return output;
1105
- const json = JSON.stringify(output);
1106
- return { content: [{ type: "text", text: typeof json === "string" ? json : String(output) }] };
1107
- }
1108
- function errorMessageOf(err) {
1109
- if (err instanceof Error) return err.message;
1110
- return typeof err === "string" ? err : JSON.stringify(err) ?? String(err);
1111
- }
1112
-
1113
1215
  // src/loop/tools-bound.ts
1114
1216
  function lastToolsBound(timeline) {
1115
1217
  for (let i = timeline.length - 1; i >= 0; i--) {
@@ -1136,7 +1238,15 @@ function renderToolChangeNote(diff) {
1136
1238
  function toolsBoundDrafts(input) {
1137
1239
  const toolNames = [...input.toolNames].sort();
1138
1240
  const drafts = [
1139
- { type: "core.tools_bound", actor: "system", payload: { toolNames, configHash: input.configHash } }
1241
+ {
1242
+ type: "core.tools_bound",
1243
+ actor: "system",
1244
+ payload: {
1245
+ toolNames,
1246
+ configHash: input.configHash,
1247
+ ...input.marksEnd ? { marksEnd: true } : {}
1248
+ }
1249
+ }
1140
1250
  ];
1141
1251
  const previous = lastToolsBound(input.timeline);
1142
1252
  if (!input.announce || previous === void 0) return drafts;
@@ -1316,7 +1426,9 @@ async function* runLoop(cfg) {
1316
1426
  const reason = texts ? "host" : requested;
1317
1427
  const interruptions = texts ? [{ kind: "host", note: texts.note }] : requestedInterruptions;
1318
1428
  const settled = texts ? await settleStopped(texts) : [];
1319
- const pending = pendingToolCalls(await readTimeline(log, sessionId, { registry }));
1429
+ const timeline = await readTimeline(log, sessionId, { registry });
1430
+ const pending = pendingToolCalls(timeline);
1431
+ const awaiting = awaitingOf({ timeline, pending, tools: baseTools, interruptions });
1320
1432
  const state = await serializeRunState({
1321
1433
  sessionId,
1322
1434
  lastSeq: lastSeq + 1,
@@ -1328,7 +1440,13 @@ async function* runLoop(cfg) {
1328
1440
  });
1329
1441
  const events = [
1330
1442
  ...settled,
1331
- ...await append([{ type: "core.run_paused", actor: "system", payload: { reason, state } }])
1443
+ ...await append([
1444
+ {
1445
+ type: "core.run_paused",
1446
+ actor: "system",
1447
+ payload: { reason, state, awaiting, ...texts ? { stopped: true } : {} }
1448
+ }
1449
+ ])
1332
1450
  ];
1333
1451
  return { events, result: { status: "paused", sessionId, lastSeq, reason, interruptions, state } };
1334
1452
  };
@@ -1337,7 +1455,10 @@ async function* runLoop(cfg) {
1337
1455
  ctx.budget.tokensSpent = tokensSpent;
1338
1456
  };
1339
1457
  const fail = async (payload) => {
1340
- const events = await append([{ type: "core.error", actor: "system", payload }]);
1458
+ const events = await append([
1459
+ { type: "core.error", actor: "system", payload },
1460
+ { type: "core.run_ended", actor: "system", payload: { status: "error", category: payload.category } }
1461
+ ]);
1341
1462
  const error = events[0];
1342
1463
  return { events, result: { status: "error", sessionId, lastSeq, error } };
1343
1464
  };
@@ -1347,7 +1468,8 @@ async function* runLoop(cfg) {
1347
1468
  const forwardedDecisions = (cfg.decisions ?? []).filter(
1348
1469
  (d) => d.sessionId !== void 0 && d.sessionId !== sessionId
1349
1470
  );
1350
- if (cfg.resume !== void 0 || ownDecisions.length > 0) {
1471
+ const resuming = cfg.resume !== void 0 || ownDecisions.length > 0;
1472
+ if (resuming) {
1351
1473
  const timeline = await readTimeline(log, sessionId, { registry });
1352
1474
  if (cfg.resume !== void 0) {
1353
1475
  await validateResume({
@@ -1374,6 +1496,20 @@ async function* runLoop(cfg) {
1374
1496
  );
1375
1497
  }
1376
1498
  }
1499
+ }
1500
+ if (!cfg.signal?.aborted) {
1501
+ yield* await append(
1502
+ toolsBoundDrafts({
1503
+ timeline: await readTimeline(log, sessionId, { registry }),
1504
+ toolNames: baseTools.map((t) => t.name),
1505
+ configHash,
1506
+ announce: cfg.announceToolChanges ?? true,
1507
+ marksEnd: true
1508
+ })
1509
+ );
1510
+ }
1511
+ if (resuming) {
1512
+ const decisions = ownDecisions;
1377
1513
  if (cfg.resume !== void 0) {
1378
1514
  const by = decisions[0]?.by;
1379
1515
  yield* await append([
@@ -1393,16 +1529,6 @@ async function* runLoop(cfg) {
1393
1529
  }))
1394
1530
  );
1395
1531
  }
1396
- if (!cfg.signal?.aborted) {
1397
- yield* await append(
1398
- toolsBoundDrafts({
1399
- timeline: await readTimeline(log, sessionId, { registry }),
1400
- toolNames: baseTools.map((t) => t.name),
1401
- configHash,
1402
- announce: cfg.announceToolChanges ?? true
1403
- })
1404
- );
1405
- }
1406
1532
  yield* await append(input.map((d) => withResultTrust(d, baseTools)));
1407
1533
  while (true) {
1408
1534
  if (cfg.signal?.aborted) {
@@ -1716,7 +1842,10 @@ async function* runLoop(cfg) {
1716
1842
  }
1717
1843
  yield* await flush();
1718
1844
  if (decision === "continue") return void 0;
1719
- if (decision === "stop") return { status: "done", sessionId, lastSeq };
1845
+ if (decision === "stop") {
1846
+ yield* await append([{ type: "core.run_ended", actor: "system", payload: { status: "done" } }]);
1847
+ return { status: "done", sessionId, lastSeq };
1848
+ }
1720
1849
  if ("pause" in decision) {
1721
1850
  const note = decision.pause.note ?? `a socket requested a pause (${decision.pause.reason})`;
1722
1851
  const kind = decision.pause.reason;
@@ -1755,6 +1884,9 @@ async function* runLoop(cfg) {
1755
1884
  );
1756
1885
  await log.append(openingEvents);
1757
1886
  yield* openingEvents;
1887
+ yield* await append([
1888
+ { type: "core.run_ended", actor: "system", payload: { status: "handoff", toSessionId } }
1889
+ ]);
1758
1890
  await cfg.onHandoff?.(sessionId, toSessionId);
1759
1891
  return { status: "handoff", sessionId, lastSeq, toSessionId };
1760
1892
  }
@@ -1884,7 +2016,7 @@ async function* executeToolCalls(ctx, calls, timeline, deps) {
1884
2016
  batch.held.push(toolCallId);
1885
2017
  continue;
1886
2018
  }
1887
- if (!tool.execute || tool.side === "client") {
2019
+ if (isClientTool(tool) || !tool.execute) {
1888
2020
  summary.interruptions.push({ kind: "client_tool", toolCallId, call: call.payload });
1889
2021
  batch.held.push(toolCallId);
1890
2022
  continue;
@@ -2211,7 +2343,7 @@ function memoryStore() {
2211
2343
  }
2212
2344
 
2213
2345
  // src/index.ts
2214
- var REINS_VERSION = "0.13.0";
2346
+ var REINS_VERSION = "0.14.0";
2215
2347
  export {
2216
2348
  BUILTIN_APPROVAL_POLICY,
2217
2349
  CORE_SCHEMAS,
@@ -2234,6 +2366,7 @@ export {
2234
2366
  LoweringError,
2235
2367
  OUTCOME_UNKNOWN_TEXT,
2236
2368
  REINS_VERSION,
2369
+ RUN_MARKER_TYPES,
2237
2370
  RunStateError,
2238
2371
  RunStop,
2239
2372
  STOPPED_IN_PROGRESS_TEXT,
@@ -2244,6 +2377,7 @@ export {
2244
2377
  UNTRUSTED_CLOSE_TAG,
2245
2378
  UNTRUSTED_TAG,
2246
2379
  assertRunStateShape,
2380
+ awaitingOf,
2247
2381
  backoffDelayMs,
2248
2382
  budgetTruncate,
2249
2383
  computeConfigHash,
@@ -2273,6 +2407,7 @@ export {
2273
2407
  foldedToolResults,
2274
2408
  forkSession,
2275
2409
  inputDrafts,
2410
+ isClientTool,
2276
2411
  isCompaction,
2277
2412
  isContentPart,
2278
2413
  isModelOutput,
@@ -2283,6 +2418,7 @@ export {
2283
2418
  isSubagentPause,
2284
2419
  isTransientFailure,
2285
2420
  keptBy,
2421
+ lastRunMarker,
2286
2422
  lastToolsBound,
2287
2423
  lossesOf,
2288
2424
  markUntrusted,
@@ -2305,6 +2441,7 @@ export {
2305
2441
  resolveSocketContributions,
2306
2442
  roughTokenEstimate,
2307
2443
  runLoop,
2444
+ runStatusOf,
2308
2445
  serializeRunState,
2309
2446
  signRunState,
2310
2447
  splitTurns,