motebit 1.8.3 → 1.9.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.
Files changed (2) hide show
  1. package/dist/index.js +788 -428
  2. package/package.json +14 -14
package/dist/index.js CHANGED
@@ -657,6 +657,16 @@ var init_eval_attestation = __esm({
657
657
  }
658
658
  });
659
659
 
660
+ // ../../packages/protocol/dist/routing-transcript.js
661
+ var ROUTING_TRANSCRIPT_SPEC_ID;
662
+ var init_routing_transcript = __esm({
663
+ "../../packages/protocol/dist/routing-transcript.js"() {
664
+ "use strict";
665
+ init_esm_shims();
666
+ ROUTING_TRANSCRIPT_SPEC_ID = "motebit/routing-transcript@1.0";
667
+ }
668
+ });
669
+
660
670
  // ../../packages/protocol/dist/merkle-tree-hash.js
661
671
  function isMerkleTreeVersion(value) {
662
672
  return typeof value === "string" && value in MERKLE_TREE_VERSION_REGISTRY;
@@ -889,7 +899,7 @@ function sensitivityPermits(upper, candidate) {
889
899
  function isSensitivityLevel(value) {
890
900
  return typeof value === "string" && ALL_SENSITIVITY_LEVELS.includes(value);
891
901
  }
892
- var SENSITIVITY_RANK, ALL_SENSITIVITY_LEVELS;
902
+ var SENSITIVITY_RANK, ALL_SENSITIVITY_LEVELS, CONTEXT_SAFE_SENSITIVITY;
893
903
  var init_sensitivity = __esm({
894
904
  "../../packages/protocol/dist/sensitivity.js"() {
895
905
  "use strict";
@@ -908,6 +918,7 @@ var init_sensitivity = __esm({
908
918
  "financial",
909
919
  "secret"
910
920
  ]);
921
+ CONTEXT_SAFE_SENSITIVITY = Object.freeze(ALL_SENSITIVITY_LEVELS.filter((l6) => rankSensitivity(l6) < rankSensitivity("medical")));
911
922
  }
912
923
  });
913
924
 
@@ -1283,6 +1294,7 @@ var init_dist = __esm({
1283
1294
  init_crypto_suite();
1284
1295
  init_evidence_provenance();
1285
1296
  init_eval_attestation();
1297
+ init_routing_transcript();
1286
1298
  init_merkle_tree_hash();
1287
1299
  init_retention_policy();
1288
1300
  init_computer_use();
@@ -4132,6 +4144,7 @@ __export(dist_exports, {
4132
4144
  COLOR_PRESETS: () => COLOR_PRESETS,
4133
4145
  COMPUTER_ACTION_KINDS: () => COMPUTER_ACTION_KINDS,
4134
4146
  COMPUTER_FAILURE_REASONS: () => COMPUTER_FAILURE_REASONS,
4147
+ CONTEXT_SAFE_SENSITIVITY: () => CONTEXT_SAFE_SENSITIVITY,
4135
4148
  CONVERSATION_LIST_ARTIFACT: () => CONVERSATION_LIST_ARTIFACT,
4136
4149
  CONVERSATION_MESSAGES_ARTIFACT: () => CONVERSATION_MESSAGES_ARTIFACT,
4137
4150
  CO_BROWSE_TRANSITION_KINDS: () => CO_BROWSE_TRANSITION_KINDS,
@@ -4206,6 +4219,7 @@ __export(dist_exports, {
4206
4219
  RESEARCH_TASK_SHAPE: () => RESEARCH_TASK_SHAPE,
4207
4220
  RISK_LABELS: () => RISK_LABELS,
4208
4221
  ROTATE_KEY_AUDIENCE: () => ROTATE_KEY_AUDIENCE,
4222
+ ROUTING_TRANSCRIPT_SPEC_ID: () => ROUTING_TRANSCRIPT_SPEC_ID,
4209
4223
  RUNTIME_ATTACH_AUDIENCE: () => RUNTIME_ATTACH_AUDIENCE,
4210
4224
  RUNTIME_RETENTION_REGISTRY: () => RUNTIME_RETENTION_REGISTRY,
4211
4225
  RegulatoryRiskSemiring: () => RegulatoryRiskSemiring,
@@ -6443,208 +6457,6 @@ var init_promotion = __esm({
6443
6457
  }
6444
6458
  });
6445
6459
 
6446
- // ../../packages/memory-graph/dist/memory-index.js
6447
- function resolveOptions(options) {
6448
- return {
6449
- maxBytes: options?.maxBytes ?? DEFAULT_INDEX_BYTE_BUDGET,
6450
- nowMs: options?.nowMs ?? Date.now(),
6451
- maxSummaryChars: options?.maxSummaryChars ?? DEFAULT_MAX_SUMMARY_CHARS
6452
- };
6453
- }
6454
- function classifyCertainty(confidence) {
6455
- if (confidence >= 0.95)
6456
- return "absolute";
6457
- if (confidence >= 0.7)
6458
- return "confident";
6459
- return "tentative";
6460
- }
6461
- function scoreForIndex(node, edgeCount, decayedConfidence2) {
6462
- const pinBonus = node.pinned ? 0.5 : 0;
6463
- const connectivityBonus = Math.log1p(edgeCount) * 0.15;
6464
- return decayedConfidence2 + pinBonus + connectivityBonus;
6465
- }
6466
- function rankIndexEntries(nodes, edges, options) {
6467
- const o5 = resolveOptions(options);
6468
- const liveNodes = nodes.filter((n2) => !n2.tombstoned);
6469
- const edgeCounts = /* @__PURE__ */ new Map();
6470
- for (const edge of edges) {
6471
- edgeCounts.set(edge.source_id, (edgeCounts.get(edge.source_id) ?? 0) + 1);
6472
- edgeCounts.set(edge.target_id, (edgeCounts.get(edge.target_id) ?? 0) + 1);
6473
- }
6474
- const entries = [];
6475
- for (const node of liveNodes) {
6476
- const edgeCount = edgeCounts.get(node.node_id) ?? 0;
6477
- const decayed = computeDecayedConfidence(node.confidence, node.half_life, o5.nowMs - node.created_at);
6478
- const score = scoreForIndex(node, edgeCount, decayed);
6479
- entries.push({
6480
- node,
6481
- certainty: classifyCertainty(decayed),
6482
- score,
6483
- edgeCount,
6484
- decayedConfidence: decayed
6485
- });
6486
- }
6487
- entries.sort((a3, b3) => {
6488
- if (b3.score !== a3.score)
6489
- return b3.score - a3.score;
6490
- if (b3.node.created_at !== a3.node.created_at)
6491
- return b3.node.created_at - a3.node.created_at;
6492
- return a3.node.node_id < b3.node.node_id ? -1 : 1;
6493
- });
6494
- return entries;
6495
- }
6496
- function renderLine(entry, maxSummaryChars) {
6497
- const shortId = entry.node.node_id.slice(0, 8);
6498
- const summary = entry.node.content.replace(/\s+/g, " ").trim().slice(0, maxSummaryChars);
6499
- const suffix = entry.node.pinned ? " [pinned]" : "";
6500
- const marker = entry.node.source !== void 0 ? MEMORY_SOURCE_MARKERS[entry.node.source] : MEMORY_SOURCE_MARKER_UNKNOWN;
6501
- return `- [${shortId}] ${summary} (${entry.certainty}, from:${marker})${suffix}`;
6502
- }
6503
- function buildMemoryIndex(nodes, edges, options) {
6504
- const o5 = resolveOptions(options);
6505
- const entries = rankIndexEntries(nodes, edges, options);
6506
- if (entries.length === 0)
6507
- return "";
6508
- const header = [
6509
- "# Memory Index (Layer 1)",
6510
- "Entries ranked by index-worthiness. Certainty: absolute | confident | tentative. Provenance: from:user is a direct user statement; every other from:* label (tool, peer-agent, inference, consolidation, unknown) is an absorbed, unverified claim. Pull full detail via recall; correct a stale entry via the `rewrite_memory` tool (node_id is the `[xxxxxxxx]` short id).",
6511
- ""
6512
- ];
6513
- const lines = [...header];
6514
- let bytesUsed = new Blob([lines.join("\n")]).size;
6515
- for (const entry of entries) {
6516
- const line = renderLine(entry, o5.maxSummaryChars);
6517
- const lineBytes = new Blob([line + "\n"]).size;
6518
- if (bytesUsed + lineBytes > o5.maxBytes)
6519
- break;
6520
- lines.push(line);
6521
- bytesUsed += lineBytes;
6522
- }
6523
- return lines.join("\n");
6524
- }
6525
- var DEFAULT_INDEX_BYTE_BUDGET, DEFAULT_MAX_SUMMARY_CHARS;
6526
- var init_memory_index = __esm({
6527
- "../../packages/memory-graph/dist/memory-index.js"() {
6528
- "use strict";
6529
- init_esm_shims();
6530
- init_dist2();
6531
- init_dist3();
6532
- DEFAULT_INDEX_BYTE_BUDGET = 2048;
6533
- DEFAULT_MAX_SUMMARY_CHARS = 120;
6534
- }
6535
- });
6536
-
6537
- // ../../packages/memory-graph/dist/embeddings.js
6538
- async function remoteEmbed(text) {
6539
- const res = await fetch(remoteEmbedUrl, {
6540
- method: "POST",
6541
- headers: { "Content-Type": "application/json" },
6542
- body: JSON.stringify({ texts: [text] }),
6543
- signal: AbortSignal.timeout(1e4)
6544
- });
6545
- const data = await res.json();
6546
- if (!data.ok || !data.embeddings?.[0]) {
6547
- throw new Error(data.error ?? "Remote embedding failed");
6548
- }
6549
- return data.embeddings[0];
6550
- }
6551
- async function getPipeline() {
6552
- if (pipelineInstance !== null)
6553
- return pipelineInstance;
6554
- if (pipelineFailed)
6555
- throw new Error("Pipeline previously failed to load");
6556
- try {
6557
- const { pipeline } = await import("@xenova/transformers");
6558
- pipelineInstance = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2");
6559
- return pipelineInstance;
6560
- } catch (e2) {
6561
- pipelineFailed = true;
6562
- throw e2;
6563
- }
6564
- }
6565
- async function embedText(text) {
6566
- if (text === "") {
6567
- return new Array(EMBEDDING_DIMENSIONS).fill(0);
6568
- }
6569
- if (remoteEmbedUrl) {
6570
- try {
6571
- return await remoteEmbed(text);
6572
- } catch {
6573
- }
6574
- }
6575
- try {
6576
- const extractor = await getPipeline();
6577
- const output = await extractor(text, { pooling: "mean", normalize: true });
6578
- return Array.from(output.data);
6579
- } catch {
6580
- const hash2 = embedTextHash(text);
6581
- const padded = new Array(EMBEDDING_DIMENSIONS).fill(0);
6582
- for (let i3 = 0; i3 < hash2.length; i3++) {
6583
- padded[i3] = hash2[i3];
6584
- }
6585
- return padded;
6586
- }
6587
- }
6588
- function tokenize(text) {
6589
- return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((t3) => t3.length > 0);
6590
- }
6591
- function hashToken(token) {
6592
- let h5 = 0;
6593
- for (let i3 = 0; i3 < token.length; i3++) {
6594
- h5 = h5 * 31 + token.charCodeAt(i3) | 0;
6595
- }
6596
- return (h5 % HASH_DIMENSIONS + HASH_DIMENSIONS) % HASH_DIMENSIONS;
6597
- }
6598
- function charTrigrams(token) {
6599
- const grams = [];
6600
- if (token.length < 3) {
6601
- grams.push(token);
6602
- } else {
6603
- for (let i3 = 0; i3 <= token.length - 3; i3++) {
6604
- grams.push(token.slice(i3, i3 + 3));
6605
- }
6606
- }
6607
- return grams;
6608
- }
6609
- function embedTextHash(text) {
6610
- const vec = new Array(HASH_DIMENSIONS).fill(0);
6611
- const tokens = tokenize(text);
6612
- for (const token of tokens) {
6613
- const bucket = hashToken(token);
6614
- vec[bucket] = (vec[bucket] ?? 0) + 1;
6615
- }
6616
- for (const token of tokens) {
6617
- const grams = charTrigrams(token);
6618
- for (const gram of grams) {
6619
- const bucket = hashToken("#" + gram);
6620
- vec[bucket] = (vec[bucket] ?? 0) + 0.5;
6621
- }
6622
- }
6623
- let norm = 0;
6624
- for (let i3 = 0; i3 < HASH_DIMENSIONS; i3++) {
6625
- norm += vec[i3] * vec[i3];
6626
- }
6627
- norm = Math.sqrt(norm);
6628
- if (norm > 0) {
6629
- for (let i3 = 0; i3 < HASH_DIMENSIONS; i3++) {
6630
- vec[i3] = vec[i3] / norm;
6631
- }
6632
- }
6633
- return vec;
6634
- }
6635
- var EMBEDDING_DIMENSIONS, remoteEmbedUrl, pipelineInstance, pipelineFailed, HASH_DIMENSIONS;
6636
- var init_embeddings = __esm({
6637
- "../../packages/memory-graph/dist/embeddings.js"() {
6638
- "use strict";
6639
- init_esm_shims();
6640
- EMBEDDING_DIMENSIONS = 384;
6641
- remoteEmbedUrl = null;
6642
- pipelineInstance = null;
6643
- pipelineFailed = false;
6644
- HASH_DIMENSIONS = 128;
6645
- }
6646
- });
6647
-
6648
6460
  // ../../packages/memory-graph/dist/retrieval.js
6649
6461
  var retrieval_exports = {};
6650
6462
  __export(retrieval_exports, {
@@ -6911,6 +6723,209 @@ var init_retrieval = __esm({
6911
6723
  }
6912
6724
  });
6913
6725
 
6726
+ // ../../packages/memory-graph/dist/memory-index.js
6727
+ function resolveOptions(options) {
6728
+ return {
6729
+ maxBytes: options?.maxBytes ?? DEFAULT_INDEX_BYTE_BUDGET,
6730
+ nowMs: options?.nowMs ?? Date.now(),
6731
+ maxSummaryChars: options?.maxSummaryChars ?? DEFAULT_MAX_SUMMARY_CHARS
6732
+ };
6733
+ }
6734
+ function classifyCertainty(confidence) {
6735
+ if (confidence >= 0.95)
6736
+ return "absolute";
6737
+ if (confidence >= 0.7)
6738
+ return "confident";
6739
+ return "tentative";
6740
+ }
6741
+ function scoreForIndex(node, edgeCount, decayedConfidence2) {
6742
+ const pinBonus = node.pinned ? 0.5 : 0;
6743
+ const connectivityBonus = Math.log1p(edgeCount) * 0.15;
6744
+ return decayedConfidence2 + pinBonus + connectivityBonus;
6745
+ }
6746
+ function rankIndexEntries(nodes, edges, options) {
6747
+ const o5 = resolveOptions(options);
6748
+ const liveNodes = nodes.filter((n2) => !n2.tombstoned && isValidAt(n2, o5.nowMs));
6749
+ const edgeCounts = /* @__PURE__ */ new Map();
6750
+ for (const edge of edges) {
6751
+ edgeCounts.set(edge.source_id, (edgeCounts.get(edge.source_id) ?? 0) + 1);
6752
+ edgeCounts.set(edge.target_id, (edgeCounts.get(edge.target_id) ?? 0) + 1);
6753
+ }
6754
+ const entries = [];
6755
+ for (const node of liveNodes) {
6756
+ const edgeCount = edgeCounts.get(node.node_id) ?? 0;
6757
+ const decayed = computeDecayedConfidence(node.confidence, node.half_life, o5.nowMs - node.created_at);
6758
+ const score = scoreForIndex(node, edgeCount, decayed);
6759
+ entries.push({
6760
+ node,
6761
+ certainty: classifyCertainty(decayed),
6762
+ score,
6763
+ edgeCount,
6764
+ decayedConfidence: decayed
6765
+ });
6766
+ }
6767
+ entries.sort((a3, b3) => {
6768
+ if (b3.score !== a3.score)
6769
+ return b3.score - a3.score;
6770
+ if (b3.node.created_at !== a3.node.created_at)
6771
+ return b3.node.created_at - a3.node.created_at;
6772
+ return a3.node.node_id < b3.node.node_id ? -1 : 1;
6773
+ });
6774
+ return entries;
6775
+ }
6776
+ function renderLine(entry, maxSummaryChars) {
6777
+ const shortId = entry.node.node_id.slice(0, 8);
6778
+ const summary = entry.node.content.replace(/\s+/g, " ").trim().slice(0, maxSummaryChars);
6779
+ const suffix = entry.node.pinned ? " [pinned]" : "";
6780
+ const marker = entry.node.source !== void 0 ? MEMORY_SOURCE_MARKERS[entry.node.source] : MEMORY_SOURCE_MARKER_UNKNOWN;
6781
+ return `- [${shortId}] ${summary} (${entry.certainty}, from:${marker})${suffix}`;
6782
+ }
6783
+ function buildMemoryIndex(nodes, edges, options) {
6784
+ const o5 = resolveOptions(options);
6785
+ const entries = rankIndexEntries(nodes, edges, options);
6786
+ if (entries.length === 0)
6787
+ return "";
6788
+ const header = [
6789
+ "# Memory Index (Layer 1)",
6790
+ "Entries ranked by index-worthiness. Certainty: absolute | confident | tentative. Provenance: from:user is a direct user statement; every other from:* label (tool, peer-agent, inference, consolidation, unknown) is an absorbed, unverified claim. Pull full detail via recall; correct a stale entry via the `rewrite_memory` tool (node_id is the `[xxxxxxxx]` short id).",
6791
+ ""
6792
+ ];
6793
+ const lines = [...header];
6794
+ let bytesUsed = new Blob([lines.join("\n")]).size;
6795
+ for (const entry of entries) {
6796
+ const line = renderLine(entry, o5.maxSummaryChars);
6797
+ const lineBytes = new Blob([line + "\n"]).size;
6798
+ if (bytesUsed + lineBytes > o5.maxBytes)
6799
+ break;
6800
+ lines.push(line);
6801
+ bytesUsed += lineBytes;
6802
+ }
6803
+ return lines.join("\n");
6804
+ }
6805
+ var DEFAULT_INDEX_BYTE_BUDGET, DEFAULT_MAX_SUMMARY_CHARS;
6806
+ var init_memory_index = __esm({
6807
+ "../../packages/memory-graph/dist/memory-index.js"() {
6808
+ "use strict";
6809
+ init_esm_shims();
6810
+ init_dist2();
6811
+ init_dist3();
6812
+ init_retrieval();
6813
+ DEFAULT_INDEX_BYTE_BUDGET = 2048;
6814
+ DEFAULT_MAX_SUMMARY_CHARS = 120;
6815
+ }
6816
+ });
6817
+
6818
+ // ../../packages/memory-graph/dist/embeddings.js
6819
+ async function remoteEmbed(text) {
6820
+ const res = await fetch(remoteEmbedUrl, {
6821
+ method: "POST",
6822
+ headers: { "Content-Type": "application/json" },
6823
+ body: JSON.stringify({ texts: [text] }),
6824
+ signal: AbortSignal.timeout(1e4)
6825
+ });
6826
+ const data = await res.json();
6827
+ if (!data.ok || !data.embeddings?.[0]) {
6828
+ throw new Error(data.error ?? "Remote embedding failed");
6829
+ }
6830
+ return data.embeddings[0];
6831
+ }
6832
+ async function getPipeline() {
6833
+ if (pipelineInstance !== null)
6834
+ return pipelineInstance;
6835
+ if (pipelineFailed)
6836
+ throw new Error("Pipeline previously failed to load");
6837
+ try {
6838
+ const { pipeline } = await import("@xenova/transformers");
6839
+ pipelineInstance = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2");
6840
+ return pipelineInstance;
6841
+ } catch (e2) {
6842
+ pipelineFailed = true;
6843
+ throw e2;
6844
+ }
6845
+ }
6846
+ async function embedText(text) {
6847
+ if (text === "") {
6848
+ return new Array(EMBEDDING_DIMENSIONS).fill(0);
6849
+ }
6850
+ if (remoteEmbedUrl) {
6851
+ try {
6852
+ return await remoteEmbed(text);
6853
+ } catch {
6854
+ }
6855
+ }
6856
+ try {
6857
+ const extractor = await getPipeline();
6858
+ const output = await extractor(text, { pooling: "mean", normalize: true });
6859
+ return Array.from(output.data);
6860
+ } catch {
6861
+ const hash2 = embedTextHash(text);
6862
+ const padded = new Array(EMBEDDING_DIMENSIONS).fill(0);
6863
+ for (let i3 = 0; i3 < hash2.length; i3++) {
6864
+ padded[i3] = hash2[i3];
6865
+ }
6866
+ return padded;
6867
+ }
6868
+ }
6869
+ function tokenize(text) {
6870
+ return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((t3) => t3.length > 0);
6871
+ }
6872
+ function hashToken(token) {
6873
+ let h5 = 0;
6874
+ for (let i3 = 0; i3 < token.length; i3++) {
6875
+ h5 = h5 * 31 + token.charCodeAt(i3) | 0;
6876
+ }
6877
+ return (h5 % HASH_DIMENSIONS + HASH_DIMENSIONS) % HASH_DIMENSIONS;
6878
+ }
6879
+ function charTrigrams(token) {
6880
+ const grams = [];
6881
+ if (token.length < 3) {
6882
+ grams.push(token);
6883
+ } else {
6884
+ for (let i3 = 0; i3 <= token.length - 3; i3++) {
6885
+ grams.push(token.slice(i3, i3 + 3));
6886
+ }
6887
+ }
6888
+ return grams;
6889
+ }
6890
+ function embedTextHash(text) {
6891
+ const vec = new Array(HASH_DIMENSIONS).fill(0);
6892
+ const tokens = tokenize(text);
6893
+ for (const token of tokens) {
6894
+ const bucket = hashToken(token);
6895
+ vec[bucket] = (vec[bucket] ?? 0) + 1;
6896
+ }
6897
+ for (const token of tokens) {
6898
+ const grams = charTrigrams(token);
6899
+ for (const gram of grams) {
6900
+ const bucket = hashToken("#" + gram);
6901
+ vec[bucket] = (vec[bucket] ?? 0) + 0.5;
6902
+ }
6903
+ }
6904
+ let norm = 0;
6905
+ for (let i3 = 0; i3 < HASH_DIMENSIONS; i3++) {
6906
+ norm += vec[i3] * vec[i3];
6907
+ }
6908
+ norm = Math.sqrt(norm);
6909
+ if (norm > 0) {
6910
+ for (let i3 = 0; i3 < HASH_DIMENSIONS; i3++) {
6911
+ vec[i3] = vec[i3] / norm;
6912
+ }
6913
+ }
6914
+ return vec;
6915
+ }
6916
+ var EMBEDDING_DIMENSIONS, remoteEmbedUrl, pipelineInstance, pipelineFailed, HASH_DIMENSIONS;
6917
+ var init_embeddings = __esm({
6918
+ "../../packages/memory-graph/dist/embeddings.js"() {
6919
+ "use strict";
6920
+ init_esm_shims();
6921
+ EMBEDDING_DIMENSIONS = 384;
6922
+ remoteEmbedUrl = null;
6923
+ pipelineInstance = null;
6924
+ pipelineFailed = false;
6925
+ HASH_DIMENSIONS = 128;
6926
+ }
6927
+ });
6928
+
6914
6929
  // ../../packages/memory-graph/dist/accrual.js
6915
6930
  function recalledMemoryBasis(queryEmbedding, nodes, opts = {}) {
6916
6931
  if (queryEmbedding.length === 0)
@@ -6973,7 +6988,7 @@ function scoreNode(node, edgeCount, hasConflictPartner, decayedConfidence2, opti
6973
6988
  }
6974
6989
  function rankNotableMemories(nodes, edges, options) {
6975
6990
  const o5 = resolve(options);
6976
- const live = nodes.filter((n2) => !n2.tombstoned);
6991
+ const live = nodes.filter((n2) => !n2.tombstoned && (n2.valid_until == null || n2.valid_until > o5.nowMs));
6977
6992
  const liveIds = new Set(live.map((n2) => n2.node_id));
6978
6993
  const nodeMap = new Map(live.map((n2) => [n2.node_id, n2]));
6979
6994
  const edgeCounts = /* @__PURE__ */ new Map();
@@ -7138,6 +7153,8 @@ function findCuriosityTargets(nodes, options) {
7138
7153
  for (const node of nodes) {
7139
7154
  if (node.tombstoned || node.pinned)
7140
7155
  continue;
7156
+ if (node.valid_until != null && node.valid_until <= now)
7157
+ continue;
7141
7158
  if (node.confidence < minOriginalConfidence)
7142
7159
  continue;
7143
7160
  const elapsed = now - node.created_at;
@@ -7945,14 +7962,24 @@ var init_dist3 = __esm({
7945
7962
  * consolidation LLM classifier because the agent has already
7946
7963
  * decided the rewrite is correct. Preserves the original
7947
7964
  * `memory_formed` event (append-only; §3.1) — the old node is
7948
- * tombstoned + marked `valid_until` now, a fresh node carries the
7949
- * new content, a Supersedes edge links them, and a
7950
- * `memory_consolidated` event with `action: "supersede"` is
7951
- * emitted for the sync layer.
7952
- *
7953
- * Returns the new node id. Throws when `oldNodeId` is unknown or
7954
- * already tombstoned the tool handler turns that into a
7955
- * user-surface error.
7965
+ * INVALIDATED (`valid_until` set to now) but kept LIVE, a fresh node
7966
+ * carries the new content, a Supersedes edge links them, and a
7967
+ * `memory_consolidated` event with `action: "supersede"` is emitted
7968
+ * for the sync layer.
7969
+ *
7970
+ * Invalidation-with-provenance, never destruction: the superseded
7971
+ * node is NOT tombstoned, so as-of-`T` recall can still reconstruct
7972
+ * what was believed inside `[valid_from, valid_until)` (doctrine
7973
+ * `memory-architecture.md` invariant #2 — "history is preserved").
7974
+ * This makes the one supersede mechanism identical to the
7975
+ * consolidation `UPDATE` path, and matches what syncing peers apply
7976
+ * (they close the interval via `superseded_valid_until`, they do not
7977
+ * tombstone) — so a tool-superseded node no longer ends up tombstoned
7978
+ * locally yet live on every peer.
7979
+ *
7980
+ * Returns the new node id. Throws when `oldNodeId` is unknown, already
7981
+ * superseded (`valid_until` set), or tombstoned (deleted) — the tool
7982
+ * handler turns that into a user-surface error.
7956
7983
  */
7957
7984
  async supersedeMemoryByNodeId(oldNodeId, newContent, reason) {
7958
7985
  const oldNode = await this.storage.getNode(oldNodeId);
@@ -7960,6 +7987,8 @@ var init_dist3 = __esm({
7960
7987
  throw new Error(`No memory node with id ${oldNodeId}`);
7961
7988
  if (oldNode.tombstoned)
7962
7989
  throw new Error(`Memory ${oldNodeId} is already tombstoned`);
7990
+ if (oldNode.valid_until != null)
7991
+ throw new Error(`Memory ${oldNodeId} is already superseded`);
7963
7992
  const embedding = await this.embed(newContent);
7964
7993
  const now = Date.now();
7965
7994
  const newNode = await this.formMemory({
@@ -7975,7 +8004,6 @@ var init_dist3 = __esm({
7975
8004
  source_turn_id: oldNode.source_turn_id
7976
8005
  }, embedding, oldNode.half_life, now);
7977
8006
  oldNode.valid_until = now;
7978
- oldNode.tombstoned = true;
7979
8007
  await this.storage.saveNode(oldNode);
7980
8008
  await this.link(newNode.node_id, oldNodeId, RelationType.Supersedes);
7981
8009
  try {
@@ -8373,7 +8401,7 @@ async function* runTurnStreaming(deps, userMessage, options) {
8373
8401
  let providerCallStart;
8374
8402
  let contextPipelineMs;
8375
8403
  let firstTokenAt;
8376
- const CONTEXT_SAFE_SENSITIVITY = [SensitivityLevel.None, SensitivityLevel.Personal];
8404
+ const CONTEXT_SAFE_SENSITIVITY2 = [...CONTEXT_SAFE_SENSITIVITY];
8377
8405
  const hasMemory = await withStageTimeout("memory_probe", STAGE_TIMEOUTS_MS.memory_probe, memoryGraph.hasAnyMemory());
8378
8406
  const [recentEvents, queryEmbedding, pinnedMemoriesRaw] = await Promise.all([
8379
8407
  withStageTimeout("event_query", STAGE_TIMEOUTS_MS.event_query, eventStore.query({ motebit_id: motebitId, limit: 10 }), (ms) => {
@@ -8386,11 +8414,11 @@ async function* runTurnStreaming(deps, userMessage, options) {
8386
8414
  pinnedMs = ms;
8387
8415
  }) : Promise.resolve([])
8388
8416
  ]);
8389
- const pinnedMemories = pinnedMemoriesRaw.filter((m3) => CONTEXT_SAFE_SENSITIVITY.includes(m3.sensitivity));
8417
+ const pinnedMemories = pinnedMemoriesRaw.filter((m3) => CONTEXT_SAFE_SENSITIVITY2.includes(m3.sensitivity));
8390
8418
  const similarityMemories = hasMemory ? await withStageTimeout("memory_retrieve", STAGE_TIMEOUTS_MS.memory_retrieve, memoryGraph.recallRelevant(queryEmbedding, {
8391
8419
  limit: 5,
8392
8420
  strengthenCoRetrieved: true,
8393
- sensitivityFilter: CONTEXT_SAFE_SENSITIVITY
8421
+ sensitivityFilter: CONTEXT_SAFE_SENSITIVITY2
8394
8422
  }), (ms) => {
8395
8423
  memoryRetrieveMs = ms;
8396
8424
  }) : [];
@@ -9032,6 +9060,7 @@ var init_loop = __esm({
9032
9060
  "use strict";
9033
9061
  init_esm_shims();
9034
9062
  init_dist2();
9063
+ init_dist2();
9035
9064
  init_dist3();
9036
9065
  init_infer_state();
9037
9066
  init_core();
@@ -9093,6 +9122,8 @@ __export(dist_exports2, {
9093
9122
  KEY_SUCCESSION_SUITE: () => KEY_SUCCESSION_SUITE,
9094
9123
  MOTEBIT_ANNOUNCEMENT_MAX_AGE_MS: () => MOTEBIT_ANNOUNCEMENT_MAX_AGE_MS,
9095
9124
  MOTEBIT_ANNOUNCEMENT_SUITE: () => MOTEBIT_ANNOUNCEMENT_SUITE,
9125
+ ROUTING_TRANSCRIPT_SPEC_MIRROR: () => ROUTING_TRANSCRIPT_SPEC_MIRROR,
9126
+ ROUTING_TRANSCRIPT_SUITE: () => ROUTING_TRANSCRIPT_SUITE,
9096
9127
  SETTLEMENT_RECORD_SUITE: () => SETTLEMENT_RECORD_SUITE,
9097
9128
  SIGNED_REQUEST_ENVELOPE_SUITE: () => SIGNED_REQUEST_ENVELOPE_SUITE,
9098
9129
  SIGNED_TOKEN_SUITE: () => SIGNED_TOKEN_SUITE,
@@ -9192,6 +9223,7 @@ __export(dist_exports2, {
9192
9223
  signMigrationRequest: () => signMigrationRequest,
9193
9224
  signMotebitAnnouncement: () => signMotebitAnnouncement,
9194
9225
  signRequestEnvelope: () => signRequestEnvelope,
9226
+ signRoutingTranscript: () => signRoutingTranscript,
9195
9227
  signSettlement: () => signSettlement,
9196
9228
  signSkillEnvelope: () => signSkillEnvelope,
9197
9229
  signSkillManifest: () => signSkillManifest,
@@ -9259,6 +9291,7 @@ __export(dist_exports2, {
9259
9291
  verifyRequestEnvelope: () => verifyRequestEnvelope,
9260
9292
  verifyRetentionManifest: () => verifyRetentionManifest,
9261
9293
  verifyRevocationAnchor: () => verifyRevocationAnchor,
9294
+ verifyRoutingTranscript: () => verifyRoutingTranscript,
9262
9295
  verifySettlement: () => verifySettlement,
9263
9296
  verifySignedToken: () => verifySignedToken,
9264
9297
  verifySkillBundle: () => verifySkillBundle,
@@ -10457,8 +10490,8 @@ function createFROST(opts) {
10457
10490
  const Signature = {
10458
10491
  // RFC 9591 Appendix A encodes signatures canonically as
10459
10492
  // SerializeElement(R) || SerializeScalar(z).
10460
- encode: (R3, z43) => {
10461
- let res = concatBytes3(serializePoint(R3), Fn.toBytes(z43));
10493
+ encode: (R3, z44) => {
10494
+ let res = concatBytes3(serializePoint(R3), Fn.toBytes(z44));
10462
10495
  if (opts.adjustTx)
10463
10496
  res = opts.adjustTx.encode(res);
10464
10497
  return res;
@@ -10467,8 +10500,8 @@ function createFROST(opts) {
10467
10500
  if (opts.adjustTx)
10468
10501
  sig = opts.adjustTx.decode(sig);
10469
10502
  const R3 = parsePoint(sig.subarray(0, -Fn.BYTES));
10470
- const z43 = Fn.fromBytes(sig.subarray(-Fn.BYTES));
10471
- return { R: R3, z: z43 };
10503
+ const z44 = Fn.fromBytes(sig.subarray(-Fn.BYTES));
10504
+ return { R: R3, z: z44 };
10472
10505
  }
10473
10506
  };
10474
10507
  const genPointScalarPair = (rng = randomBytes3) => {
@@ -10554,10 +10587,10 @@ function createFROST(opts) {
10554
10587
  validate(id, commitment, proof) {
10555
10588
  if (commitment.length < 1)
10556
10589
  throw new Error("commitment should have at least one element");
10557
- const { R: R3, z: z43 } = Signature.decode(proof);
10590
+ const { R: R3, z: z44 } = Signature.decode(proof);
10558
10591
  const phi = parsePoint(commitment[0]);
10559
10592
  const c3 = this.challenge(id, phi, R3);
10560
- if (!R3.equals(Point2.BASE.multiply(z43).subtract(phi.multiply(c3))))
10593
+ if (!R3.equals(Point2.BASE.multiply(z44).subtract(phi.multiply(c3))))
10561
10594
  throw new Error("invalid proof of knowledge");
10562
10595
  }
10563
10596
  };
@@ -10571,16 +10604,16 @@ function createFROST(opts) {
10571
10604
  const { point: R3, scalar: r2 } = genPointScalarPair(rng);
10572
10605
  const PK = Point2.BASE.multiply(sk);
10573
10606
  const c3 = this.challenge(R3, PK, msg);
10574
- const z43 = Fn.add(r2, Fn.mul(c3, sk));
10575
- return [R3, z43];
10607
+ const z44 = Fn.add(r2, Fn.mul(c3, sk));
10608
+ return [R3, z44];
10576
10609
  },
10577
- verify(msg, R3, z43, PK) {
10610
+ verify(msg, R3, z44, PK) {
10578
10611
  if (opts.adjustPoint)
10579
10612
  PK = opts.adjustPoint(PK);
10580
10613
  if (opts.adjustPoint)
10581
10614
  R3 = opts.adjustPoint(R3);
10582
10615
  const c3 = this.challenge(R3, PK, msg);
10583
- const zB = Point2.BASE.multiply(z43);
10616
+ const zB = Point2.BASE.multiply(z44);
10584
10617
  const cA = PK.multiply(c3);
10585
10618
  let check = zB.subtract(cA).subtract(R3);
10586
10619
  if (check.clearCofactor)
@@ -10917,10 +10950,10 @@ function createFROST(opts) {
10917
10950
  }
10918
10951
  const GPK = parsePoint(pub.commitments[0]);
10919
10952
  const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg);
10920
- let z43 = Fn.ZERO;
10953
+ let z44 = Fn.ZERO;
10921
10954
  for (const id of ids)
10922
- z43 = Fn.add(z43, Fn.fromBytes(sigShares[id]));
10923
- if (!Basic.verify(msg, groupCommitment, z43, GPK)) {
10955
+ z44 = Fn.add(z44, Fn.fromBytes(sigShares[id]));
10956
+ if (!Basic.verify(msg, groupCommitment, z44, GPK)) {
10924
10957
  const cheaters = [];
10925
10958
  for (const id of ids) {
10926
10959
  if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id]))
@@ -10928,20 +10961,20 @@ function createFROST(opts) {
10928
10961
  }
10929
10962
  throw new AggErr("aggregation failed", cheaters);
10930
10963
  }
10931
- return Signature.encode(groupCommitment, z43);
10964
+ return Signature.encode(groupCommitment, z44);
10932
10965
  },
10933
10966
  // Basic sign/verify using single key
10934
10967
  sign(msg, secretKey) {
10935
10968
  let sk = Fn.fromBytes(secretKey);
10936
10969
  if (opts.adjustScalar)
10937
10970
  sk = opts.adjustScalar(sk);
10938
- const [R3, z43] = Basic.sign(msg, sk);
10939
- return Signature.encode(R3, z43);
10971
+ const [R3, z44] = Basic.sign(msg, sk);
10972
+ return Signature.encode(R3, z44);
10940
10973
  },
10941
10974
  verify(sig, msg, publicKey) {
10942
10975
  const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey);
10943
- const { R: R3, z: z43 } = Signature.decode(sig);
10944
- return Basic.verify(msg, R3, z43, PK);
10976
+ const { R: R3, z: z44 } = Signature.decode(sig);
10977
+ return Basic.verify(msg, R3, z44, PK);
10945
10978
  },
10946
10979
  // Combine multiple secret shares to restore secret
10947
10980
  combineSecret(shares, signers) {
@@ -14384,6 +14417,60 @@ async function verifyEvalAttestation(attestation) {
14384
14417
  }
14385
14418
  return { valid: true };
14386
14419
  }
14420
+ function canonicalizeForSigning3(unsigned) {
14421
+ return new TextEncoder().encode(canonicalJson(unsigned));
14422
+ }
14423
+ async function signRoutingTranscript(body, delegatorPrivateKey) {
14424
+ const unsigned = {
14425
+ ...body,
14426
+ suite: ROUTING_TRANSCRIPT_SUITE
14427
+ };
14428
+ const message2 = canonicalizeForSigning3(unsigned);
14429
+ const sig = await signBySuite(ROUTING_TRANSCRIPT_SUITE, message2, delegatorPrivateKey);
14430
+ return { ...unsigned, signature: toBase64Url(sig) };
14431
+ }
14432
+ async function verifyRoutingTranscript(transcript) {
14433
+ if (transcript.suite !== ROUTING_TRANSCRIPT_SUITE) {
14434
+ return { valid: false, reason: "unsupported_suite" };
14435
+ }
14436
+ if (transcript.spec !== ROUTING_TRANSCRIPT_SPEC_MIRROR) {
14437
+ return { valid: false, reason: "unsupported_spec" };
14438
+ }
14439
+ const candidates = Array.isArray(
14440
+ transcript.candidates
14441
+ ) ? transcript.candidates : [];
14442
+ if (candidates.length === 0) {
14443
+ return { valid: false, reason: "empty_candidates" };
14444
+ }
14445
+ if (!candidates.some((c3) => c3.motebit_id === transcript.winner_motebit_id)) {
14446
+ return { valid: false, reason: "winner_not_in_candidates" };
14447
+ }
14448
+ if (!/^[0-9a-f]{64}$/i.test(transcript.delegator_public_key)) {
14449
+ return { valid: false, reason: "malformed_public_key" };
14450
+ }
14451
+ const publicKey = hexToBytes5(transcript.delegator_public_key);
14452
+ let sigBytes;
14453
+ try {
14454
+ sigBytes = fromBase64Url(transcript.signature);
14455
+ } catch {
14456
+ return { valid: false, reason: "malformed_signature" };
14457
+ }
14458
+ if (sigBytes.length !== 64) {
14459
+ return { valid: false, reason: "malformed_signature" };
14460
+ }
14461
+ const { signature: _sig, ...unsigned } = transcript;
14462
+ const message2 = canonicalizeForSigning3(unsigned);
14463
+ let valid;
14464
+ try {
14465
+ valid = await verifyBySuite(transcript.suite, message2, sigBytes, publicKey);
14466
+ } catch {
14467
+ return { valid: false, reason: "signature_invalid" };
14468
+ }
14469
+ if (!valid) {
14470
+ return { valid: false, reason: "signature_invalid" };
14471
+ }
14472
+ return { valid: true };
14473
+ }
14387
14474
  async function computeCredentialLeaf(credential, treeHashVersion = "merkle-sha256-plain-v1") {
14388
14475
  return canonicalLeaf(credential, treeHashVersion);
14389
14476
  }
@@ -16488,7 +16575,7 @@ async function verify(artifact, options) {
16488
16575
  return verifySkillEnvelopeArtifact(resolved);
16489
16576
  }
16490
16577
  }
16491
- var __defProp2, __getOwnPropNames2, __esm2, __export2, hasHexBuiltin, hexes, asciis, oidNist, init_utils, HashMD, SHA256_IV, SHA384_IV, SHA512_IV, init_md, U32_MASK64, _32n, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, add3L, add3H, add4L, add4H, add5L, add5H, init_u64, SHA256_K, SHA256_W, SHA2_32B, _SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA2_64B, _SHA512, _SHA384, sha256, sha512, sha384, init_sha2, abytes3, anumber2, bytesToHex3, concatBytes3, hexToBytes3, isBytes3, randomBytes3, _0n, _1n, isPosBig, bitMask, init_utils2, _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, FIELD_FIELDS, FIELD_SQRT, _Field, init_modular, _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF2, init_curve, init_fft, os2ip, _DST_scalar, init_hash_to_curve, validateSigners, validateCommitmentsNum, AggErr, init_frost, _DST_scalarBytes, init_oprf, _HMAC, hmac, init_hmac, divNearest, DERErr, DER, _0n4, _1n4, _2n2, _3n2, _4n2, init_weierstrass, nist_exports, p256_CURVE, p384_CURVE, p521_CURVE, p256_Point, p256, p256_hasher, p256_oprf, p256_FROST, p384_Point, p384, p384_hasher, p384_oprf, p521_Point, p521, p521_hasher, p521_oprf, init_nist, ed25519_CURVE, P, N, Gx, Gy, _a, _d, h, L, captureTrace, err, isBig, isStr, isBytes, abytes, u8n, u8fr, padh, bytesToHex, C, _ch, hexToBytes, cr, subtle, concatBytes, randomBytes, big, assertRange, M, P_MASK, modP, modN, invert, callHash, checkDigest, apoint, B256, Point, G, I, numTo32bLE, bytesToNumberLE, pow2, pow_2_252_3, RM1, uvRatio, modL_LE, sha512a, hash2extK, getExtendedPublicKeyAsync, getPublicKeyAsync, hashFinishA, _sign, signAsync, defaultVerifyOpts, _verify, verifyAsync, hashes, randomSecretKey, keygenAsync, W, scalarBits, pwindows, pwindowSize, precompute, Gpows, ctneg, wNAF, SIGNED_TOKEN_SUITE, BASE58_ALPHABET, NODE_TAG_V2, LEAF_TAG_V2, EXECUTION_RECEIPT_SUITE, TOOL_INVOCATION_RECEIPT_SUITE, COMPUTER_SESSION_RECEIPT_SUITE, DELEGATION_TOKEN_SUITE, NANOS_PER_MINOR, SIGNED_REQUEST_ENVELOPE_SUITE, ADJUDICATOR_VOTE_SUITE, DISPUTE_RESOLUTION_SUITE, DISPUTE_REQUEST_SUITE, DISPUTE_EVIDENCE_SUITE, DISPUTE_APPEAL_SUITE, APPROVAL_DECISION_SUITE, BOND_COMMITMENT_SUITE, CONSOLIDATION_RECEIPT_SUITE, CONSOLIDATION_MUTATION_MANIFEST_SUITE, BALANCE_WAIVER_SUITE, SETTLEMENT_RECORD_SUITE, FEDERATION_SETTLEMENT_RECORD_SUITE, KEY_SUCCESSION_SUITE, GUARDIAN_REVOCATION_SUITE, COLLABORATIVE_RECEIPT_SUITE, DEVICE_REGISTRATION_SUITE, DEVICE_REGISTRATION_MAX_AGE_MS, MOTEBIT_ANNOUNCEMENT_SUITE, MOTEBIT_ANNOUNCEMENT_MAX_AGE_MS, ANNOUNCEMENT_SURFACES, SKILL_SIGNATURE_SUITE, VC_TYPE_GRADIENT2, VC_TYPE_REPUTATION2, VC_TYPE_TRUST2, ONE_HOUR_MS, CONTENT_ARTIFACT_SUITE, EVAL_ATTESTATION_SUITE, EVAL_KINDS_MIRROR, CREDENTIAL_ANCHOR_SUITE, REVOCATION_ANCHOR_SUITE, AGENT_SETTLEMENT_ANCHOR_SUITE, FEDERATION_SETTLEMENT_ANCHOR_SUITE, DELETION_CERTIFICATE_SUITE, WITNESS_OMISSION_DISPUTE_WINDOW_MS, EMPTY_FEDERATION_GRAPH_ANCHOR_ROOT, REASON_TABLE, WITNESS_OMISSION_DISPUTE_SUITE, FEDERATION_HEARTBEAT_SUITE, HEARTBEAT_FRESHNESS_WINDOW_MS, BASE58_ALPHABET2, IDENTITY_FILE_SUITE, SIG_PREFIX, SIG_SUFFIX, DEFAULT_CLOCK_SKEW_SECONDS;
16578
+ var __defProp2, __getOwnPropNames2, __esm2, __export2, hasHexBuiltin, hexes, asciis, oidNist, init_utils, HashMD, SHA256_IV, SHA384_IV, SHA512_IV, init_md, U32_MASK64, _32n, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, add3L, add3H, add4L, add4H, add5L, add5H, init_u64, SHA256_K, SHA256_W, SHA2_32B, _SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA2_64B, _SHA512, _SHA384, sha256, sha512, sha384, init_sha2, abytes3, anumber2, bytesToHex3, concatBytes3, hexToBytes3, isBytes3, randomBytes3, _0n, _1n, isPosBig, bitMask, init_utils2, _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, FIELD_FIELDS, FIELD_SQRT, _Field, init_modular, _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF2, init_curve, init_fft, os2ip, _DST_scalar, init_hash_to_curve, validateSigners, validateCommitmentsNum, AggErr, init_frost, _DST_scalarBytes, init_oprf, _HMAC, hmac, init_hmac, divNearest, DERErr, DER, _0n4, _1n4, _2n2, _3n2, _4n2, init_weierstrass, nist_exports, p256_CURVE, p384_CURVE, p521_CURVE, p256_Point, p256, p256_hasher, p256_oprf, p256_FROST, p384_Point, p384, p384_hasher, p384_oprf, p521_Point, p521, p521_hasher, p521_oprf, init_nist, ed25519_CURVE, P, N, Gx, Gy, _a, _d, h, L, captureTrace, err, isBig, isStr, isBytes, abytes, u8n, u8fr, padh, bytesToHex, C, _ch, hexToBytes, cr, subtle, concatBytes, randomBytes, big, assertRange, M, P_MASK, modP, modN, invert, callHash, checkDigest, apoint, B256, Point, G, I, numTo32bLE, bytesToNumberLE, pow2, pow_2_252_3, RM1, uvRatio, modL_LE, sha512a, hash2extK, getExtendedPublicKeyAsync, getPublicKeyAsync, hashFinishA, _sign, signAsync, defaultVerifyOpts, _verify, verifyAsync, hashes, randomSecretKey, keygenAsync, W, scalarBits, pwindows, pwindowSize, precompute, Gpows, ctneg, wNAF, SIGNED_TOKEN_SUITE, BASE58_ALPHABET, NODE_TAG_V2, LEAF_TAG_V2, EXECUTION_RECEIPT_SUITE, TOOL_INVOCATION_RECEIPT_SUITE, COMPUTER_SESSION_RECEIPT_SUITE, DELEGATION_TOKEN_SUITE, NANOS_PER_MINOR, SIGNED_REQUEST_ENVELOPE_SUITE, ADJUDICATOR_VOTE_SUITE, DISPUTE_RESOLUTION_SUITE, DISPUTE_REQUEST_SUITE, DISPUTE_EVIDENCE_SUITE, DISPUTE_APPEAL_SUITE, APPROVAL_DECISION_SUITE, BOND_COMMITMENT_SUITE, CONSOLIDATION_RECEIPT_SUITE, CONSOLIDATION_MUTATION_MANIFEST_SUITE, BALANCE_WAIVER_SUITE, SETTLEMENT_RECORD_SUITE, FEDERATION_SETTLEMENT_RECORD_SUITE, KEY_SUCCESSION_SUITE, GUARDIAN_REVOCATION_SUITE, COLLABORATIVE_RECEIPT_SUITE, DEVICE_REGISTRATION_SUITE, DEVICE_REGISTRATION_MAX_AGE_MS, MOTEBIT_ANNOUNCEMENT_SUITE, MOTEBIT_ANNOUNCEMENT_MAX_AGE_MS, ANNOUNCEMENT_SURFACES, SKILL_SIGNATURE_SUITE, VC_TYPE_GRADIENT2, VC_TYPE_REPUTATION2, VC_TYPE_TRUST2, ONE_HOUR_MS, CONTENT_ARTIFACT_SUITE, EVAL_ATTESTATION_SUITE, EVAL_KINDS_MIRROR, ROUTING_TRANSCRIPT_SUITE, ROUTING_TRANSCRIPT_SPEC_MIRROR, CREDENTIAL_ANCHOR_SUITE, REVOCATION_ANCHOR_SUITE, AGENT_SETTLEMENT_ANCHOR_SUITE, FEDERATION_SETTLEMENT_ANCHOR_SUITE, DELETION_CERTIFICATE_SUITE, WITNESS_OMISSION_DISPUTE_WINDOW_MS, EMPTY_FEDERATION_GRAPH_ANCHOR_ROOT, REASON_TABLE, WITNESS_OMISSION_DISPUTE_SUITE, FEDERATION_HEARTBEAT_SUITE, HEARTBEAT_FRESHNESS_WINDOW_MS, BASE58_ALPHABET2, IDENTITY_FILE_SUITE, SIG_PREFIX, SIG_SUFFIX, DEFAULT_CLOCK_SKEW_SECONDS;
16492
16579
  var init_dist5 = __esm({
16493
16580
  "../../packages/crypto/dist/index.js"() {
16494
16581
  "use strict";
@@ -18364,6 +18451,8 @@ var init_dist5 = __esm({
18364
18451
  CONTENT_ARTIFACT_SUITE = "motebit-jcs-ed25519-hex-v1";
18365
18452
  EVAL_ATTESTATION_SUITE = "motebit-jcs-ed25519-b64-v1";
18366
18453
  EVAL_KINDS_MIRROR = Object.freeze(["verification_audit"]);
18454
+ ROUTING_TRANSCRIPT_SUITE = "motebit-jcs-ed25519-b64-v1";
18455
+ ROUTING_TRANSCRIPT_SPEC_MIRROR = "motebit/routing-transcript@1.0";
18367
18456
  CREDENTIAL_ANCHOR_SUITE = "motebit-jcs-ed25519-hex-v1";
18368
18457
  REVOCATION_ANCHOR_SUITE = "motebit-concat-ed25519-hex-v1";
18369
18458
  AGENT_SETTLEMENT_ANCHOR_SUITE = "motebit-jcs-ed25519-hex-v1";
@@ -20988,7 +21077,7 @@ var init_config2 = __esm({
20988
21077
  "src/config.ts"() {
20989
21078
  "use strict";
20990
21079
  init_esm_shims();
20991
- VERSION = true ? "1.8.3" : "0.0.0-dev";
21080
+ VERSION = true ? "1.9.0" : "0.0.0-dev";
20992
21081
  CONFIG_DIR = process.env["MOTEBIT_CONFIG_DIR"] ?? path2.join(os.homedir(), ".motebit");
20993
21082
  CONFIG_PATH = path2.join(CONFIG_DIR, "config.json");
20994
21083
  RELAY_DIR = path2.join(CONFIG_DIR, "relay");
@@ -27367,6 +27456,9 @@ function cappedCounts(successful, failed) {
27367
27456
  return { s: s3, f: COUNT_CAP - s3 };
27368
27457
  }
27369
27458
  function exploratoryQuality(c3, explore, capability) {
27459
+ return exploratoryQualityDetail(c3, explore, capability).quality;
27460
+ }
27461
+ function exploratoryQualityDetail(c3, explore, capability) {
27370
27462
  const prior = levelPrior(c3.trustRecord?.trust_level);
27371
27463
  const counts = competenceCounts(c3.trustRecord, capability);
27372
27464
  const { s: s3, f: f6 } = cappedCounts(counts.successful, counts.failed);
@@ -27376,9 +27468,9 @@ function exploratoryQuality(c3, explore, capability) {
27376
27468
  const base = clampStrength(explore.strength ?? 1);
27377
27469
  const strength = c3.bonded ? Math.min(1, base * BOND_EXPLORE_BOOST) : base;
27378
27470
  if (strength <= 0)
27379
- return mean;
27471
+ return { quality: mean, alpha, beta };
27380
27472
  const draw = thompsonDraw(alpha, beta, `${explore.seed}|${c3.motebit_id}`);
27381
- return mean + strength * (draw - mean);
27473
+ return { quality: mean + strength * (draw - mean), alpha, beta, theta: draw };
27382
27474
  }
27383
27475
  function reliabilityOf(record, capability) {
27384
27476
  if (!record)
@@ -27414,10 +27506,65 @@ function rankWorkers(selfId, candidates, opts) {
27414
27506
  });
27415
27507
  return ranked.map((r2) => ({ motebit_id: r2.motebit_id, score: r2.score, route: r2.route })).sort((a3, b3) => b3.score - a3.score || (a3.motebit_id < b3.motebit_id ? -1 : 1));
27416
27508
  }
27417
- function selectWorker(selfId, candidates, opts) {
27418
- return rankWorkers(selfId, candidates, opts)[0] ?? null;
27509
+ function rankWorkersWithBasis(selfId, candidates, opts) {
27510
+ const weights = opts?.weights ?? DEFAULT_WEIGHTS;
27511
+ const capability = opts?.capability;
27512
+ const explore = opts?.explore != null && clampStrength(opts.explore.strength ?? 1) > 0 ? opts.explore : void 0;
27513
+ const ranking = rankWorkers(selfId, candidates, opts);
27514
+ const winner = ranking[0] ?? null;
27515
+ if (winner == null)
27516
+ return { winner: null, basis: null };
27517
+ const rankIndex = new Map(ranking.map((r2, i3) => [r2.motebit_id, i3]));
27518
+ const frozen = candidates.filter((c3) => c3.trustRecord?.trust_level !== AgentTrustLevel.Blocked).map((c3) => {
27519
+ const shared = {
27520
+ motebit_id: c3.motebit_id,
27521
+ ...c3.unitCost != null ? { unit_cost: c3.unitCost } : {},
27522
+ ...c3.bonded === true ? { bonded: true } : {}
27523
+ };
27524
+ if (explore) {
27525
+ const d4 = exploratoryQualityDetail(c3, explore, capability);
27526
+ return {
27527
+ ...shared,
27528
+ trust_axis: d4.quality,
27529
+ reliability_axis: d4.quality,
27530
+ alpha: d4.alpha,
27531
+ beta: d4.beta,
27532
+ ...d4.theta != null ? { theta: d4.theta } : {}
27533
+ };
27534
+ }
27535
+ return {
27536
+ ...shared,
27537
+ trust_axis: trustLevelToScore(c3.trustRecord?.trust_level ?? AgentTrustLevel.Unknown),
27538
+ reliability_axis: reliabilityOf(c3.trustRecord, capability)
27539
+ };
27540
+ }).sort((a3, b3) => (rankIndex.get(a3.motebit_id) ?? Number.MAX_SAFE_INTEGER) - (rankIndex.get(b3.motebit_id) ?? Number.MAX_SAFE_INTEGER));
27541
+ const exploitTop = explore ? rankWorkers(selfId, candidates, {
27542
+ ...opts?.weights != null ? { weights: opts.weights } : {},
27543
+ ...capability != null ? { capability } : {}
27544
+ })[0] ?? null : winner;
27545
+ return {
27546
+ winner,
27547
+ basis: {
27548
+ capability: capability ?? "",
27549
+ candidates: frozen,
27550
+ seed: opts?.explore?.seed ?? "",
27551
+ strength: explore ? clampStrength(explore.strength ?? 1) : 0,
27552
+ weights: {
27553
+ trust: weights.trust,
27554
+ reliability: weights.reliability,
27555
+ cost: weights.cost,
27556
+ latency: weights.latency
27557
+ },
27558
+ count_cap: COUNT_CAP,
27559
+ bond_explore_boost: BOND_EXPLORE_BOOST,
27560
+ default_latency_ms: DEFAULT_LATENCY_MS,
27561
+ algorithm_version: WORKER_SELECTION_ALGORITHM_VERSION,
27562
+ winner_motebit_id: winner.motebit_id,
27563
+ explored: explore != null && exploitTop != null && winner.motebit_id !== exploitTop.motebit_id
27564
+ }
27565
+ };
27419
27566
  }
27420
- var DEFAULT_LATENCY_MS, COUNT_CAP, BOND_EXPLORE_BOOST, DEFAULT_WEIGHTS;
27567
+ var DEFAULT_LATENCY_MS, COUNT_CAP, BOND_EXPLORE_BOOST, DEFAULT_WEIGHTS, WORKER_SELECTION_ALGORITHM_VERSION;
27421
27568
  var init_worker_selection = __esm({
27422
27569
  "../../packages/semiring/dist/worker-selection.js"() {
27423
27570
  "use strict";
@@ -27434,6 +27581,7 @@ var init_worker_selection = __esm({
27434
27581
  cost: 0.2,
27435
27582
  latency: 0
27436
27583
  };
27584
+ WORKER_SELECTION_ALGORITHM_VERSION = "motebit-worker-selection@1";
27437
27585
  }
27438
27586
  });
27439
27587
 
@@ -31628,11 +31776,11 @@ var init_three_core = __esm({
31628
31776
  * @param {number} [z=0] - The z value of this quaternion.
31629
31777
  * @param {number} [w=1] - The w value of this quaternion.
31630
31778
  */
31631
- constructor(x3 = 0, y5 = 0, z43 = 0, w2 = 1) {
31779
+ constructor(x3 = 0, y5 = 0, z44 = 0, w2 = 1) {
31632
31780
  this.isQuaternion = true;
31633
31781
  this._x = x3;
31634
31782
  this._y = y5;
31635
- this._z = z43;
31783
+ this._z = z44;
31636
31784
  this._w = w2;
31637
31785
  }
31638
31786
  /**
@@ -31776,10 +31924,10 @@ var init_three_core = __esm({
31776
31924
  * @param {number} w - The w value of this quaternion.
31777
31925
  * @return {Quaternion} A reference to this quaternion.
31778
31926
  */
31779
- set(x3, y5, z43, w2) {
31927
+ set(x3, y5, z44, w2) {
31780
31928
  this._x = x3;
31781
31929
  this._y = y5;
31782
- this._z = z43;
31930
+ this._z = z44;
31783
31931
  this._w = w2;
31784
31932
  this._onChangeCallback();
31785
31933
  return this;
@@ -31815,15 +31963,15 @@ var init_three_core = __esm({
31815
31963
  * @return {Quaternion} A reference to this quaternion.
31816
31964
  */
31817
31965
  setFromEuler(euler, update2 = true) {
31818
- const x3 = euler._x, y5 = euler._y, z43 = euler._z, order = euler._order;
31966
+ const x3 = euler._x, y5 = euler._y, z44 = euler._z, order = euler._order;
31819
31967
  const cos = Math.cos;
31820
31968
  const sin = Math.sin;
31821
31969
  const c1 = cos(x3 / 2);
31822
31970
  const c22 = cos(y5 / 2);
31823
- const c3 = cos(z43 / 2);
31971
+ const c3 = cos(z44 / 2);
31824
31972
  const s1 = sin(x3 / 2);
31825
31973
  const s22 = sin(y5 / 2);
31826
- const s3 = sin(z43 / 2);
31974
+ const s3 = sin(z44 / 2);
31827
31975
  switch (order) {
31828
31976
  case "XYZ":
31829
31977
  this._x = s1 * c22 * c3 + c1 * s22 * s3;
@@ -32101,12 +32249,12 @@ var init_three_core = __esm({
32101
32249
  * @return {Quaternion} A reference to this quaternion.
32102
32250
  */
32103
32251
  slerp(qb, t3) {
32104
- let x3 = qb._x, y5 = qb._y, z43 = qb._z, w2 = qb._w;
32252
+ let x3 = qb._x, y5 = qb._y, z44 = qb._z, w2 = qb._w;
32105
32253
  let dot = this.dot(qb);
32106
32254
  if (dot < 0) {
32107
32255
  x3 = -x3;
32108
32256
  y5 = -y5;
32109
- z43 = -z43;
32257
+ z44 = -z44;
32110
32258
  w2 = -w2;
32111
32259
  dot = -dot;
32112
32260
  }
@@ -32118,13 +32266,13 @@ var init_three_core = __esm({
32118
32266
  t3 = Math.sin(t3 * theta) / sin;
32119
32267
  this._x = this._x * s3 + x3 * t3;
32120
32268
  this._y = this._y * s3 + y5 * t3;
32121
- this._z = this._z * s3 + z43 * t3;
32269
+ this._z = this._z * s3 + z44 * t3;
32122
32270
  this._w = this._w * s3 + w2 * t3;
32123
32271
  this._onChangeCallback();
32124
32272
  } else {
32125
32273
  this._x = this._x * s3 + x3 * t3;
32126
32274
  this._y = this._y * s3 + y5 * t3;
32127
- this._z = this._z * s3 + z43 * t3;
32275
+ this._z = this._z * s3 + z44 * t3;
32128
32276
  this._w = this._w * s3 + w2 * t3;
32129
32277
  this.normalize();
32130
32278
  }
@@ -32247,10 +32395,10 @@ var init_three_core = __esm({
32247
32395
  * @param {number} [y=0] - The y value of this vector.
32248
32396
  * @param {number} [z=0] - The z value of this vector.
32249
32397
  */
32250
- constructor(x3 = 0, y5 = 0, z43 = 0) {
32398
+ constructor(x3 = 0, y5 = 0, z44 = 0) {
32251
32399
  this.x = x3;
32252
32400
  this.y = y5;
32253
- this.z = z43;
32401
+ this.z = z44;
32254
32402
  }
32255
32403
  /**
32256
32404
  * Sets the vector components.
@@ -32260,11 +32408,11 @@ var init_three_core = __esm({
32260
32408
  * @param {number} z - The value of the z component.
32261
32409
  * @return {Vector3} A reference to this vector.
32262
32410
  */
32263
- set(x3, y5, z43) {
32264
- if (z43 === void 0) z43 = this.z;
32411
+ set(x3, y5, z44) {
32412
+ if (z44 === void 0) z44 = this.z;
32265
32413
  this.x = x3;
32266
32414
  this.y = y5;
32267
- this.z = z43;
32415
+ this.z = z44;
32268
32416
  return this;
32269
32417
  }
32270
32418
  /**
@@ -32305,8 +32453,8 @@ var init_three_core = __esm({
32305
32453
  * @param {number} z - The value to set.
32306
32454
  * @return {Vector3} A reference to this vector.
32307
32455
  */
32308
- setZ(z43) {
32309
- this.z = z43;
32456
+ setZ(z44) {
32457
+ this.z = z44;
32310
32458
  return this;
32311
32459
  }
32312
32460
  /**
@@ -32520,11 +32668,11 @@ var init_three_core = __esm({
32520
32668
  * @return {Vector3} A reference to this vector.
32521
32669
  */
32522
32670
  applyMatrix3(m3) {
32523
- const x3 = this.x, y5 = this.y, z43 = this.z;
32671
+ const x3 = this.x, y5 = this.y, z44 = this.z;
32524
32672
  const e2 = m3.elements;
32525
- this.x = e2[0] * x3 + e2[3] * y5 + e2[6] * z43;
32526
- this.y = e2[1] * x3 + e2[4] * y5 + e2[7] * z43;
32527
- this.z = e2[2] * x3 + e2[5] * y5 + e2[8] * z43;
32673
+ this.x = e2[0] * x3 + e2[3] * y5 + e2[6] * z44;
32674
+ this.y = e2[1] * x3 + e2[4] * y5 + e2[7] * z44;
32675
+ this.z = e2[2] * x3 + e2[5] * y5 + e2[8] * z44;
32528
32676
  return this;
32529
32677
  }
32530
32678
  /**
@@ -32545,12 +32693,12 @@ var init_three_core = __esm({
32545
32693
  * @return {Vector3} A reference to this vector.
32546
32694
  */
32547
32695
  applyMatrix4(m3) {
32548
- const x3 = this.x, y5 = this.y, z43 = this.z;
32696
+ const x3 = this.x, y5 = this.y, z44 = this.z;
32549
32697
  const e2 = m3.elements;
32550
- const w2 = 1 / (e2[3] * x3 + e2[7] * y5 + e2[11] * z43 + e2[15]);
32551
- this.x = (e2[0] * x3 + e2[4] * y5 + e2[8] * z43 + e2[12]) * w2;
32552
- this.y = (e2[1] * x3 + e2[5] * y5 + e2[9] * z43 + e2[13]) * w2;
32553
- this.z = (e2[2] * x3 + e2[6] * y5 + e2[10] * z43 + e2[14]) * w2;
32698
+ const w2 = 1 / (e2[3] * x3 + e2[7] * y5 + e2[11] * z44 + e2[15]);
32699
+ this.x = (e2[0] * x3 + e2[4] * y5 + e2[8] * z44 + e2[12]) * w2;
32700
+ this.y = (e2[1] * x3 + e2[5] * y5 + e2[9] * z44 + e2[13]) * w2;
32701
+ this.z = (e2[2] * x3 + e2[6] * y5 + e2[10] * z44 + e2[14]) * w2;
32554
32702
  return this;
32555
32703
  }
32556
32704
  /**
@@ -32598,11 +32746,11 @@ var init_three_core = __esm({
32598
32746
  * @return {Vector3} A reference to this vector.
32599
32747
  */
32600
32748
  transformDirection(m3) {
32601
- const x3 = this.x, y5 = this.y, z43 = this.z;
32749
+ const x3 = this.x, y5 = this.y, z44 = this.z;
32602
32750
  const e2 = m3.elements;
32603
- this.x = e2[0] * x3 + e2[4] * y5 + e2[8] * z43;
32604
- this.y = e2[1] * x3 + e2[5] * y5 + e2[9] * z43;
32605
- this.z = e2[2] * x3 + e2[6] * y5 + e2[10] * z43;
32751
+ this.x = e2[0] * x3 + e2[4] * y5 + e2[8] * z44;
32752
+ this.y = e2[1] * x3 + e2[5] * y5 + e2[9] * z44;
32753
+ this.z = e2[2] * x3 + e2[6] * y5 + e2[10] * z44;
32606
32754
  return this.normalize();
32607
32755
  }
32608
32756
  /**
@@ -34139,10 +34287,10 @@ var init_three_core = __esm({
34139
34287
  * @param {number} [z=0] - The z value of this vector.
34140
34288
  * @param {number} [w=1] - The w value of this vector.
34141
34289
  */
34142
- constructor(x3 = 0, y5 = 0, z43 = 0, w2 = 1) {
34290
+ constructor(x3 = 0, y5 = 0, z44 = 0, w2 = 1) {
34143
34291
  this.x = x3;
34144
34292
  this.y = y5;
34145
- this.z = z43;
34293
+ this.z = z44;
34146
34294
  this.w = w2;
34147
34295
  }
34148
34296
  /**
@@ -34176,10 +34324,10 @@ var init_three_core = __esm({
34176
34324
  * @param {number} w - The value of the w component.
34177
34325
  * @return {Vector4} A reference to this vector.
34178
34326
  */
34179
- set(x3, y5, z43, w2) {
34327
+ set(x3, y5, z44, w2) {
34180
34328
  this.x = x3;
34181
34329
  this.y = y5;
34182
- this.z = z43;
34330
+ this.z = z44;
34183
34331
  this.w = w2;
34184
34332
  return this;
34185
34333
  }
@@ -34222,8 +34370,8 @@ var init_three_core = __esm({
34222
34370
  * @param {number} z - The value to set.
34223
34371
  * @return {Vector4} A reference to this vector.
34224
34372
  */
34225
- setZ(z43) {
34226
- this.z = z43;
34373
+ setZ(z44) {
34374
+ this.z = z44;
34227
34375
  return this;
34228
34376
  }
34229
34377
  /**
@@ -34432,12 +34580,12 @@ var init_three_core = __esm({
34432
34580
  * @return {Vector4} A reference to this vector.
34433
34581
  */
34434
34582
  applyMatrix4(m3) {
34435
- const x3 = this.x, y5 = this.y, z43 = this.z, w2 = this.w;
34583
+ const x3 = this.x, y5 = this.y, z44 = this.z, w2 = this.w;
34436
34584
  const e2 = m3.elements;
34437
- this.x = e2[0] * x3 + e2[4] * y5 + e2[8] * z43 + e2[12] * w2;
34438
- this.y = e2[1] * x3 + e2[5] * y5 + e2[9] * z43 + e2[13] * w2;
34439
- this.z = e2[2] * x3 + e2[6] * y5 + e2[10] * z43 + e2[14] * w2;
34440
- this.w = e2[3] * x3 + e2[7] * y5 + e2[11] * z43 + e2[15] * w2;
34585
+ this.x = e2[0] * x3 + e2[4] * y5 + e2[8] * z44 + e2[12] * w2;
34586
+ this.y = e2[1] * x3 + e2[5] * y5 + e2[9] * z44 + e2[13] * w2;
34587
+ this.z = e2[2] * x3 + e2[6] * y5 + e2[10] * z44 + e2[14] * w2;
34588
+ this.w = e2[3] * x3 + e2[7] * y5 + e2[11] * z44 + e2[15] * w2;
34441
34589
  return this;
34442
34590
  }
34443
34591
  /**
@@ -34491,7 +34639,7 @@ var init_three_core = __esm({
34491
34639
  * @return {Vector4} A reference to this vector.
34492
34640
  */
34493
34641
  setAxisAngleFromRotationMatrix(m3) {
34494
- let angle, x3, y5, z43;
34642
+ let angle, x3, y5, z44;
34495
34643
  const epsilon = 0.01, epsilon2 = 0.1, te2 = m3.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10];
34496
34644
  if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
34497
34645
  if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
@@ -34509,34 +34657,34 @@ var init_three_core = __esm({
34509
34657
  if (xx < epsilon) {
34510
34658
  x3 = 0;
34511
34659
  y5 = 0.707106781;
34512
- z43 = 0.707106781;
34660
+ z44 = 0.707106781;
34513
34661
  } else {
34514
34662
  x3 = Math.sqrt(xx);
34515
34663
  y5 = xy / x3;
34516
- z43 = xz / x3;
34664
+ z44 = xz / x3;
34517
34665
  }
34518
34666
  } else if (yy > zz) {
34519
34667
  if (yy < epsilon) {
34520
34668
  x3 = 0.707106781;
34521
34669
  y5 = 0;
34522
- z43 = 0.707106781;
34670
+ z44 = 0.707106781;
34523
34671
  } else {
34524
34672
  y5 = Math.sqrt(yy);
34525
34673
  x3 = xy / y5;
34526
- z43 = yz / y5;
34674
+ z44 = yz / y5;
34527
34675
  }
34528
34676
  } else {
34529
34677
  if (zz < epsilon) {
34530
34678
  x3 = 0.707106781;
34531
34679
  y5 = 0.707106781;
34532
- z43 = 0;
34680
+ z44 = 0;
34533
34681
  } else {
34534
- z43 = Math.sqrt(zz);
34535
- x3 = xz / z43;
34536
- y5 = yz / z43;
34682
+ z44 = Math.sqrt(zz);
34683
+ x3 = xz / z44;
34684
+ y5 = yz / z44;
34537
34685
  }
34538
34686
  }
34539
- this.set(x3, y5, z43, angle);
34687
+ this.set(x3, y5, z44, angle);
34540
34688
  return this;
34541
34689
  }
34542
34690
  let s3 = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12));
@@ -35150,10 +35298,10 @@ var init_three_core = __esm({
35150
35298
  */
35151
35299
  makeRotationFromEuler(euler) {
35152
35300
  const te2 = this.elements;
35153
- const x3 = euler.x, y5 = euler.y, z43 = euler.z;
35301
+ const x3 = euler.x, y5 = euler.y, z44 = euler.z;
35154
35302
  const a3 = Math.cos(x3), b3 = Math.sin(x3);
35155
35303
  const c3 = Math.cos(y5), d4 = Math.sin(y5);
35156
- const e2 = Math.cos(z43), f6 = Math.sin(z43);
35304
+ const e2 = Math.cos(z44), f6 = Math.sin(z44);
35157
35305
  if (euler.order === "XYZ") {
35158
35306
  const ae = a3 * e2, af = a3 * f6, be = b3 * e2, bf = b3 * f6;
35159
35307
  te2[0] = c3 * e2;
@@ -35438,7 +35586,7 @@ var init_three_core = __esm({
35438
35586
  * @param {number} z - The z component of the vector.
35439
35587
  * @return {Matrix4} A reference to this matrix.
35440
35588
  */
35441
- setPosition(x3, y5, z43) {
35589
+ setPosition(x3, y5, z44) {
35442
35590
  const te2 = this.elements;
35443
35591
  if (x3.isVector3) {
35444
35592
  te2[12] = x3.x;
@@ -35447,7 +35595,7 @@ var init_three_core = __esm({
35447
35595
  } else {
35448
35596
  te2[12] = x3;
35449
35597
  te2[13] = y5;
35450
- te2[14] = z43;
35598
+ te2[14] = z44;
35451
35599
  }
35452
35600
  return this;
35453
35601
  }
@@ -35489,19 +35637,19 @@ var init_three_core = __esm({
35489
35637
  */
35490
35638
  scale(v2) {
35491
35639
  const te2 = this.elements;
35492
- const x3 = v2.x, y5 = v2.y, z43 = v2.z;
35640
+ const x3 = v2.x, y5 = v2.y, z44 = v2.z;
35493
35641
  te2[0] *= x3;
35494
35642
  te2[4] *= y5;
35495
- te2[8] *= z43;
35643
+ te2[8] *= z44;
35496
35644
  te2[1] *= x3;
35497
35645
  te2[5] *= y5;
35498
- te2[9] *= z43;
35646
+ te2[9] *= z44;
35499
35647
  te2[2] *= x3;
35500
35648
  te2[6] *= y5;
35501
- te2[10] *= z43;
35649
+ te2[10] *= z44;
35502
35650
  te2[3] *= x3;
35503
35651
  te2[7] *= y5;
35504
- te2[11] *= z43;
35652
+ te2[11] *= z44;
35505
35653
  return this;
35506
35654
  }
35507
35655
  /**
@@ -35524,7 +35672,7 @@ var init_three_core = __esm({
35524
35672
  * @param {number} z - The amount to translate in the z axis.
35525
35673
  * @return {Matrix4} A reference to this matrix.
35526
35674
  */
35527
- makeTranslation(x3, y5, z43) {
35675
+ makeTranslation(x3, y5, z44) {
35528
35676
  if (x3.isVector3) {
35529
35677
  this.set(
35530
35678
  1,
@@ -35557,7 +35705,7 @@ var init_three_core = __esm({
35557
35705
  0,
35558
35706
  0,
35559
35707
  1,
35560
- z43,
35708
+ z44,
35561
35709
  0,
35562
35710
  0,
35563
35711
  0,
@@ -35668,20 +35816,20 @@ var init_three_core = __esm({
35668
35816
  const c3 = Math.cos(angle);
35669
35817
  const s3 = Math.sin(angle);
35670
35818
  const t3 = 1 - c3;
35671
- const x3 = axis.x, y5 = axis.y, z43 = axis.z;
35819
+ const x3 = axis.x, y5 = axis.y, z44 = axis.z;
35672
35820
  const tx = t3 * x3, ty = t3 * y5;
35673
35821
  this.set(
35674
35822
  tx * x3 + c3,
35675
- tx * y5 - s3 * z43,
35676
- tx * z43 + s3 * y5,
35823
+ tx * y5 - s3 * z44,
35824
+ tx * z44 + s3 * y5,
35677
35825
  0,
35678
- tx * y5 + s3 * z43,
35826
+ tx * y5 + s3 * z44,
35679
35827
  ty * y5 + c3,
35680
- ty * z43 - s3 * x3,
35828
+ ty * z44 - s3 * x3,
35681
35829
  0,
35682
- tx * z43 - s3 * y5,
35683
- ty * z43 + s3 * x3,
35684
- t3 * z43 * z43 + c3,
35830
+ tx * z44 - s3 * y5,
35831
+ ty * z44 + s3 * x3,
35832
+ t3 * z44 * z44 + c3,
35685
35833
  0,
35686
35834
  0,
35687
35835
  0,
@@ -35698,7 +35846,7 @@ var init_three_core = __esm({
35698
35846
  * @param {number} z - The amount to scale in the Z axis.
35699
35847
  * @return {Matrix4} A reference to this matrix.
35700
35848
  */
35701
- makeScale(x3, y5, z43) {
35849
+ makeScale(x3, y5, z44) {
35702
35850
  this.set(
35703
35851
  x3,
35704
35852
  0,
@@ -35710,7 +35858,7 @@ var init_three_core = __esm({
35710
35858
  0,
35711
35859
  0,
35712
35860
  0,
35713
- z43,
35861
+ z44,
35714
35862
  0,
35715
35863
  0,
35716
35864
  0,
@@ -35762,10 +35910,10 @@ var init_three_core = __esm({
35762
35910
  */
35763
35911
  compose(position, quaternion, scale) {
35764
35912
  const te2 = this.elements;
35765
- const x3 = quaternion._x, y5 = quaternion._y, z43 = quaternion._z, w2 = quaternion._w;
35766
- const x22 = x3 + x3, y22 = y5 + y5, z210 = z43 + z43;
35913
+ const x3 = quaternion._x, y5 = quaternion._y, z44 = quaternion._z, w2 = quaternion._w;
35914
+ const x22 = x3 + x3, y22 = y5 + y5, z210 = z44 + z44;
35767
35915
  const xx = x3 * x22, xy = x3 * y22, xz = x3 * z210;
35768
- const yy = y5 * y22, yz = y5 * z210, zz = z43 * z210;
35916
+ const yy = y5 * y22, yz = y5 * z210, zz = z44 * z210;
35769
35917
  const wx = w2 * x22, wy = w2 * y22, wz = w2 * z210;
35770
35918
  const sx = scale.x, sy = scale.y, sz = scale.z;
35771
35919
  te2[0] = (1 - (yy + zz)) * sx;
@@ -36013,11 +36161,11 @@ var init_three_core = __esm({
36013
36161
  * @param {number} [z=0] - The angle of the z axis in radians.
36014
36162
  * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
36015
36163
  */
36016
- constructor(x3 = 0, y5 = 0, z43 = 0, order = _Euler.DEFAULT_ORDER) {
36164
+ constructor(x3 = 0, y5 = 0, z44 = 0, order = _Euler.DEFAULT_ORDER) {
36017
36165
  this.isEuler = true;
36018
36166
  this._x = x3;
36019
36167
  this._y = y5;
36020
- this._z = z43;
36168
+ this._z = z44;
36021
36169
  this._order = order;
36022
36170
  }
36023
36171
  /**
@@ -36081,10 +36229,10 @@ var init_three_core = __esm({
36081
36229
  * @param {string} [order] - A string representing the order that the rotations are applied.
36082
36230
  * @return {Euler} A reference to this Euler instance.
36083
36231
  */
36084
- set(x3, y5, z43, order = this._order) {
36232
+ set(x3, y5, z44, order = this._order) {
36085
36233
  this._x = x3;
36086
36234
  this._y = y5;
36087
- this._z = z43;
36235
+ this._z = z44;
36088
36236
  this._order = order;
36089
36237
  this._onChangeCallback();
36090
36238
  return this;
@@ -36704,11 +36852,11 @@ var init_three_core = __esm({
36704
36852
  * @param {number} [y] - The y coordinate in world space.
36705
36853
  * @param {number} [z] - The z coordinate in world space.
36706
36854
  */
36707
- lookAt(x3, y5, z43) {
36855
+ lookAt(x3, y5, z44) {
36708
36856
  if (x3.isVector3) {
36709
36857
  _target.copy(x3);
36710
36858
  } else {
36711
- _target.set(x3, y5, z43);
36859
+ _target.set(x3, y5, z44);
36712
36860
  }
36713
36861
  const parent = this.parent;
36714
36862
  this.updateWorldMatrix(true, false);
@@ -43006,7 +43154,11 @@ async function resolveP2pPaymentRequest(params) {
43006
43154
  const priceFor3 = (a3) => (a3.pricing ?? []).find((p5) => p5.capability === capability)?.unit_cost ?? (a3.pricing ?? [])[0]?.unit_cost ?? void 0;
43007
43155
  const chosenId = await params.selectWorker(admissible.map((a3) => {
43008
43156
  const unitCost = priceFor3(a3);
43009
- return { motebit_id: a3.motebit_id, ...unitCost != null ? { unitCost } : {} };
43157
+ return {
43158
+ motebit_id: a3.motebit_id,
43159
+ ...unitCost != null ? { unitCost } : {},
43160
+ ...a3.bonded === true ? { bonded: true } : {}
43161
+ };
43010
43162
  }));
43011
43163
  if (chosenId != null) {
43012
43164
  const chosen = admissible.find((a3) => a3.motebit_id === chosenId);
@@ -53495,7 +53647,7 @@ ${snippet}`;
53495
53647
  * CLI/desktop/mobile with SQLite is sync all the way down and needs
53496
53648
  * no preload.
53497
53649
  */
53498
- searchHistory(query, limit = 5) {
53650
+ searchHistory(query, limit = 5, sensitivityFilter) {
53499
53651
  const { store } = this.deps;
53500
53652
  if (store == null)
53501
53653
  return [];
@@ -53506,6 +53658,9 @@ ${snippet}`;
53506
53658
  for (const m3 of msgs) {
53507
53659
  if (m3.role !== "user" && m3.role !== "assistant")
53508
53660
  continue;
53661
+ if (sensitivityFilter != null && (m3.sensitivity == null || !sensitivityFilter.includes(m3.sensitivity))) {
53662
+ continue;
53663
+ }
53509
53664
  messages.push({
53510
53665
  conversationId: c3.conversationId,
53511
53666
  role: m3.role,
@@ -56522,6 +56677,13 @@ var init_motebit_runtime = __esm({
56522
56677
  latencyStatsStore;
56523
56678
  agentGraph;
56524
56679
  _signingKeys;
56680
+ /**
56681
+ * Bounded buffer of recently minted routing-decision transcripts
56682
+ * (docs/doctrine/routing-decision-transcript.md — minted always, retained
56683
+ * locally, egressed on dispute or owner choice, never broadcast). The
56684
+ * `getRecentApprovalDecisions()` buffer-and-getter shape.
56685
+ */
56686
+ _recentRoutingTranscripts = [];
56525
56687
  /**
56526
56688
  * Sovereign Solana wallet rail. Null when the runtime has no signing keys
56527
56689
  * or the caller did not configure a Solana rail. When present, exposes
@@ -58033,7 +58195,8 @@ var init_motebit_runtime = __esm({
58033
58195
  * logic.
58034
58196
  */
58035
58197
  searchConversations(query, limit = 5) {
58036
- return this.conversation.searchHistory(query, limit);
58198
+ const sensitivityFilter = this.providerIsSovereign() ? void 0 : CONTEXT_SAFE_SENSITIVITY;
58199
+ return this.conversation.searchHistory(query, limit, sensitivityFilter);
58037
58200
  }
58038
58201
  /**
58039
58202
  * Resolve when no background memory-formation jobs are pending.
@@ -59017,6 +59180,18 @@ var init_motebit_runtime = __esm({
59017
59180
  getRecentApprovalDecisions() {
59018
59181
  return this._recentApprovalDecisions;
59019
59182
  }
59183
+ /**
59184
+ * Recently minted routing-decision transcripts, newest last — the signed
59185
+ * record of why each ranked paid hire won
59186
+ * (docs/doctrine/routing-decision-transcript.md). Session-scoped and
59187
+ * bounded, like `getRecentApprovalDecisions()`: disclosure is
59188
+ * dispute-scoped or owner-initiated, never broadcast, and the buffer
59189
+ * REVEALS, never authorizes. Durable cross-restart archival is a deferred,
59190
+ * consumer-shaped concern.
59191
+ */
59192
+ getRecentRoutingTranscripts() {
59193
+ return this._recentRoutingTranscripts;
59194
+ }
59020
59195
  /**
59021
59196
  * Per-session pixel-passthrough consent. Composed into the loop's
59022
59197
  * `projectForAi` pixel gate alongside provider mode and effective
@@ -59179,6 +59354,41 @@ var init_motebit_runtime = __esm({
59179
59354
  providerIsSovereign() {
59180
59355
  return this._providerMode === "on-device";
59181
59356
  }
59357
+ /**
59358
+ * The `recall_memories` tool's search backend — the ONE sanctioned path for
59359
+ * the agent's explicit memory recall, so the egress boundary lives here and
59360
+ * cannot be forgotten per-surface (it was, on all four; that leak is what this
59361
+ * method closes). Surfaces wire it as `memorySearchFn` instead of hand-rolling
59362
+ * a `memory.recallRelevant` closure.
59363
+ *
59364
+ * The load-bearing privacy invariant (root CLAUDE.md — "medical/financial/
59365
+ * secret never reach external AI") is enforced here by keying the sensitivity
59366
+ * ceiling on the provider: an EXTERNAL provider gets only `CONTEXT_SAFE_
59367
+ * SENSITIVITY` (< medical), so a stored medical/financial/secret memory is
59368
+ * never returned toward it; a SOVEREIGN (on-device) provider recalls every
59369
+ * tier, because that content never leaves the device. Fail-closed: an unset
59370
+ * provider mode is non-sovereign, so it also gets the filtered set.
59371
+ *
59372
+ * Embeds, recalls (threading the bi-temporal `asOf` / `includeExpired` modes),
59373
+ * and maps to the tool's result shape (`supersededAt` from `valid_until`).
59374
+ */
59375
+ async recallMemoriesForTool(query, opts) {
59376
+ const queryEmbedding = await embedText(query);
59377
+ const nodes = await this.memory.recallRelevant(queryEmbedding, {
59378
+ limit: opts.limit,
59379
+ ...opts.asOf != null ? { asOf: opts.asOf } : {},
59380
+ ...opts.includeExpired ? { includeExpired: true } : {},
59381
+ // Egress ceiling: undefined ⇒ no filter (sovereign, all tiers stay local);
59382
+ // otherwise restrict to the context-safe tiers before anything can reach
59383
+ // an external provider.
59384
+ ...this.providerIsSovereign() ? {} : { sensitivityFilter: [...CONTEXT_SAFE_SENSITIVITY] }
59385
+ });
59386
+ return nodes.map((n2) => ({
59387
+ content: n2.content,
59388
+ confidence: n2.confidence,
59389
+ ...n2.valid_until != null ? { supersededAt: n2.valid_until } : {}
59390
+ }));
59391
+ }
59182
59392
  /**
59183
59393
  * Effective session sensitivity — the max of the explicit
59184
59394
  * `_sessionSensitivity` (set via `setSessionSensitivity`) and the
@@ -59722,25 +59932,61 @@ var init_motebit_runtime = __esm({
59722
59932
  const rankable = await Promise.all(candidates.map(async (c3) => ({
59723
59933
  motebit_id: c3.motebit_id,
59724
59934
  trustRecord: await this.getAgentTrust(c3.motebit_id),
59725
- ...c3.unitCost != null ? { unitCost: c3.unitCost } : {}
59935
+ ...c3.unitCost != null ? { unitCost: c3.unitCost } : {},
59936
+ // Relay-verified commitment bond → exploration PRIORITY
59937
+ // (a faster shot, never a quality score — the sybil-swarm
59938
+ // bound of docs/doctrine/exploration-as-market-vitality.md
59939
+ // Inc 2, live on real hops now that discovery surfaces it).
59940
+ ...c3.bonded === true ? { bonded: true } : {}
59726
59941
  })));
59727
59942
  const repCostUsd = Math.min(...rankable.map((r2) => r2.unitCost ?? 0));
59728
59943
  const strength = explorationStrengthForStakes(repCostUsd);
59729
59944
  const capability = params.capability;
59730
- const exploitTop = selectWorker(this.motebitId, rankable, { capability });
59731
- const winner = selectWorker(this.motebitId, rankable, {
59945
+ const { winner, basis } = rankWorkersWithBasis(this.motebitId, rankable, {
59732
59946
  capability,
59733
59947
  explore: { seed: exploreSeed, strength }
59734
59948
  });
59735
- if (winner != null) {
59949
+ if (winner != null && basis != null) {
59736
59950
  this._logger.warn("routing.worker_selected", {
59737
59951
  selected: winner.motebit_id,
59738
59952
  capability,
59739
59953
  candidates: rankable.length,
59740
59954
  strength: Number(strength.toFixed(3)),
59741
- explored: exploitTop != null && winner.motebit_id !== exploitTop.motebit_id,
59742
- quality: Number(winner.route.trust.toFixed(3))
59955
+ explored: basis.explored,
59956
+ quality: Number(winner.route.trust.toFixed(3)),
59957
+ bonded: rankable.find((r2) => r2.motebit_id === winner.motebit_id)?.bonded === true
59743
59958
  });
59959
+ if (this._signingKeys != null) {
59960
+ try {
59961
+ const transcript = await signRoutingTranscript({
59962
+ spec: "motebit/routing-transcript@1.0",
59963
+ delegator_motebit_id: this.motebitId,
59964
+ delegator_public_key: bytesToHex4(this._signingKeys.publicKey),
59965
+ issued_at: Date.now(),
59966
+ ...basis
59967
+ }, this._signingKeys.privateKey);
59968
+ this._recentRoutingTranscripts.push(transcript);
59969
+ if (this._recentRoutingTranscripts.length > 50) {
59970
+ this._recentRoutingTranscripts.shift();
59971
+ }
59972
+ this._logger.warn("routing.transcript_minted", {
59973
+ winner: transcript.winner_motebit_id,
59974
+ capability: transcript.capability,
59975
+ candidates: transcript.candidates.length,
59976
+ explored: transcript.explored,
59977
+ // The signature is the transcript's collision-resistant
59978
+ // handle (it covers the JCS-canonical bytes) — the
59979
+ // binding key a consumer joins on. Wire-level digest
59980
+ // binding into the delegation record lands with Inc 4's
59981
+ // consumer (the conformance probe), consumer-forced.
59982
+ transcript_sig: transcript.signature.slice(0, 16)
59983
+ });
59984
+ } catch (err2) {
59985
+ this._logger.warn("routing.transcript_mint_failed", {
59986
+ error: err2 instanceof Error ? err2.message : String(err2)
59987
+ });
59988
+ }
59989
+ }
59744
59990
  }
59745
59991
  return winner?.motebit_id ?? null;
59746
59992
  };
@@ -83039,6 +83285,53 @@ var init_eval_attestation2 = __esm({
83039
83285
  }
83040
83286
  });
83041
83287
 
83288
+ // ../../packages/wire-schemas/dist/routing-transcript.js
83289
+ import { z as z40 } from "zod";
83290
+ import { zodToJsonSchema as zodToJsonSchema39 } from "zod-to-json-schema";
83291
+ var TranscriptCandidateSchema, RoutingDecisionTranscriptSchema;
83292
+ var init_routing_transcript2 = __esm({
83293
+ "../../packages/wire-schemas/dist/routing-transcript.js"() {
83294
+ "use strict";
83295
+ init_esm_shims();
83296
+ init_assemble();
83297
+ TranscriptCandidateSchema = z40.object({
83298
+ motebit_id: z40.string().min(1),
83299
+ unit_cost: z40.number().nonnegative().optional(),
83300
+ bonded: z40.literal(true).optional(),
83301
+ trust_axis: z40.number(),
83302
+ reliability_axis: z40.number(),
83303
+ alpha: z40.number().int().positive().optional(),
83304
+ beta: z40.number().int().positive().optional(),
83305
+ theta: z40.number().optional()
83306
+ }).strict();
83307
+ RoutingDecisionTranscriptSchema = z40.object({
83308
+ spec: z40.literal("motebit/routing-transcript@1.0").describe("Wire-format version discriminator."),
83309
+ capability: z40.string().describe("The capability hired for."),
83310
+ delegator_motebit_id: z40.string().min(1).describe("The delegator \u2014 the chooser and the signer (subject = signer)."),
83311
+ delegator_public_key: z40.string().regex(/^[0-9a-f]{64}$/).describe("The delegator's Ed25519 public key, lowercase hex."),
83312
+ candidates: z40.array(TranscriptCandidateSchema).min(1).describe("The frozen admissible candidate set, in ranked order."),
83313
+ seed: z40.string().describe("Seed provenance: the tick token's Ed25519 signature \u2014 binds the transcript to the delegation turn; per-candidate draw seed is `${seed}|${motebit_id}`."),
83314
+ strength: z40.number().min(0).max(1).describe("Base exploration strength in [0,1], before any bond boost."),
83315
+ weights: z40.object({
83316
+ trust: z40.number(),
83317
+ reliability: z40.number(),
83318
+ cost: z40.number(),
83319
+ latency: z40.number()
83320
+ }).strict().describe("The composite weights the ranking consumed."),
83321
+ count_cap: z40.number().int().positive().describe("Evidence cap applied to posterior counts (frozen ranker-internal literal)."),
83322
+ bond_explore_boost: z40.number().positive().describe("Multiplicative bond exploration boost (frozen ranker-internal literal)."),
83323
+ default_latency_ms: z40.number().nonnegative().describe("Neutral latency (ms) assumed per candidate (frozen ranker-internal literal)."),
83324
+ algorithm_version: z40.string().min(1).describe("The ranking-implementation version this transcript is recomputable under."),
83325
+ winner_motebit_id: z40.string().min(1).describe("The worker hired; MUST be a member of `candidates`."),
83326
+ pinned: z40.literal(true).optional().describe("Present (true) only when the hire was a pinned deterministic override \u2014 no draw ran."),
83327
+ explored: z40.boolean().describe("Whether the exploration draw overrode the exploit-favorite."),
83328
+ issued_at: z40.number().int().nonnegative().describe("Decision time, epoch milliseconds."),
83329
+ suite: z40.literal("motebit-jcs-ed25519-b64-v1").describe("Cryptosuite (pinned literal \u2014 new suites arrive as new transcript versions)."),
83330
+ signature: z40.string().min(1).describe("Ed25519 over the JCS-canonical transcript minus this field, base64url.")
83331
+ }).strict();
83332
+ }
83333
+ });
83334
+
83042
83335
  // ../../packages/wire-schemas/dist/index.js
83043
83336
  var init_dist31 = __esm({
83044
83337
  "../../packages/wire-schemas/dist/index.js"() {
@@ -83083,6 +83376,7 @@ var init_dist31 = __esm({
83083
83376
  init_retention_manifest();
83084
83377
  init_witness_omission_dispute();
83085
83378
  init_eval_attestation2();
83379
+ init_routing_transcript2();
83086
83380
  }
83087
83381
  });
83088
83382
 
@@ -84410,14 +84704,54 @@ function createRecallMemoriesHandler(searchFn) {
84410
84704
  if (!query)
84411
84705
  return { ok: false, error: "Missing required parameter: query" };
84412
84706
  const limit = args.limit ?? 5;
84707
+ const includeHistory = args.include_history === true;
84708
+ let asOf;
84709
+ const asOfRaw = args.as_of;
84710
+ if (asOfRaw != null && asOfRaw !== "") {
84711
+ if (typeof asOfRaw !== "string") {
84712
+ return { ok: false, error: "Invalid as_of: expected an ISO 8601 date string." };
84713
+ }
84714
+ const parsed = Date.parse(asOfRaw);
84715
+ if (Number.isNaN(parsed)) {
84716
+ return {
84717
+ ok: false,
84718
+ error: `Invalid as_of date: "${asOfRaw}". Use an ISO 8601 date, e.g. "2026-06-01".`
84719
+ };
84720
+ }
84721
+ asOf = parsed;
84722
+ }
84723
+ if (asOf != null && includeHistory) {
84724
+ return {
84725
+ ok: false,
84726
+ error: "Use as_of OR include_history, not both: as_of is a point-in-time snapshot; include_history returns every version."
84727
+ };
84728
+ }
84413
84729
  try {
84414
- const memories = await searchFn(query, limit);
84730
+ const memories = await searchFn(query, {
84731
+ limit,
84732
+ ...asOf != null ? { asOf } : {},
84733
+ ...includeHistory ? { includeExpired: true } : {}
84734
+ });
84415
84735
  if (memories.length === 0) {
84416
- return { ok: true, data: "No relevant memories found." };
84736
+ return {
84737
+ ok: true,
84738
+ data: asOf != null ? `No memories were valid as of ${new Date(asOf).toISOString()}.` : "No relevant memories found."
84739
+ };
84417
84740
  }
84418
84741
  const escape3 = (content) => content.replace(/\[MEMORY_DATA\b/g, "[ESCAPED_MEMORY").replace(/\[\/MEMORY_DATA\]/g, "[/ESCAPED_MEMORY]").replace(/\[from:/g, "[escaped-from:");
84419
- const formatted = memories.map((m3, i3) => `${i3 + 1}. [confidence=${m3.confidence.toFixed(2)}] ${escape3(m3.content)}`).join("\n");
84420
- return { ok: true, data: formatted };
84742
+ const formatted = memories.map((m3, i3) => {
84743
+ const status = includeHistory ? m3.supersededAt != null ? `[superseded ${new Date(m3.supersededAt).toISOString()}] ` : "[current] " : "";
84744
+ return `${i3 + 1}. ${status}[confidence=${m3.confidence.toFixed(2)}] ${escape3(m3.content)}`;
84745
+ }).join("\n");
84746
+ let data = formatted;
84747
+ if (asOf != null) {
84748
+ data = `As of ${new Date(asOf).toISOString()}, you believed (historical snapshot \u2014 some may since have been superseded):
84749
+ ${formatted}`;
84750
+ } else if (includeHistory) {
84751
+ data = `All versions found \u2014 current beliefs and the ones they replaced. A [superseded] entry is NOT current fact:
84752
+ ${formatted}`;
84753
+ }
84754
+ return { ok: true, data };
84421
84755
  } catch (err2) {
84422
84756
  const msg = err2 instanceof Error ? err2.message : String(err2);
84423
84757
  return { ok: false, error: `Memory search error: ${msg}` };
@@ -84432,12 +84766,20 @@ var init_recall_memories = __esm({
84432
84766
  recallMemoriesDefinition = {
84433
84767
  name: "recall_memories",
84434
84768
  mode: "api",
84435
- description: "Search your own memory graph for relevant information. Use when you need to remember something about the user or past conversations.",
84769
+ description: 'Search your own memory graph for relevant information. Use when you need to remember something about the user or past conversations. Two optional bi-temporal modes (mutually exclusive): pass `as_of` (an ISO date, e.g. "2026-06-01") to reconstruct what you believed AS OF that date; pass `include_history: true` to see ALL versions of a belief at once \u2014 current beliefs and the ones they replaced, each labelled. In both modes some results are beliefs you have since revised, so report them as past belief, never as current fact.',
84436
84770
  inputSchema: {
84437
84771
  type: "object",
84438
84772
  properties: {
84439
84773
  query: { type: "string", description: "What to search for in memories" },
84440
- limit: { type: "number", description: "Max results (default 5)" }
84774
+ limit: { type: "number", description: "Max results (default 5)" },
84775
+ as_of: {
84776
+ type: "string",
84777
+ description: "Optional ISO 8601 date/datetime. Reconstruct beliefs valid AS OF this point in time (a snapshot). Mutually exclusive with include_history. Omit for current recall."
84778
+ },
84779
+ include_history: {
84780
+ type: "boolean",
84781
+ description: "Optional. Return ALL versions of a belief \u2014 current and since-superseded \u2014 each labelled [current] or [superseded <date>]. Use to see how a belief changed. Mutually exclusive with as_of."
84782
+ }
84441
84783
  },
84442
84784
  required: ["query"]
84443
84785
  }
@@ -84492,7 +84834,7 @@ var init_rewrite_memory = __esm({
84492
84834
  rewriteMemoryDefinition = {
84493
84835
  name: "rewrite_memory",
84494
84836
  mode: "api",
84495
- description: "Correct a stale or incorrect memory by superseding it with new content. Use when you discover a previously-formed memory is wrong \u2014 the user corrected something, a newer fact contradicts an older one, or you realize your prior claim was mistaken. Pass the 8-char short node id shown in the memory index (the `[xxxxxxxx]` prefix). The original memory is tombstoned but preserved in the event log for audit.",
84837
+ description: "Correct a stale or incorrect memory by superseding it with new content. Use when you discover a previously-formed memory is wrong \u2014 the user corrected something, a newer fact contradicts an older one, or you realize your prior claim was mistaken. Pass the 8-char short node id shown in the memory index (the `[xxxxxxxx]` prefix). The original memory is not destroyed \u2014 it is superseded (marked no longer current) but kept, so it drops out of current recall yet can still be reconstructed via `recall_memories` with `as_of` or `include_history`.",
84496
84838
  inputSchema: {
84497
84839
  type: "object",
84498
84840
  properties: {
@@ -85394,11 +85736,9 @@ function buildToolRegistry(config, runtimeRef, motebitId) {
85394
85736
  registry.register(currentTimeDefinition, createCurrentTimeHandler());
85395
85737
  registry.register(webSearchDefinition, createWebSearchHandler(searchProvider));
85396
85738
  registry.register(readUrlDefinition, createReadUrlHandler());
85397
- const memorySearchFn = async (query, limit) => {
85739
+ const memorySearchFn = async (query, opts) => {
85398
85740
  if (!runtimeRef.current) return [];
85399
- const queryEmbedding = await embedText(query);
85400
- const nodes = await runtimeRef.current.memory.recallRelevant(queryEmbedding, { limit });
85401
- return nodes.map((n2) => ({ content: n2.content, confidence: n2.confidence }));
85741
+ return runtimeRef.current.recallMemoriesForTool(query, opts);
85402
85742
  };
85403
85743
  const eventQueryFn = async (limit, eventType) => {
85404
85744
  if (!runtimeRef.current) return [];
@@ -85616,7 +85956,6 @@ var init_runtime_factory = __esm({
85616
85956
  init_esm_shims();
85617
85957
  init_dist23();
85618
85958
  init_dist28();
85619
- init_dist3();
85620
85959
  init_dist4();
85621
85960
  init_dist30();
85622
85961
  init_dist20();
@@ -89980,6 +90319,24 @@ function enrichWithLatencyStats(agents, db) {
89980
90319
  return { ...a3, latency_stats: projection };
89981
90320
  });
89982
90321
  }
90322
+ function enrichWithBondStatus(agents, db, nowMs = Date.now()) {
90323
+ if (agents.length === 0)
90324
+ return agents;
90325
+ const placeholders = agents.map(() => "?").join(",");
90326
+ const rows = db.prepare(`SELECT DISTINCT motebit_id
90327
+ FROM relay_bond_commitments
90328
+ WHERE motebit_id IN (${placeholders})
90329
+ AND expires_at > ?
90330
+ AND backing_state = 'backed'`).all(...agents.map((a3) => a3.motebit_id), nowMs);
90331
+ if (rows.length === 0)
90332
+ return agents;
90333
+ const backed = new Set(rows.map((r2) => r2.motebit_id));
90334
+ return agents.map((a3) => {
90335
+ if (a3.bonded != null)
90336
+ return a3;
90337
+ return backed.has(a3.motebit_id) ? { ...a3, bonded: true } : a3;
90338
+ });
90339
+ }
89983
90340
  function registerAgentAuthMiddleware(deps) {
89984
90341
  const { app, apiToken, identityManager, parseTokenPayloadUnsafe: parseTokenPayloadUnsafe2, verifySignedTokenForDevice: verifySignedTokenForDevice2, isTokenBlacklisted, isAgentRevoked } = deps;
89985
90342
  app.use("/api/v1/agents/*", async (c3, next) => {
@@ -90568,7 +90925,8 @@ function registerAgentRoutes(deps) {
90568
90925
  const enriched = enrichWithCallerTrust(localResults, c3.get("callerMotebitId"), moteDb.db);
90569
90926
  const withHa2 = enrichWithHardwareAttestation(enriched, moteDb.db);
90570
90927
  const withLatency2 = enrichWithLatencyStats(withHa2, moteDb.db);
90571
- return c3.json({ agents: withLatency2 });
90928
+ const withBond2 = enrichWithBondStatus(withLatency2, moteDb.db);
90929
+ return c3.json({ agents: withBond2 });
90572
90930
  }
90573
90931
  const queryId = crypto.randomUUID();
90574
90932
  federationQueryCache.set(queryId, Date.now());
@@ -90576,17 +90934,18 @@ function registerAgentRoutes(deps) {
90576
90934
  const peers = moteDb.db.prepare("SELECT peer_relay_id, endpoint_url, public_key FROM relay_peers WHERE state = 'active'").all();
90577
90935
  const forwardPromises = peers.map(async (peer) => {
90578
90936
  try {
90937
+ const discoverBody = await signDiscoverBody({
90938
+ query: { capability, motebit_id: motebitId, limit },
90939
+ hop_count: 0,
90940
+ max_hops: 3,
90941
+ visited,
90942
+ query_id: queryId,
90943
+ origin_relay: relayIdentity.relayMotebitId
90944
+ }, relayIdentity);
90579
90945
  const resp = await fetch(`${peer.endpoint_url}/federation/v1/discover`, {
90580
90946
  method: "POST",
90581
90947
  headers: { "Content-Type": "application/json", "X-Correlation-ID": queryId },
90582
- body: JSON.stringify({
90583
- query: { capability, motebit_id: motebitId, limit },
90584
- hop_count: 0,
90585
- max_hops: 3,
90586
- visited,
90587
- query_id: queryId,
90588
- origin_relay: relayIdentity.relayMotebitId
90589
- }),
90948
+ body: JSON.stringify(discoverBody),
90590
90949
  signal: AbortSignal.timeout(5e3)
90591
90950
  });
90592
90951
  if (!resp.ok)
@@ -90610,8 +90969,9 @@ function registerAgentRoutes(deps) {
90610
90969
  const final = enrichWithCallerTrust(trimmed, c3.get("callerMotebitId"), moteDb.db);
90611
90970
  const withHa = enrichWithHardwareAttestation(final, moteDb.db);
90612
90971
  const withLatency = enrichWithLatencyStats(withHa, moteDb.db);
90972
+ const withBond = enrichWithBondStatus(withLatency, moteDb.db);
90613
90973
  const peerKeyById = new Map(peers.map((p5) => [p5.peer_relay_id, p5.public_key]));
90614
- const withPeerKey = withLatency.map((agent) => {
90974
+ const withPeerKey = withBond.map((agent) => {
90615
90975
  const sourceRelay = agent.source_relay;
90616
90976
  const peerKey = sourceRelay != null ? peerKeyById.get(sourceRelay) : void 0;
90617
90977
  return peerKey != null ? { ...agent, source_relay_public_key: peerKey } : agent;
@@ -91947,9 +92307,9 @@ var init_federation = __esm({
91947
92307
  init_retry_policy();
91948
92308
  init_dist31();
91949
92309
  FEDERATION_SUITE = "motebit-concat-ed25519-hex-v1";
91950
- RELAY_SPEC_VERSION = "motebit/relay-federation@1.3";
92310
+ RELAY_SPEC_VERSION = "motebit/relay-federation@1.4";
91951
92311
  logger18 = createLogger({ service: "relay", module: "federation" });
91952
- DEFAULT_REQUIRE_DISCOVER_SIGNATURE = false;
92312
+ DEFAULT_REQUIRE_DISCOVER_SIGNATURE = true;
91953
92313
  REVOCATION_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
91954
92314
  PBKDF2_ITERATIONS = 6e5;
91955
92315
  AUTH_TAG_BYTES = 16;
@@ -100642,7 +101002,7 @@ init_dist2();
100642
101002
  init_dist6();
100643
101003
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
100644
101004
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
100645
- import { z as z40 } from "zod";
101005
+ import { z as z41 } from "zod";
100646
101006
 
100647
101007
  // ../../packages/mcp-server/dist/service.js
100648
101008
  init_esm_shims();
@@ -100885,17 +101245,17 @@ function jsonSchemaToZodShape(inputSchema) {
100885
101245
  let zodType;
100886
101246
  switch (prop["type"]) {
100887
101247
  case "string":
100888
- zodType = z40.string();
101248
+ zodType = z41.string();
100889
101249
  break;
100890
101250
  case "number":
100891
101251
  case "integer":
100892
- zodType = z40.number();
101252
+ zodType = z41.number();
100893
101253
  break;
100894
101254
  case "boolean":
100895
- zodType = z40.boolean();
101255
+ zodType = z41.boolean();
100896
101256
  break;
100897
101257
  default:
100898
- zodType = z40.unknown();
101258
+ zodType = z41.unknown();
100899
101259
  break;
100900
101260
  }
100901
101261
  if (typeof prop["description"] === "string") {
@@ -101078,7 +101438,7 @@ var McpServerAdapter = class _McpServerAdapter {
101078
101438
  if (this.deps.sendMessage) {
101079
101439
  const sendMessage = this.deps.sendMessage;
101080
101440
  const toolDef = _McpServerAdapter.syntheticToolDef("motebit_query", "Ask this motebit a question \u2014 AI response with memory context", RiskLevel.R2_WRITE);
101081
- server.tool("motebit_query", "Ask this motebit a question \u2014 AI response with memory context", { message: z40.string().describe("The question or message to send") }, async (args) => {
101441
+ server.tool("motebit_query", "Ask this motebit a question \u2014 AI response with memory context", { message: z41.string().describe("The question or message to send") }, async (args) => {
101082
101442
  const denied = await this.validateSyntheticTool(toolDef, args);
101083
101443
  if (denied)
101084
101444
  return denied;
@@ -101091,8 +101451,8 @@ var McpServerAdapter = class _McpServerAdapter {
101091
101451
  const storeMemory = this.deps.storeMemory;
101092
101452
  const toolDef = _McpServerAdapter.syntheticToolDef("motebit_remember", "Store a memory in this motebit", RiskLevel.R2_WRITE);
101093
101453
  server.tool("motebit_remember", "Store a memory in this motebit", {
101094
- content: z40.string().describe("The content to remember"),
101095
- sensitivity: z40.string().optional().describe("Sensitivity level (none, personal)")
101454
+ content: z41.string().describe("The content to remember"),
101455
+ sensitivity: z41.string().optional().describe("Sensitivity level (none, personal)")
101096
101456
  }, async (args) => {
101097
101457
  const denied = await this.validateSyntheticTool(toolDef, args);
101098
101458
  if (denied)
@@ -101117,8 +101477,8 @@ var McpServerAdapter = class _McpServerAdapter {
101117
101477
  const queryMemories = this.deps.queryMemories;
101118
101478
  const toolDef = _McpServerAdapter.syntheticToolDef("motebit_recall", "Search this motebit's semantic memory", RiskLevel.R1_DRAFT);
101119
101479
  server.tool("motebit_recall", "Search this motebit's semantic memory", {
101120
- query: z40.string().describe("Semantic search query"),
101121
- limit: z40.number().optional().describe("Max results to return")
101480
+ query: z41.string().describe("Semantic search query"),
101481
+ limit: z41.number().optional().describe("Max results to return")
101122
101482
  }, async (args) => {
101123
101483
  const denied = await this.validateSyntheticTool(toolDef, args);
101124
101484
  if (denied)
@@ -101132,10 +101492,10 @@ var McpServerAdapter = class _McpServerAdapter {
101132
101492
  const handleAgentTask2 = this.deps.handleAgentTask;
101133
101493
  const toolDef = _McpServerAdapter.syntheticToolDef("motebit_task", "Submit an autonomous task \u2014 returns a signed ExecutionReceipt", RiskLevel.R3_EXECUTE);
101134
101494
  server.tool("motebit_task", "Submit an autonomous task \u2014 returns a signed ExecutionReceipt", {
101135
- prompt: z40.string().describe("The task prompt for the agent to execute"),
101136
- delegation_token: z40.string().optional().describe("Signed delegation token (JSON) authorizing this task within a specific scope"),
101137
- required_capabilities: z40.unknown().optional().describe('Array of capability names required for this task (e.g. ["web_search"])'),
101138
- relay_task_id: z40.string().optional().describe("Relay-assigned task ID for economic binding \u2014 included in the signed receipt")
101495
+ prompt: z41.string().describe("The task prompt for the agent to execute"),
101496
+ delegation_token: z41.string().optional().describe("Signed delegation token (JSON) authorizing this task within a specific scope"),
101497
+ required_capabilities: z41.unknown().optional().describe('Array of capability names required for this task (e.g. ["web_search"])'),
101498
+ relay_task_id: z41.string().optional().describe("Relay-assigned task ID for economic binding \u2014 included in the signed receipt")
101139
101499
  }, async (args) => {
101140
101500
  const denied = await this.validateSyntheticTool(toolDef, args);
101141
101501
  if (denied)
@@ -101376,7 +101736,7 @@ var McpServerAdapter = class _McpServerAdapter {
101376
101736
  }
101377
101737
  // --- Prompt Registration ---
101378
101738
  registerPromptsOn(server) {
101379
- server.prompt("chat", "Send a message to this motebit", { message: z40.string() }, ({ message: message2 }) => ({
101739
+ server.prompt("chat", "Send a message to this motebit", { message: z41.string() }, ({ message: message2 }) => ({
101380
101740
  messages: [
101381
101741
  {
101382
101742
  role: "user",
@@ -101387,7 +101747,7 @@ var McpServerAdapter = class _McpServerAdapter {
101387
101747
  }
101388
101748
  ]
101389
101749
  }));
101390
- server.prompt("recall", "Search semantic memory", { query: z40.string(), limit: z40.string().optional() }, ({ query, limit }) => ({
101750
+ server.prompt("recall", "Search semantic memory", { query: z41.string(), limit: z41.string().optional() }, ({ query, limit }) => ({
101391
101751
  messages: [
101392
101752
  {
101393
101753
  role: "user",
@@ -105785,53 +106145,53 @@ import { TextDocument } from "vscode-languageserver-textdocument";
105785
106145
  // src/yaml-config.ts
105786
106146
  init_esm_shims();
105787
106147
  import * as crypto2 from "crypto";
105788
- import { z as z41 } from "zod";
105789
- var ProviderSchema = z41.object({
105790
- mode: z41.enum(["byok", "paid", "sovereign"]).optional().describe(
106148
+ import { z as z42 } from "zod";
106149
+ var ProviderSchema = z42.object({
106150
+ mode: z42.enum(["byok", "paid", "sovereign"]).optional().describe(
105791
106151
  "Provider mode. `byok` = bring-your-own API key (env var). `paid` = motebit cloud. `sovereign` = local on-device model (no external calls)."
105792
106152
  ),
105793
- wireProtocol: z41.enum(["anthropic", "openai"]).optional().describe(
106153
+ wireProtocol: z42.enum(["anthropic", "openai"]).optional().describe(
105794
106154
  "Wire protocol the endpoint speaks. `anthropic` for Claude, `openai` for OpenAI-compatible endpoints (OpenAI, Ollama, LM Studio, vLLM)."
105795
106155
  ),
105796
- model: z41.string().optional().describe("Model identifier, e.g. `claude-sonnet-4-6`, `gpt-5.4-mini`, `llama3.2`."),
105797
- baseUrl: z41.string().url().optional().describe(
106156
+ model: z42.string().optional().describe("Model identifier, e.g. `claude-sonnet-4-6`, `gpt-5.4-mini`, `llama3.2`."),
106157
+ baseUrl: z42.string().url().optional().describe(
105798
106158
  "Override the API base URL. Used for local inference servers (`http://localhost:11434/v1` for Ollama) or routing through a proxy."
105799
106159
  ),
105800
- maxTokens: z41.number().int().positive().optional().describe("Upper bound on response length (model output tokens).")
106160
+ maxTokens: z42.number().int().positive().optional().describe("Upper bound on response length (model output tokens).")
105801
106161
  }).strict().describe(
105802
106162
  "AI provider configuration. API keys are NEVER declared here \u2014 they're read from environment variables or the OS keyring."
105803
106163
  );
105804
- var GovernanceSchema = z41.object({
105805
- approvalPreset: z41.enum(["cautious", "balanced", "autonomous"]).describe(
106164
+ var GovernanceSchema = z42.object({
106165
+ approvalPreset: z42.enum(["cautious", "balanced", "autonomous"]).describe(
105806
106166
  "Default gate for tool calls. `cautious` = approve every sensitive call. `balanced` = approve writes, auto-approve reads. `autonomous` = auto-approve most calls."
105807
106167
  ),
105808
- persistenceThreshold: z41.number().min(0).max(1).describe(
106168
+ persistenceThreshold: z42.number().min(0).max(1).describe(
105809
106169
  "Memory-formation threshold [0, 1]. Higher = fewer memories formed; only strong signals persist. Typical: 0.6."
105810
106170
  ),
105811
- rejectSecrets: z41.boolean().describe(
106171
+ rejectSecrets: z42.boolean().describe(
105812
106172
  "When true, the privacy layer blocks any tool call or outbound message whose content is classified as `secret`. Fail-closed: error on classifier failure."
105813
106173
  ),
105814
- maxCallsPerTurn: z41.number().int().positive().describe(
106174
+ maxCallsPerTurn: z42.number().int().positive().describe(
105815
106175
  "Per-turn tool-call ceiling. Bounds runaway loops and protects the policy gate from exhaustion attacks."
105816
106176
  ),
105817
- maxMemoriesPerTurn: z41.number().int().positive().describe(
106177
+ maxMemoriesPerTurn: z42.number().int().positive().describe(
105818
106178
  "Per-turn memory-formation ceiling. Prevents a single turn from flooding the memory graph."
105819
106179
  )
105820
106180
  }).strict().describe("Governance at the boundary \u2014 surface-tension constraints that apply to every turn.");
105821
- var McpServerSchema = z41.object({
105822
- name: z41.string().min(1).describe("Local name for the MCP server. Must be unique."),
105823
- transport: z41.enum(["stdio", "http"]).describe("Transport. `stdio` spawns a child process; `http` connects to a URL."),
105824
- command: z41.string().optional().describe("Executable to spawn when `transport: stdio`. E.g. `npx`, `node`, `python`."),
105825
- args: z41.array(z41.string()).optional().describe("Argument vector passed to `command` when `transport: stdio`."),
105826
- url: z41.string().url().optional().describe("Endpoint URL when `transport: http`. Must be a full URL including scheme."),
105827
- env: z41.record(z41.string(), z41.string()).optional().describe("Environment variables set for the child process (stdio transport)."),
105828
- trusted: z41.boolean().optional().describe(
106181
+ var McpServerSchema = z42.object({
106182
+ name: z42.string().min(1).describe("Local name for the MCP server. Must be unique."),
106183
+ transport: z42.enum(["stdio", "http"]).describe("Transport. `stdio` spawns a child process; `http` connects to a URL."),
106184
+ command: z42.string().optional().describe("Executable to spawn when `transport: stdio`. E.g. `npx`, `node`, `python`."),
106185
+ args: z42.array(z42.string()).optional().describe("Argument vector passed to `command` when `transport: stdio`."),
106186
+ url: z42.string().url().optional().describe("Endpoint URL when `transport: http`. Must be a full URL including scheme."),
106187
+ env: z42.record(z42.string(), z42.string()).optional().describe("Environment variables set for the child process (stdio transport)."),
106188
+ trusted: z42.boolean().optional().describe(
105829
106189
  "Auto-approve tool calls from this server. Equivalent to promoting the server into `mcp_trusted_servers`. Off by default."
105830
106190
  ),
105831
- motebit: z41.boolean().optional().describe(
106191
+ motebit: z42.boolean().optional().describe(
105832
106192
  "This server is another motebit instance \u2014 enables motebit-to-motebit transport with caller identity injected into every call."
105833
106193
  ),
105834
- motebitType: z41.enum(["personal", "service", "collaborative"]).optional().describe(
106194
+ motebitType: z42.enum(["personal", "service", "collaborative"]).optional().describe(
105835
106195
  "Semantic role of the peer motebit. `personal` = another device of yours. `service` = paid worker. `collaborative` = peer agent."
105836
106196
  )
105837
106197
  }).strict().refine((s3) => s3.transport === "stdio" ? s3.command != null : s3.url != null, {
@@ -105839,65 +106199,65 @@ var McpServerSchema = z41.object({
105839
106199
  }).describe(
105840
106200
  "MCP server \u2014 a tool source. stdio transports spawn a subprocess; http transports dial a remote endpoint."
105841
106201
  );
105842
- var IntervalString = z41.string().min(1).transform((raw, ctx) => {
106202
+ var IntervalString = z42.string().min(1).transform((raw, ctx) => {
105843
106203
  try {
105844
106204
  return parseInterval(raw);
105845
106205
  } catch (err2) {
105846
106206
  ctx.addIssue({
105847
- code: z41.ZodIssueCode.custom,
106207
+ code: z42.ZodIssueCode.custom,
105848
106208
  message: err2 instanceof Error ? err2.message : String(err2)
105849
106209
  });
105850
- return z41.NEVER;
106210
+ return z42.NEVER;
105851
106211
  }
105852
106212
  }).describe("Interval string: `<n>m` minutes, `<n>h` hours, `<n>d` days. E.g. `30m`, `1h`, `7d`.");
105853
- var RoutineSchema = z41.object({
105854
- id: z41.string().min(1).max(64).regex(/^[a-z0-9][a-z0-9_-]*$/, {
106213
+ var RoutineSchema = z42.object({
106214
+ id: z42.string().min(1).max(64).regex(/^[a-z0-9][a-z0-9_-]*$/, {
105855
106215
  message: "routine id must be lowercase alphanumeric with _ or - (e.g. 'daily-digest')"
105856
106216
  }).describe(
105857
106217
  "Stable identifier for the routine. Used as the upsert key \u2014 changing the id renames the routine (old one is pruned, new one added). Lowercase alphanumeric with `-` or `_`."
105858
106218
  ),
105859
- prompt: z41.string().min(1).describe(
106219
+ prompt: z42.string().min(1).describe(
105860
106220
  "Natural-language prompt the agent runs on each tick. Content changes update the same goal row (preserving `created_at`)."
105861
106221
  ),
105862
106222
  every: IntervalString.describe(
105863
106223
  "Run cadence. Interval string (`<n>m`, `<n>h`, `<n>d`). E.g. `1h` = hourly."
105864
106224
  ),
105865
- mode: z41.enum(["recurring", "once"]).default("recurring").describe(
106225
+ mode: z42.enum(["recurring", "once"]).default("recurring").describe(
105866
106226
  "`recurring` runs every `every` tick forever. `once` runs a single time then marks the goal completed."
105867
106227
  ),
105868
106228
  wall_clock: IntervalString.optional().describe(
105869
106229
  "Hard wall-clock timeout per run. Kills the turn if it exceeds this. Default: 10m."
105870
106230
  ),
105871
- project: z41.string().min(1).optional().describe("Project identifier \u2014 groups goals that share context (shared memory scope)."),
105872
- enabled: z41.boolean().default(true).describe(
106231
+ project: z42.string().min(1).optional().describe("Project identifier \u2014 groups goals that share context (shared memory scope)."),
106232
+ enabled: z42.boolean().default(true).describe(
105873
106233
  "Set false to pause the routine without deleting it. Preserves state and history; resumable with no data loss."
105874
106234
  )
105875
106235
  }).strict().describe(
105876
106236
  "A scheduled routine \u2014 compiles to exactly one Goal row. Changing fields other than `id` updates the same row in place."
105877
106237
  );
105878
- var MotebitYamlObjectSchema = z41.object({
106238
+ var MotebitYamlObjectSchema = z42.object({
105879
106239
  // Pinning the version lets us rev the schema later without silently
105880
106240
  // interpreting v2 yaml as v1. Mismatch → the loader prints a targeted
105881
106241
  // error telling the user which CLI version expects which yaml version.
105882
- version: z41.literal(1).describe(
106242
+ version: z42.literal(1).describe(
105883
106243
  "Schema version. Currently `1`. Pinning lets future CLI versions print a targeted error on mismatch instead of silently misinterpreting the document."
105884
106244
  ),
105885
- name: z41.string().optional().describe(
106245
+ name: z42.string().optional().describe(
105886
106246
  "Display name for this motebit. Surfaces in the REPL banner and delegation listings."
105887
106247
  ),
105888
- personality_notes: z41.string().optional().describe(
106248
+ personality_notes: z42.string().optional().describe(
105889
106249
  "Free-form personality guidance. Appended to the system prompt on every turn. Keep short \u2014 every token here costs on every call."
105890
106250
  ),
105891
- temperature: z41.number().min(0).max(2).optional().describe(
106251
+ temperature: z42.number().min(0).max(2).optional().describe(
105892
106252
  "Sampling temperature for the default provider [0, 2]. Unset = model default. Only applied when explicitly set."
105893
106253
  ),
105894
- max_tokens: z41.number().int().positive().optional().describe("Default max output tokens per response. Overridden by `--max-tokens` at the CLI."),
106254
+ max_tokens: z42.number().int().positive().optional().describe("Default max output tokens per response. Overridden by `--max-tokens` at the CLI."),
105895
106255
  provider: ProviderSchema.optional(),
105896
106256
  governance: GovernanceSchema.optional(),
105897
- mcp_servers: z41.array(McpServerSchema).optional().describe(
106257
+ mcp_servers: z42.array(McpServerSchema).optional().describe(
105898
106258
  "MCP tool servers to connect on start. Each entry declares transport, endpoint, and (optionally) trust status."
105899
106259
  ),
105900
- routines: z41.array(RoutineSchema).optional().describe(
106260
+ routines: z42.array(RoutineSchema).optional().describe(
105901
106261
  "Scheduled routines. Each compiles to exactly one Goal row; `id` is the upsert key. Re-running `motebit up` on unchanged yaml is a true no-op."
105902
106262
  )
105903
106263
  });
@@ -105909,7 +106269,7 @@ var MotebitYamlSchema = MotebitYamlObjectSchema.strict().superRefine((data, ctx)
105909
106269
  const prev = seen.get(id);
105910
106270
  if (prev !== void 0) {
105911
106271
  ctx.addIssue({
105912
- code: z41.ZodIssueCode.custom,
106272
+ code: z42.ZodIssueCode.custom,
105913
106273
  path: ["routines", i3, "id"],
105914
106274
  message: `duplicate routine id "${id}" (also used at routines[${prev}])`
105915
106275
  });
@@ -106081,12 +106441,12 @@ function walk(node, offset, path19) {
106081
106441
 
106082
106442
  // src/lsp/schema-walker.ts
106083
106443
  init_esm_shims();
106084
- import { z as z42 } from "zod";
106444
+ import { z as z43 } from "zod";
106085
106445
  function unwrapOne(schema) {
106086
- if (schema instanceof z42.ZodOptional) return schema.unwrap();
106087
- if (schema instanceof z42.ZodDefault) return schema.removeDefault();
106088
- if (schema instanceof z42.ZodEffects) return schema.innerType();
106089
- if (schema instanceof z42.ZodNullable) return schema.unwrap();
106446
+ if (schema instanceof z43.ZodOptional) return schema.unwrap();
106447
+ if (schema instanceof z43.ZodDefault) return schema.removeDefault();
106448
+ if (schema instanceof z43.ZodEffects) return schema.innerType();
106449
+ if (schema instanceof z43.ZodNullable) return schema.unwrap();
106090
106450
  return null;
106091
106451
  }
106092
106452
  function unwrapAll(schema) {
@@ -106111,14 +106471,14 @@ function resolvePath(schema, path19) {
106111
106471
  let cur = schema;
106112
106472
  for (const seg of path19) {
106113
106473
  const inner = unwrapAll(cur);
106114
- if (inner instanceof z42.ZodObject) {
106474
+ if (inner instanceof z43.ZodObject) {
106115
106475
  const shape = inner.shape;
106116
106476
  const next = shape[String(seg)];
106117
106477
  if (!next) return null;
106118
106478
  cur = next;
106119
106479
  continue;
106120
106480
  }
106121
- if (inner instanceof z42.ZodArray) {
106481
+ if (inner instanceof z43.ZodArray) {
106122
106482
  cur = inner.element;
106123
106483
  continue;
106124
106484
  }
@@ -106130,12 +106490,12 @@ function objectKeys(schema, path19) {
106130
106490
  const target = resolvePath(schema, path19);
106131
106491
  if (target == null) return [];
106132
106492
  const inner = unwrapAll(target);
106133
- if (inner instanceof z42.ZodObject) {
106493
+ if (inner instanceof z43.ZodObject) {
106134
106494
  return Object.keys(inner.shape);
106135
106495
  }
106136
- if (inner instanceof z42.ZodArray) {
106496
+ if (inner instanceof z43.ZodArray) {
106137
106497
  const elem = unwrapAll(inner.element);
106138
- if (elem instanceof z42.ZodObject) {
106498
+ if (elem instanceof z43.ZodObject) {
106139
106499
  return Object.keys(elem.shape);
106140
106500
  }
106141
106501
  }
@@ -106145,13 +106505,13 @@ function enumValues(schema, path19) {
106145
106505
  const target = resolvePath(schema, path19);
106146
106506
  if (target == null) return null;
106147
106507
  const inner = unwrapAll(target);
106148
- if (inner instanceof z42.ZodEnum) {
106508
+ if (inner instanceof z43.ZodEnum) {
106149
106509
  return [...inner.options];
106150
106510
  }
106151
- if (inner instanceof z42.ZodLiteral) {
106511
+ if (inner instanceof z43.ZodLiteral) {
106152
106512
  return [String(inner.value)];
106153
106513
  }
106154
- if (inner instanceof z42.ZodBoolean) {
106514
+ if (inner instanceof z43.ZodBoolean) {
106155
106515
  return ["true", "false"];
106156
106516
  }
106157
106517
  return null;
@@ -118299,10 +118659,10 @@ init_esm_shims();
118299
118659
 
118300
118660
  // src/yaml-json-schema.ts
118301
118661
  init_esm_shims();
118302
- import { zodToJsonSchema as zodToJsonSchema39 } from "zod-to-json-schema";
118662
+ import { zodToJsonSchema as zodToJsonSchema40 } from "zod-to-json-schema";
118303
118663
  var MOTEBIT_YAML_SCHEMA_ID = "https://raw.githubusercontent.com/motebit/motebit/main/apps/cli/schema/motebit-yaml-v1.json";
118304
118664
  function buildYamlJsonSchema() {
118305
- const schema = zodToJsonSchema39(MotebitYamlObjectSchema, {
118665
+ const schema = zodToJsonSchema40(MotebitYamlObjectSchema, {
118306
118666
  name: "MotebitYaml",
118307
118667
  $refStrategy: "none",
118308
118668
  target: "jsonSchema7"