nolo-cli 0.81.0-alpha.1 → 0.81.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 (161) hide show
  1. package/README.md +2 -2
  2. package/{_executeModel-L4LCNFID.js → _executeModel-JIG7MRXQ.js} +48 -48
  3. package/{action-D22U6CTH.js → action-YVYQEAAV.js} +11 -11
  4. package/{addContentAction-XAPUTGL4.js → addContentAction-O7R66HEX.js} +9 -9
  5. package/{addDialogAgentAction-M7VLLBZM.js → addDialogAgentAction-74OA7KYP.js} +8 -8
  6. package/{agentDeleteCommand-D2WHTH7S.js → agentDeleteCommand-THAZ5GQS.js} +31 -29
  7. package/{agentEmailCommands-IHSX56GO.js → agentEmailCommands-A7T7AJA4.js} +67 -63
  8. package/{agentGrantCommands-R3VQEZJR.js → agentGrantCommands-M3XFO6EN.js} +2 -2
  9. package/{agentListCommands-R2DGZMFP.js → agentListCommands-BRZFEJQM.js} +40 -32
  10. package/{agentMachineCommands-UYDID3HQ.js → agentMachineCommands-DM4N5PK3.js} +31 -29
  11. package/{agentProviderCommands-65ZC2WB4.js → agentProviderCommands-GNPTL5XR.js} +87 -0
  12. package/{agentPullCommand-N7L2CT7L.js → agentPullCommand-O5MPVJ5E.js} +3 -3
  13. package/agentRecordCommands-TTAEMNHB.js +128 -0
  14. package/{agentRunCommand-5PJF27JP.js → agentRunCommand-JVSTGVG2.js} +65 -61
  15. package/{agentRunControl-T44MESII.js → agentRunControl-WCTKX5VL.js} +2 -2
  16. package/{agentRuntimeLocal-VD4O2QFQ.js → agentRuntimeLocal-73CVIWBB.js} +27 -25
  17. package/{agentSlice-43ORUHTC.js → agentSlice-6X4JL2E3.js} +10 -10
  18. package/{appDeleteCommands-DXJA7XOZ.js → appDeleteCommands-S7CK4OYL.js} +31 -29
  19. package/{appDeployCommands-JL6XJZJE.js → appDeployCommands-U6TMS5GO.js} +31 -29
  20. package/{appDeployStatusCommands-MS2D2R6R.js → appDeployStatusCommands-DTNQJ3LJ.js} +31 -29
  21. package/{appGetCommands-BV2RDCEV.js → appGetCommands-3SHZEQD5.js} +31 -29
  22. package/{appListCommands-E2AM636N.js → appListCommands-E2ZMIUB6.js} +31 -29
  23. package/{authCommand-EVGFLAHO.js → authCommand-F4EFRRX6.js} +164 -24
  24. package/{authCommands-ILTBI6JV.js → authCommands-RGOGCPP6.js} +4 -5
  25. package/builtinSkillRegistry-FUAVTRVZ.js +33 -0
  26. package/{chatQueueReduxAdapter-F3IRDXDQ.js → chatQueueReduxAdapter-LAQEZQKE.js} +24 -24
  27. package/{chromeCommands-VOIRNJBL.js → chromeCommands-FZYAU75D.js} +1 -1
  28. package/{chromeOpsCommands-M7DPCX2T.js → chromeOpsCommands-62P2Q2YB.js} +31 -1
  29. package/{chunk-C3FZR5EC.js → chunk-2F7RJC6L.js} +1 -1
  30. package/{chunk-HQUORJTM.js → chunk-3BMYXEUW.js} +1 -1
  31. package/{chunk-3QPYFHAH.js → chunk-3DII57IT.js} +1 -1
  32. package/{chunk-KIS76A2P.js → chunk-3IIEFNGY.js} +38 -4
  33. package/{chunk-NTW5GWDM.js → chunk-3VNWWVKB.js} +2 -0
  34. package/{chunk-JQBONKAV.js → chunk-3WD6RUUJ.js} +11 -173
  35. package/{chunk-DWUCB2A3.js → chunk-42V6BK2E.js} +1 -1
  36. package/{chunk-GBPZKFYK.js → chunk-53HEEOTT.js} +4 -4
  37. package/{chunk-GEH7MMBB.js → chunk-54ADB4W7.js} +1 -1
  38. package/{chunk-5XTOKQLW.js → chunk-5UTFL4QJ.js} +6 -2
  39. package/chunk-5ZUL4CUO.js +10 -0
  40. package/{chunk-E6RGHPDR.js → chunk-6D6VBVEW.js} +4 -6
  41. package/{chunk-QNWHWBB7.js → chunk-6FVRQBRR.js} +52 -30
  42. package/{chunk-CMH2SYHX.js → chunk-6OZ36FXI.js} +2 -2
  43. package/{chunk-NRALD3CC.js → chunk-76WEAXJB.js} +49 -10
  44. package/{chunk-DFJFH53D.js → chunk-7OLPQSMQ.js} +6 -6
  45. package/{chunk-BYEJ7K2Z.js → chunk-7S4YWN7P.js} +1 -1
  46. package/{chunk-SREASRV5.js → chunk-ABQYVJBJ.js} +1 -1
  47. package/chunk-ACTMNVHM.js +93 -0
  48. package/{chunk-XWNRAIUL.js → chunk-AFUORTY4.js} +6 -16
  49. package/{chunk-WL2RKIBF.js → chunk-BLJWCTRL.js} +1 -1
  50. package/chunk-BNGW5ASC.js +344 -0
  51. package/{chunk-SZLVDREM.js → chunk-BP4XNZRM.js} +3 -3
  52. package/{chunk-2KDR4CWE.js → chunk-BYMV6QZG.js} +24 -1
  53. package/{chunk-MYU3MJCF.js → chunk-DHDMC6FO.js} +175 -7
  54. package/{chunk-4YCRJUQ2.js → chunk-ESWUWEFS.js} +10 -10
  55. package/{chunk-EXMHJN7C.js → chunk-EYAQT56M.js} +4 -3
  56. package/{chunk-CJCJF5XB.js → chunk-FDTR4QJ6.js} +4 -2
  57. package/{chunk-PYXL2CJL.js → chunk-GPCZ7UXG.js} +1 -1
  58. package/{chunk-K7AG465Q.js → chunk-GQBOR3G6.js} +4 -2
  59. package/{chunk-YFADVSZE.js → chunk-H62HCIUP.js} +6 -6
  60. package/{chunk-PZM3EENV.js → chunk-HJUYAD4A.js} +1 -1
  61. package/{chunk-3JQ2NRYU.js → chunk-HVURBGF3.js} +4 -4
  62. package/{chunk-DAIOZ3ZO.js → chunk-HWIZU4OL.js} +13 -15
  63. package/{chunk-ZVN6I33J.js → chunk-IIVGDG4I.js} +6 -5
  64. package/{chunk-UDQWGU7F.js → chunk-J4MOO56S.js} +1 -1
  65. package/{chunk-DSRXPQWA.js → chunk-JAXOVNM4.js} +43 -43
  66. package/{chunk-QQ7SX52C.js → chunk-JCIHVIVG.js} +15 -15
  67. package/{chunk-KC5FAHVS.js → chunk-JEDZAO7L.js} +1 -1
  68. package/{chunk-6XIE5ZGI.js → chunk-JPGCXHNM.js} +1 -1
  69. package/chunk-JRQFUXY7.js +1625 -0
  70. package/{chunk-J4R5XRX5.js → chunk-K4YGZD3P.js} +419 -72
  71. package/chunk-KQ4ONNQD.js +677 -0
  72. package/{chunk-RXX4GDIH.js → chunk-LS2ZANRJ.js} +1 -1
  73. package/{chunk-ODWEZBU6.js → chunk-LXF6XQDT.js} +1219 -57
  74. package/{chunk-CPSZJBLK.js → chunk-LZIWMYX4.js} +105 -26
  75. package/{chunk-BJIRLHJR.js → chunk-M2EJHDJP.js} +4 -0
  76. package/{chunk-EVBFYPDC.js → chunk-MC4XLIJ7.js} +6 -2
  77. package/{chunk-QC5LGHYP.js → chunk-OF7AQZUG.js} +10 -5
  78. package/{chunk-UJ63UXGE.js → chunk-OIVSQH2O.js} +1006 -801
  79. package/{chunk-AETZ7AD6.js → chunk-Q554LLSI.js} +1 -1
  80. package/chunk-Q5FJJ6XI.js +103 -0
  81. package/{chunk-AJHEFRGJ.js → chunk-Q67DOFOO.js} +214 -5
  82. package/{chunk-UZ6XXCVR.js → chunk-QDSINZM3.js} +15 -2
  83. package/{chunk-D6XYLSOS.js → chunk-QIAVMDHY.js} +1 -1
  84. package/{chunk-IHTVDCWH.js → chunk-R2B3MIZA.js} +3 -3
  85. package/{chunk-YWG6EMH3.js → chunk-RG6JBBX5.js} +10 -6
  86. package/{chunk-QCZX4FTW.js → chunk-SH43IESU.js} +173 -15
  87. package/{chunk-FNGAF7C4.js → chunk-SNPMM7H3.js} +137 -12
  88. package/{chunk-XKNBWXDH.js → chunk-SQQVLHMH.js} +7 -7
  89. package/{chunk-SPAQ4PVV.js → chunk-SV5IJK6K.js} +1 -1
  90. package/{chunk-KVDUCO4Q.js → chunk-TDRTS7QW.js} +16 -12
  91. package/{chunk-BJCWNHVU.js → chunk-TOP2VXOR.js} +2 -2
  92. package/{chunk-QQBO3LQW.js → chunk-TZJJ77KQ.js} +155 -795
  93. package/{chunk-4EJ5QYB5.js → chunk-UKZDAFYT.js} +1 -1
  94. package/{chunk-PGSKWZCB.js → chunk-UZGQNTVW.js} +1 -1
  95. package/{chunk-ZZCJUXUI.js → chunk-V4MJDUSR.js} +2 -2
  96. package/{chunk-JYYZCK2Z.js → chunk-V7E4PXQD.js} +1 -1
  97. package/{chunk-OZX2IPKM.js → chunk-VLTIYV3X.js} +1 -1
  98. package/{chunk-NHRQCXIQ.js → chunk-VMFTFOWF.js} +13 -3
  99. package/{chunk-E36HZARC.js → chunk-WADCY6G6.js} +3 -3
  100. package/{chunk-HH65VA5U.js → chunk-WGR3J4Q6.js} +101 -4
  101. package/{chunk-5J7W2VWW.js → chunk-WV42OMV7.js} +6 -265
  102. package/{chunk-7QHSEMMD.js → chunk-Y5HW6GM2.js} +3 -3
  103. package/{chunk-DUJWWUGV.js → chunk-YQTQQX2H.js} +1 -1
  104. package/{chunk-QPJBFU7R.js → chunk-YVIV7WT4.js} +752 -80
  105. package/{chunk-BOYUESO7.js → chunk-Z77CRGTW.js} +1 -1
  106. package/{chunk-KSHYBTYH.js → chunk-ZWUOR654.js} +932 -299
  107. package/{contentThunks-FSQPOFYG.js → contentThunks-ATLWNC2D.js} +25 -25
  108. package/{cooldownCommands-BSCH2W7P.js → cooldownCommands-REAWYVTY.js} +2 -2
  109. package/{createAgentAutomationAction-VCHDRJ6X.js → createAgentAutomationAction-QYYWTVUR.js} +25 -25
  110. package/{createDialogAction-KZM5IE4P.js → createDialogAction-7I5VGWCR.js} +28 -28
  111. package/{createPageAction-IGMXJOY3.js → createPageAction-WNURYCWU.js} +26 -26
  112. package/{dbSlice-GKGGFNOB.js → dbSlice-XVWBAGYN.js} +8 -8
  113. package/{deleteFile-LWSR674W.js → deleteFile-YG6QMJLU.js} +3 -3
  114. package/{dialogCommands-KJS57EDF.js → dialogCommands-RILHDRQ5.js} +35 -31
  115. package/{dialogSlice-YBTC3GAW.js → dialogSlice-W5BYELVR.js} +24 -24
  116. package/{docCreateCommands-MRGXJTB4.js → docCreateCommands-GSTPU7SG.js} +32 -30
  117. package/{docDeleteCommands-YCI75CBU.js → docDeleteCommands-2FC3LSUT.js} +33 -31
  118. package/{docReadCommands-JN3VHTQY.js → docReadCommands-27POBA34.js} +32 -30
  119. package/{docStore-SDPT23I6.js → docStore-7LAHBFP2.js} +9 -9
  120. package/{docUpdateCommands-7KBOENX7.js → docUpdateCommands-U4II6VCO.js} +32 -30
  121. package/{fetchMessages-DRABNDPZ.js → fetchMessages-EIU7UFFK.js} +3 -4
  122. package/{getPricing-HRMSOF3E.js → getPricing-LUSEABA6.js} +4 -4
  123. package/{handleSendMessageAction-356IDG72.js → handleSendMessageAction-SKMJMVRU.js} +24 -24
  124. package/index.js +102 -85
  125. package/{localDialogRead-PUQKFI73.js → localDialogRead-BTFJ4V2I.js} +2 -2
  126. package/{localRuntimeDb-P37ZTX55.js → localRuntimeDb-SYQGUF4U.js} +1 -1
  127. package/{machineCommands-FYIRYMDE.js → machineCommands-S2RNYKVJ.js} +64 -60
  128. package/{machineWsRunDispatch-J2FEYI4T.js → machineWsRunDispatch-JC44LBLP.js} +62 -58
  129. package/{memberThunks-KATHH3F4.js → memberThunks-QGFLFVCI.js} +9 -9
  130. package/{models-GS72DVJS.js → models-T3SG6MJ5.js} +2 -2
  131. package/{offlineMarxistsAgentCommand-GEH6SNNA.js → offlineMarxistsAgentCommand-HGXZV4XJ.js} +1 -1
  132. package/package.json +1 -1
  133. package/providerPresetApply-FG6NZ57W.js +214 -0
  134. package/providerRegistry-757OWH3O.js +31 -0
  135. package/{read-LC6HVYBN.js → read-COE3ZYR6.js} +5 -4
  136. package/{readDocTool-N3ERJHHF.js → readDocTool-5USN4A6V.js} +1 -1
  137. package/{readlineWorkspace-OWBGR7QO.js → readlineWorkspace-VZSBXUH4.js} +188 -109
  138. package/{removeDialogAgentAction-F5GPTALR.js → removeDialogAgentAction-IX3MN2ZO.js} +11 -11
  139. package/{runAgentClientLoop-DKUUFUKT.js → runAgentClientLoop-ZYENU7GH.js} +47 -47
  140. package/{runtimeDoctorCommands-CROTMULY.js → runtimeDoctorCommands-X6WDBEQX.js} +2 -2
  141. package/{setDialogExtraReferencesAction-AY4ZCF3A.js → setDialogExtraReferencesAction-X4HCPNZL.js} +9 -9
  142. package/{setPrimaryDialogAgentAction-HPMG7V3R.js → setPrimaryDialogAgentAction-4GMIQLOD.js} +11 -11
  143. package/{settingSlice-OEJA4NQO.js → settingSlice-ZQZVUPKK.js} +10 -10
  144. package/{spaceCommands-SSLCOSBH.js → spaceCommands-QB3NNEMN.js} +30 -28
  145. package/{streamAgentChatTurn-FHZZCANP.js → streamAgentChatTurn-43GPPQSN.js} +59 -58
  146. package/{switchDialogAgentAction-HMDZTZ4I.js → switchDialogAgentAction-N52LRPA3.js} +8 -8
  147. package/{tableCommands-SUNTHAYX.js → tableCommands-O6NWHFKV.js} +1 -1
  148. package/{toolApiClient-VGYUB4P5.js → toolApiClient-QVJ6HDNN.js} +2 -2
  149. package/{tools-QZJX3BIC.js → tools-SX6Y4STZ.js} +43 -43
  150. package/tuiSummaryLlmCaller-T2SHYMDZ.js +127 -0
  151. package/{updateCommands-Y363MC3L.js → updateCommands-2M74UL7P.js} +2 -2
  152. package/{updateDialogTitleAction-JJPNGTAP.js → updateDialogTitleAction-VAKA4ZNY.js} +45 -28
  153. package/agentRecordCommands-OFYTWZAA.js +0 -124
  154. package/chunk-3IT2PFHL.js +0 -611
  155. package/chunk-I42VC5KR.js +0 -15
  156. package/chunk-NG4UT4K4.js +0 -79
  157. package/codingSkills-E6KSDNSJ.js +0 -48
  158. package/tuiSummaryLlmCaller-3Z24VUWM.js +0 -116
  159. package/{chunk-3RAG2NAD.js → chunk-UKWGR5SS.js} +3 -3
  160. package/{db-VQSAOWAO.js → db-WK5MDZVN.js} +1 -1
  161. package/{localRuntimeAuthority-R5UBODT3.js → localRuntimeAuthority-6IR6BBXE.js} +3 -3
@@ -9,7 +9,7 @@ import {
9
9
  resolveRawAgentInput,
10
10
  resolveServerUrl,
11
11
  writeUsage
12
- } from "./chunk-JYYZCK2Z.js";
12
+ } from "./chunk-V7E4PXQD.js";
13
13
  import {
14
14
  agentRunCardLabels,
15
15
  createCliLocalRuntimeAdapter,
@@ -27,7 +27,7 @@ import {
27
27
  resolveLocalUserId,
28
28
  t,
29
29
  toolLabel
30
- } from "./chunk-QPJBFU7R.js";
30
+ } from "./chunk-YVIV7WT4.js";
31
31
  import {
32
32
  createRunActivityTracker,
33
33
  popSingleQueueMessage,
@@ -35,22 +35,23 @@ import {
35
35
  resolveRunQueuePath,
36
36
  settleRunTerminalAuthoritatively,
37
37
  spawnLocalBackgroundRun
38
- } from "./chunk-HH65VA5U.js";
38
+ } from "./chunk-WGR3J4Q6.js";
39
39
  import {
40
+ clearCredentialAvailability,
40
41
  readCredentialEntry,
41
42
  recordCredentialProbe,
42
43
  resolveCredentialKeyWithFallback
43
- } from "./chunk-DWUCB2A3.js";
44
+ } from "./chunk-42V6BK2E.js";
44
45
  import {
45
46
  getReadableCliDb
46
- } from "./chunk-RXX4GDIH.js";
47
+ } from "./chunk-LS2ZANRJ.js";
47
48
  import {
48
49
  readDbRecord,
49
50
  resolveAgentRecordFromHybridStore
50
- } from "./chunk-NRALD3CC.js";
51
+ } from "./chunk-76WEAXJB.js";
51
52
  import {
52
53
  isLocalCliAgentKey
53
- } from "./chunk-SPAQ4PVV.js";
54
+ } from "./chunk-SV5IJK6K.js";
54
55
  import {
55
56
  CliProviderQuotaError
56
57
  } from "./chunk-MP64VFGD.js";
@@ -63,10 +64,10 @@ import {
63
64
  } from "./chunk-LTRXGFMS.js";
64
65
  import {
65
66
  formatAgentListCard
66
- } from "./chunk-QQBO3LQW.js";
67
+ } from "./chunk-TZJJ77KQ.js";
67
68
  import {
68
69
  isTransientFetchError
69
- } from "./chunk-5XTOKQLW.js";
70
+ } from "./chunk-5UTFL4QJ.js";
70
71
  import {
71
72
  isGatewayHttpStatus
72
73
  } from "./chunk-NF64D32W.js";
@@ -78,17 +79,17 @@ import {
78
79
  formatStatusRunCard,
79
80
  formatStopRunCard,
80
81
  isAgentRunTerminalStatus
81
- } from "./chunk-NTW5GWDM.js";
82
+ } from "./chunk-3VNWWVKB.js";
82
83
  import {
83
84
  buildMemorySubjectsForAgent,
84
85
  chooseMemoryOwners,
85
86
  loadMemoryCandidatesFromDb,
86
87
  resolveAgentMemoryPolicy
87
- } from "./chunk-JQBONKAV.js";
88
+ } from "./chunk-3WD6RUUJ.js";
88
89
  import {
89
90
  API_REPORTED_COST_MULTIPLIER,
90
91
  parseUiAskChoiceContent
91
- } from "./chunk-J4R5XRX5.js";
92
+ } from "./chunk-K4YGZD3P.js";
92
93
  import {
93
94
  isOAuthApiKeyRef
94
95
  } from "./chunk-YYLHWIW6.js";
@@ -99,50 +100,51 @@ import {
99
100
  } from "./chunk-TRV2MIDW.js";
100
101
  import {
101
102
  getDefaultCliLocalRuntimeDb
102
- } from "./chunk-C3FZR5EC.js";
103
+ } from "./chunk-2F7RJC6L.js";
103
104
  import {
104
105
  buildSkillDiscoveryContextLayer
105
106
  } from "./chunk-E4MARS3Q.js";
106
107
  import {
107
108
  parseExternalSkillMarkdown,
108
109
  parseSkillDocProtocol
109
- } from "./chunk-AETZ7AD6.js";
110
+ } from "./chunk-Q554LLSI.js";
110
111
  import {
111
112
  LOCAL_AGENT_CONFIG_MISSING_CODE,
112
113
  LOCAL_TURN_ABORTED_CODE,
113
114
  readActionGate
114
- } from "./chunk-KSHYBTYH.js";
115
+ } from "./chunk-ZWUOR654.js";
115
116
  import {
116
117
  resolveAgentRuntimeConfigFromRecord
117
- } from "./chunk-KIS76A2P.js";
118
+ } from "./chunk-3IIEFNGY.js";
118
119
  import {
119
120
  createThinkParserState,
120
121
  flushThinkParser,
121
122
  processThinkChunk
122
123
  } from "./chunk-N7J63Q6C.js";
123
124
  import {
125
+ QUOTA_ERROR_PATTERNS,
124
126
  isQuotaExhaustedError,
125
127
  isQuotaLimited403Body,
126
128
  mergeAvailabilityDeadline,
127
129
  resolveCooldownGate
128
- } from "./chunk-CJCJF5XB.js";
130
+ } from "./chunk-FDTR4QJ6.js";
129
131
  import {
130
132
  isAntigravityOAuthAgent
131
- } from "./chunk-PGSKWZCB.js";
133
+ } from "./chunk-UZGQNTVW.js";
132
134
  import {
133
135
  resolveClientVersion
134
- } from "./chunk-CMH2SYHX.js";
136
+ } from "./chunk-6OZ36FXI.js";
135
137
  import {
136
138
  DEFAULT_CONTEXT_WINDOW,
137
139
  getModelContextWindow,
138
140
  normalizeUsage
139
- } from "./chunk-DSRXPQWA.js";
141
+ } from "./chunk-JAXOVNM4.js";
140
142
  import {
141
143
  clipCompactText
142
- } from "./chunk-E36HZARC.js";
144
+ } from "./chunk-WADCY6G6.js";
143
145
  import {
144
146
  findModelConfig
145
- } from "./chunk-UJ63UXGE.js";
147
+ } from "./chunk-OIVSQH2O.js";
146
148
  import {
147
149
  compactWhitespace
148
150
  } from "./chunk-DWLEOOGR.js";
@@ -167,13 +169,14 @@ import {
167
169
  CLIENT_VERSION_TOO_OLD_CODE,
168
170
  NOLO_CLIENT_VERSION_HEADER,
169
171
  buildClientVersionUpgradeMessage
170
- } from "./chunk-AJHEFRGJ.js";
172
+ } from "./chunk-Q67DOFOO.js";
171
173
  import {
172
174
  parsePositiveFiniteNumberOrFallback
173
175
  } from "./chunk-Y5GCAMGP.js";
174
176
  import {
175
- createMemoryKey
176
- } from "./chunk-NHRQCXIQ.js";
177
+ createMemoryKey,
178
+ ulid
179
+ } from "./chunk-VMFTFOWF.js";
177
180
  import {
178
181
  asTrimmedLowercaseString
179
182
  } from "./chunk-QSJ3HFEF.js";
@@ -181,10 +184,13 @@ import {
181
184
  BUILTIN_NOLO_AGENT_KEY,
182
185
  BUILTIN_NOLO_AGENT_NAME,
183
186
  builtinAgentCatalogEntryById
184
- } from "./chunk-5J7W2VWW.js";
187
+ } from "./chunk-BNGW5ASC.js";
185
188
  import {
186
189
  parsePublicAgentId
187
- } from "./chunk-BJIRLHJR.js";
190
+ } from "./chunk-M2EJHDJP.js";
191
+ import {
192
+ isLevelNotFoundError
193
+ } from "./chunk-OW765XBU.js";
188
194
  import {
189
195
  asTrimmedString
190
196
  } from "./chunk-3EUW3WEO.js";
@@ -10411,9 +10417,9 @@ function findCollapsedPasteSpanAt(buffer, pos, opts = {}) {
10411
10417
  }
10412
10418
 
10413
10419
  // packages/cli/client/agentRun.ts
10414
- import { ulid } from "ulid";
10420
+ import { ulid as ulid2 } from "ulid";
10415
10421
  async function loadRunLocalAgentTurn() {
10416
- const { runLocalAgentTurn } = await import("./agentRuntimeLocal-VD4O2QFQ.js");
10422
+ const { runLocalAgentTurn } = await import("./agentRuntimeLocal-73CVIWBB.js");
10417
10423
  return runLocalAgentTurn;
10418
10424
  }
10419
10425
  var stripDebugNoise = (s) => s.replace(/\s*raw="[\s\S]*"/g, "").replace(/\s*raw=\S+/g, "").replace(/\s*headers=\[[^\]]*\]/g, "").replace(/\s*headers=\S+/g, "").trim();
@@ -10676,27 +10682,62 @@ function isMissingLocalAgentConfigError(error, agentRef) {
10676
10682
  }
10677
10683
  var PROVIDER_HTTP_FAILED_RE = /(.+?) provider failed:\s*HTTP\s+(\d+)\b/i;
10678
10684
  var PLATFORM_TRANSPORT_RE = /\bplatform provider failed\b/i;
10685
+ var EXTRA_RATE_LIMIT_TEXT_RE = /\brate[\s_-]?limit(?:ed|ing|s)?\b|\bresource[_\s-]?exhausted\b|\bmax_concurrent_reached\b/i;
10686
+ function looksLikeRateLimitedText(message) {
10687
+ return EXTRA_RATE_LIMIT_TEXT_RE.test(message) || QUOTA_ERROR_PATTERNS.some((pattern) => pattern.test(message));
10688
+ }
10689
+ var AUTH_TEXT_SIGNAL_RE = /\b401\b|unauthori[sz]ed|invalid[_\s-]?(?:api[_\s-]?key|token|credential)s?|(?:api[_\s-]?key|token|credential)s?[_\s-](?:invalid|expired|rejected|missing|not[_\s-]?found)|authentication[_\s-]?(?:error|failed|required)/i;
10690
+ var QUOTA_EXHAUSTED_EXTRA_RE = /insufficient[_\s-]?(?:quota|balance|credits?)|余额不足|额度已?用尽/i;
10691
+ function looksLikeQuotaExhaustedText(message) {
10692
+ return isQuotaLimited403Body(message) || QUOTA_EXHAUSTED_EXTRA_RE.test(message);
10693
+ }
10694
+ var BARE_UPSTREAM_5XX_RE = /\bHTTP[:\s]+(5\d\d)\b|\bstatus[:\s=]+(5\d\d)\b|\breturned error\s+(5\d\d)\b/i;
10679
10695
  function classifyLocalRunError(message) {
10680
10696
  const m = message.match(PROVIDER_HTTP_FAILED_RE);
10681
- if (!m) return { kind: "generic" };
10682
- const status = Number(m[2]);
10683
- const transport = PLATFORM_TRANSPORT_RE.test(message) ? "platform" : "local";
10684
- if (status === 401) {
10685
- return { kind: "auth", transport, status };
10686
- }
10687
- if (status === 403) {
10688
- return isQuotaLimited403Body(message) ? { kind: "rate-limit", transport, status } : { kind: "auth", transport, status };
10689
- }
10690
- if (status === 400 || status === 422) {
10691
- return { kind: "rejected-payload", transport, status };
10697
+ if (m) {
10698
+ const status = Number(m[2]);
10699
+ const transport2 = PLATFORM_TRANSPORT_RE.test(message) ? "platform" : "local";
10700
+ const quotaExhausted = looksLikeQuotaExhaustedText(message);
10701
+ if (status === 401) {
10702
+ return { kind: "auth", transport: transport2, status };
10703
+ }
10704
+ if (status === 403) {
10705
+ return quotaExhausted ? { kind: "rate-limit", transport: transport2, status, quotaExhausted: true } : { kind: "auth", transport: transport2, status };
10706
+ }
10707
+ if (status === 400 || status === 422) {
10708
+ return { kind: "rejected-payload", transport: transport2, status };
10709
+ }
10710
+ if (status === 429) {
10711
+ return {
10712
+ kind: "rate-limit",
10713
+ transport: transport2,
10714
+ status,
10715
+ ...quotaExhausted ? { quotaExhausted: true } : {}
10716
+ };
10717
+ }
10718
+ if (status >= 500 && status <= 599) {
10719
+ return { kind: "transient", transport: transport2, status };
10720
+ }
10721
+ return { kind: "upstream", transport: transport2, status };
10692
10722
  }
10693
- if (status === 429) {
10694
- return { kind: "rate-limit", transport, status };
10723
+ const transport = PLATFORM_TRANSPORT_RE.test(message) ? "platform" : "local";
10724
+ if (AUTH_TEXT_SIGNAL_RE.test(message)) return { kind: "generic" };
10725
+ if (looksLikeRateLimitedText(message)) {
10726
+ const quotaExhausted = looksLikeQuotaExhaustedText(message);
10727
+ return {
10728
+ kind: "rate-limit",
10729
+ transport,
10730
+ status: 429,
10731
+ statusInferred: true,
10732
+ ...quotaExhausted ? { quotaExhausted: true } : {}
10733
+ };
10695
10734
  }
10696
- if (status >= 500 && status <= 599) {
10735
+ const bare5xx = message.match(BARE_UPSTREAM_5XX_RE);
10736
+ if (bare5xx) {
10737
+ const status = Number(bare5xx[1] ?? bare5xx[2] ?? bare5xx[3]);
10697
10738
  return { kind: "transient", transport, status };
10698
10739
  }
10699
- return { kind: "upstream", transport, status };
10740
+ return { kind: "generic" };
10700
10741
  }
10701
10742
  var HISTORY_REPLAY_REJECTION_RE = /invalid_request_error|invalid\s+tool\s+call\s+arguments?/i;
10702
10743
  var RUN_UNAVAILABLE_PREFIX = "[nolo] auto runtime: local run unavailable";
@@ -10717,9 +10758,18 @@ function buildRejectedPayloadFailure(ctx) {
10717
10758
  return `${RUN_UNAVAILABLE_PREFIX} (${ctx.where} returned HTTP ${ctx.status}, the provider rejected the request body \u2014 this is NOT a local credential/config issue). Detail: ${ctx.message}${cause} ${NO_FALLBACK} Use --server to run on the server explicitly, or start a fresh dialog.
10718
10759
  `;
10719
10760
  }
10761
+ var RATE_LIMIT_RESET_HINT_RE = /retry[-_\s]?after\s*[:=]?\s*\d[\w:-]*|resets?\s+(?:in|at)\s+\d[\w:-]*(?:[ T]\d[\w:-]*)?/i;
10762
+ function extractRateLimitResetHint(message) {
10763
+ const match = message.match(RATE_LIMIT_RESET_HINT_RE);
10764
+ return match ? match[0].trim() : void 0;
10765
+ }
10720
10766
  function buildRateLimitFailure(ctx) {
10721
10767
  const cooldownNote = ctx.cooldownUntil ? ` \u5DF2\u6807\u8BB0\u51B7\u5374\u81F3 ${ctx.cooldownUntil}\uFF0C\u5230\u671F\u524D\u6D3E\u53D1\u4F1A\u88AB\u51B7\u5374\u95E8\u63A7\u62E6\u622A\uFF08\u5230\u671F\u81EA\u52A8 probe \u6062\u590D\uFF09\u3002` : "";
10722
- return `${RUN_UNAVAILABLE_PREFIX} (${ctx.where} returned HTTP ${ctx.status}, rate limited). Detail: ${ctx.message} ${NO_FALLBACK} Retry shortly, ${SERVER_FALLBACK_HINT}.${cooldownNote}
10768
+ const headline = ctx.statusInferred ? `${ctx.where} hit an upstream rate-limit/quota error` : `${ctx.where} returned HTTP ${ctx.status}, rate limited`;
10769
+ const cause = ctx.quotaExhausted ? "The upstream quota/balance for this agent is exhausted \u2014 NOT a local credential/config issue" : "This agent is being throttled by the upstream provider \u2014 NOT a local credential/config issue";
10770
+ const reset = extractRateLimitResetHint(ctx.message);
10771
+ const advice = ctx.quotaExhausted ? `Retry after the upstream quota resets${reset ? ` (${reset})` : ""}` : `Retry shortly${reset ? ` (${reset})` : ""}`;
10772
+ return `${RUN_UNAVAILABLE_PREFIX} (${headline}). Detail: ${ctx.message} ${NO_FALLBACK} ${cause}. ${advice}, switch to another agent (\`nolo agent list\`), ${SERVER_FALLBACK_HINT}${cooldownNote}
10723
10773
  `;
10724
10774
  }
10725
10775
  function buildTransientFailure(ctx) {
@@ -10814,6 +10864,8 @@ function describeLocalRunFailure(message, rawError) {
10814
10864
  message,
10815
10865
  where: cls.transport === "platform" ? "server chat proxy" : "local provider",
10816
10866
  status: cls.status,
10867
+ ...cls.statusInferred ? { statusInferred: true } : {},
10868
+ ...cls.quotaExhausted ? { quotaExhausted: true } : {},
10817
10869
  ...cooldownUntil ? { cooldownUntil } : {}
10818
10870
  };
10819
10871
  return FAILURE_BUILDERS[cls.kind](ctx);
@@ -11078,8 +11130,8 @@ async function runLocalAgentTurnForCli(options, settings) {
11078
11130
  ...options.parentWakeOnTerminal ? { parentWakeOnTerminal: true } : {},
11079
11131
  ...options.parentDialogId ? { parentThreadId: options.parentDialogId } : {}
11080
11132
  } : void 0;
11081
- const currentDialogId = options.continueDialogId ?? ulid();
11082
- const turnId = `turn-${ulid()}`;
11133
+ const currentDialogId = options.continueDialogId ?? ulid2();
11134
+ const turnId = `turn-${ulid2()}`;
11083
11135
  const runtimeContextWithOwnership = {
11084
11136
  ...runtimeContext ?? {},
11085
11137
  dialogId: currentDialogId,
@@ -11239,22 +11291,24 @@ async function checkLocalAvailabilityBeforeHttpDispatch(options) {
11239
11291
  }
11240
11292
  const agentLevelAt = baseRecord.nextAvailableAt;
11241
11293
  const agentLevelNextAvailableAt = typeof agentLevelAt === "number" && Number.isFinite(agentLevelAt) ? agentLevelAt : void 0;
11242
- if (!credentialKey && agentLevelNextAvailableAt === void 0) return null;
11294
+ if (!credentialKey && agentLevelNextAvailableAt === void 0) {
11295
+ return { credentialKey };
11296
+ }
11243
11297
  const env = options.env;
11244
11298
  const now = Date.now();
11245
11299
  const entry = credentialKey ? await readCredentialEntry(credentialKey, env, now).catch(() => void 0) : void 0;
11246
11300
  const entryAt = entry?.nextAvailableAt;
11247
11301
  const effectiveNextAvailableAt = typeof entryAt === "number" ? mergeAvailabilityDeadline(agentLevelNextAvailableAt, entryAt) : agentLevelNextAvailableAt;
11248
- if (typeof effectiveNextAvailableAt !== "number") return null;
11302
+ if (typeof effectiveNextAvailableAt !== "number") return { credentialKey };
11249
11303
  const gateDecision = resolveCooldownGate(
11250
11304
  { nextAvailableAt: effectiveNextAvailableAt, lastProbeAt: entry?.lastProbeAt },
11251
11305
  now
11252
11306
  );
11253
11307
  if (gateDecision === "probe" && credentialKey) {
11254
11308
  await recordCredentialProbe(credentialKey, env, now).catch(() => void 0);
11255
- return null;
11309
+ return { credentialKey };
11256
11310
  }
11257
- if (gateDecision !== "blocked") return null;
11311
+ if (gateDecision !== "blocked") return { credentialKey };
11258
11312
  options.output.write(
11259
11313
  `[nolo] Agent ${options.agentName || options.agentKey} is temporarily unavailable (429 cooldown) until ${new Date(Number(effectiveNextAvailableAt)).toISOString()}.
11260
11314
  Dispatch aborted before reaching the server. Pick another agent via listAgents, or retry after the cooldown.
@@ -11337,11 +11391,18 @@ async function runAgentTurn(options) {
11337
11391
  );
11338
11392
  return { exitCode: 1 };
11339
11393
  }
11340
- const localBlock = await checkLocalAvailabilityBeforeHttpDispatch(options);
11341
- if (localBlock) {
11342
- return { exitCode: localBlock.exitCode };
11394
+ const localAvailability = await checkLocalAvailabilityBeforeHttpDispatch(options);
11395
+ if (localAvailability?.exitCode) {
11396
+ return { exitCode: localAvailability.exitCode };
11397
+ }
11398
+ const httpResult = await runHttpAgentTurn(options, authToken);
11399
+ if (httpResult.exitCode === 0 && !httpResult.streamInterrupted && localAvailability?.credentialKey) {
11400
+ await clearCredentialAvailability(
11401
+ localAvailability.credentialKey,
11402
+ options.env
11403
+ ).catch(() => void 0);
11343
11404
  }
11344
- return runHttpAgentTurn(options, authToken);
11405
+ return httpResult;
11345
11406
  }
11346
11407
 
11347
11408
  // packages/cli/agentRunCommand.ts
@@ -12073,6 +12134,1078 @@ var rankMemoryCandidates = (items, query, context) => {
12073
12134
  });
12074
12135
  };
12075
12136
 
12137
+ // packages/ai/memory/vnext/store.ts
12138
+ var enc = (value) => encodeURIComponent(value).replace(/-/g, "%2D");
12139
+ var rangeOf = (prefix) => ({ gte: prefix, lte: `${prefix}\uFFFF` });
12140
+ var entityKey = (ownerId, id) => `mem2-e-${enc(ownerId)}-${enc(id)}`;
12141
+ var entityOwnerPrefix = (ownerId) => `mem2-e-${enc(ownerId)}-`;
12142
+ var stateKey = (ownerId, id) => `mem2-s-${enc(ownerId)}-${enc(id)}`;
12143
+ var stateEntityIndexKey = (ownerId, entityId, stateId) => `mem2-si-${enc(ownerId)}-${enc(entityId)}-${enc(stateId)}`;
12144
+ var stateEntityIndexPrefix = (ownerId, entityId) => `mem2-si-${enc(ownerId)}-${enc(entityId)}-`;
12145
+ var evidenceKey = (ownerId, id) => `mem2-v-${enc(ownerId)}-${enc(id)}`;
12146
+ var relationKey = (ownerId, id) => `mem2-r-${enc(ownerId)}-${enc(id)}`;
12147
+ var relationFromIndexKey = (ownerId, from, relationId) => `mem2-rf-${enc(ownerId)}-${enc(from)}-${enc(relationId)}`;
12148
+ var relationToIndexKey = (ownerId, to, relationId) => `mem2-rt-${enc(ownerId)}-${enc(to)}-${enc(relationId)}`;
12149
+ var readIndexed = async (db, prefix) => {
12150
+ const refs = [];
12151
+ for await (const [, value] of db.iterator({ ...rangeOf(prefix), reverse: false })) {
12152
+ if (typeof value?.key === "string") refs.push(value.key);
12153
+ }
12154
+ const rows = await Promise.all(refs.map((key) => db.get(key).catch(() => null)));
12155
+ return rows.filter((row) => !!row);
12156
+ };
12157
+ var getMemoryEntityVNext = async (db, ownerId, entityId) => db.get(entityKey(ownerId, entityId)).catch(() => null);
12158
+ var listMemoryEntitiesVNext = async (db, ownerId) => {
12159
+ const rows = [];
12160
+ for await (const [, value] of db.iterator({
12161
+ ...rangeOf(entityOwnerPrefix(ownerId)),
12162
+ reverse: false
12163
+ })) {
12164
+ if (value) rows.push(value);
12165
+ }
12166
+ return rows;
12167
+ };
12168
+ var getMemoryStateVNext = async (db, ownerId, stateId) => db.get(stateKey(ownerId, stateId)).catch(() => null);
12169
+ var listMemoryStatesForEntityVNext = (db, ownerId, entityId) => readIndexed(db, stateEntityIndexPrefix(ownerId, entityId));
12170
+ var putMemoryEvidenceVNext = async (db, evidence) => {
12171
+ await db.put(evidenceKey(evidence.ownerId, evidence.id), evidence);
12172
+ };
12173
+ var getMemoryEvidenceVNext = async (db, ownerId, evidenceId) => db.get(evidenceKey(ownerId, evidenceId)).catch(() => null);
12174
+ var getMemoryEvidenceVNextStrict = async (db, ownerId, evidenceId) => {
12175
+ try {
12176
+ return await db.get(evidenceKey(ownerId, evidenceId));
12177
+ } catch (error) {
12178
+ if (isLevelNotFoundError(error)) return null;
12179
+ throw error;
12180
+ }
12181
+ };
12182
+ var _appendEntityBatch = (batch, entity) => {
12183
+ batch.put(entityKey(entity.ownerId, entity.id), entity);
12184
+ };
12185
+ var _appendEvidenceBatch = (batch, evidence) => {
12186
+ batch.put(evidenceKey(evidence.ownerId, evidence.id), evidence);
12187
+ };
12188
+ var _appendStateBatch = (batch, state2) => {
12189
+ const key = stateKey(state2.ownerId, state2.id);
12190
+ batch.put(key, state2);
12191
+ batch.put(stateEntityIndexKey(state2.ownerId, state2.entityId, state2.id), { key });
12192
+ };
12193
+ var _appendRetiredStateBatch = (batch, state2) => {
12194
+ batch.put(stateKey(state2.ownerId, state2.id), state2);
12195
+ };
12196
+ var _appendRelationBatch = (batch, relation) => {
12197
+ const key = relationKey(relation.ownerId, relation.id);
12198
+ batch.put(key, relation);
12199
+ batch.put(relationFromIndexKey(relation.ownerId, relation.from, relation.id), { key });
12200
+ batch.put(relationToIndexKey(relation.ownerId, relation.to, relation.id), { key });
12201
+ };
12202
+
12203
+ // packages/ai/memory/vnext/recall.ts
12204
+ var MAX_RECALL_REFS = 6;
12205
+ var stripFence = (raw) => {
12206
+ const trimmed = raw.trim();
12207
+ const match = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
12208
+ return match ? match[1].trim() : trimmed;
12209
+ };
12210
+ var parseSelection = (raw) => {
12211
+ let parsed;
12212
+ try {
12213
+ parsed = JSON.parse(stripFence(raw));
12214
+ } catch {
12215
+ throw new Error("memory recall selector output is not valid JSON");
12216
+ }
12217
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
12218
+ throw new Error("memory recall selector output must be an object");
12219
+ }
12220
+ const obj = parsed;
12221
+ if (!Array.isArray(obj.refs) || !obj.refs.every((item) => typeof item === "string")) {
12222
+ throw new Error("memory recall selector refs must be string[]");
12223
+ }
12224
+ if (typeof obj.reason !== "string") {
12225
+ throw new Error("memory recall selector reason must be string");
12226
+ }
12227
+ return {
12228
+ refs: [...new Set(obj.refs)].slice(0, MAX_RECALL_REFS),
12229
+ reason: obj.reason
12230
+ };
12231
+ };
12232
+ var buildCatalog = async (db, ownerId) => {
12233
+ const entities = await listMemoryEntitiesVNext(db, ownerId);
12234
+ const states = [];
12235
+ for (const entity of entities) {
12236
+ states.push(...await listMemoryStatesForEntityVNext(db, ownerId, entity.id));
12237
+ }
12238
+ return { entities, states };
12239
+ };
12240
+ var catalogText = (entities, states) => JSON.stringify(
12241
+ {
12242
+ entities: entities.map((entity) => ({
12243
+ id: entity.id,
12244
+ type: entity.type,
12245
+ name: entity.name,
12246
+ ...entity.subtype ? { subtype: entity.subtype } : {},
12247
+ ...entity.aliases?.length ? { aliases: entity.aliases } : {}
12248
+ })),
12249
+ states: states.map((state2) => ({
12250
+ id: state2.id,
12251
+ entityId: state2.entityId,
12252
+ facet: state2.facet,
12253
+ text: state2.text,
12254
+ // Retired (superseded) States stay listed as recoverable history; the
12255
+ // boolean — not the retiredAt timestamp — enters the prompt so no
12256
+ // timestamps reach LLM text.
12257
+ ...state2.retiredAt ? { retired: true } : {}
12258
+ }))
12259
+ },
12260
+ null,
12261
+ 2
12262
+ );
12263
+ var createMemoryVNextRecall = (input) => async (query) => {
12264
+ const startedAt = performance.now();
12265
+ const { entities, states } = await buildCatalog(input.db, input.ownerId);
12266
+ if (entities.length === 0 && states.length === 0) {
12267
+ return {
12268
+ query,
12269
+ refs: [],
12270
+ entities: [],
12271
+ states: [],
12272
+ reason: "memory catalog is empty",
12273
+ trace: {
12274
+ candidateEntities: 0,
12275
+ candidateStates: 0,
12276
+ selectedRefs: 0,
12277
+ elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
12278
+ }
12279
+ };
12280
+ }
12281
+ const result = await input.provider.complete(
12282
+ [
12283
+ {
12284
+ role: "system",
12285
+ content: [
12286
+ "Select the smallest useful set of long-lived memory entrances for the user query.",
12287
+ 'Return ONLY JSON: {"refs":["exact-id"],"reason":"short explanation"}.',
12288
+ `Select at most ${MAX_RECALL_REFS} exact ids from the supplied catalog.`,
12289
+ "Prefer State ids when current durable understanding answers the query.",
12290
+ "Select an Entity id when it is a useful navigation anchor and no single State is enough.",
12291
+ "Do not select unrelated memories merely because they are personal or interesting.",
12292
+ "Historical-detail questions may select the relevant current State/Entity as an entrance; deeper evidence is handled by inspect, not here."
12293
+ ].join("\n")
12294
+ },
12295
+ {
12296
+ role: "user",
12297
+ content: `Query:
12298
+ ${query}
12299
+
12300
+ Memory catalog:
12301
+ ${catalogText(entities, states)}`
12302
+ }
12303
+ ],
12304
+ input.timeoutMs ? { timeoutMs: input.timeoutMs } : void 0
12305
+ );
12306
+ const selected = parseSelection(result.content);
12307
+ const entityById = new Map(entities.map((entity) => [entity.id, entity]));
12308
+ const stateById = new Map(states.map((state2) => [state2.id, state2]));
12309
+ const validRefs = selected.refs.filter((ref) => entityById.has(ref) || stateById.has(ref));
12310
+ return {
12311
+ query,
12312
+ refs: validRefs,
12313
+ entities: validRefs.flatMap((ref) => {
12314
+ const entity = entityById.get(ref);
12315
+ return entity ? [entity] : [];
12316
+ }),
12317
+ states: validRefs.flatMap((ref) => {
12318
+ const state2 = stateById.get(ref);
12319
+ return state2 ? [state2] : [];
12320
+ }),
12321
+ reason: selected.reason,
12322
+ trace: {
12323
+ candidateEntities: entities.length,
12324
+ candidateStates: states.length,
12325
+ selectedRefs: validRefs.length,
12326
+ elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
12327
+ }
12328
+ };
12329
+ };
12330
+
12331
+ // packages/ai/memory/vnext/legacyMigration.ts
12332
+ import { createHash } from "crypto";
12333
+ var LEGACY_MEMORY_SOURCE_REF_PREFIX = "legacy-memory";
12334
+ var LEGACY_MEMORY_EVIDENCE_ID_PREFIX = "mem-legacy-";
12335
+ var resolveLegacyMemoryPrincipal = (item) => ({
12336
+ ownerType: item.ownerType,
12337
+ ownerId: item.ownerId,
12338
+ principalId: `${item.ownerType}:${encodeURIComponent(item.ownerId)}`
12339
+ });
12340
+ var buildLegacyMemorySourceRef = (item) => {
12341
+ const { principalId } = resolveLegacyMemoryPrincipal(item);
12342
+ return `${LEGACY_MEMORY_SOURCE_REF_PREFIX}:${principalId}:${encodeURIComponent(item.id)}`;
12343
+ };
12344
+ var legacyEvidenceSeed = (principalId, itemId) => JSON.stringify([principalId, itemId]);
12345
+ var buildLegacyEvidenceId = (item) => {
12346
+ const { principalId } = resolveLegacyMemoryPrincipal(item);
12347
+ const digest = createHash("sha256").update(legacyEvidenceSeed(principalId, item.id)).digest("hex");
12348
+ return `${LEGACY_MEMORY_EVIDENCE_ID_PREFIX}${digest.slice(0, 32)}`;
12349
+ };
12350
+ var clampLegacyConfidence = (value) => {
12351
+ if (typeof value !== "number" || !Number.isFinite(value)) return 0;
12352
+ if (value < 0) return 0;
12353
+ if (value > 1) return 1;
12354
+ return value;
12355
+ };
12356
+ var buildLegacyMemoryEvidence = (item) => {
12357
+ const { principalId } = resolveLegacyMemoryPrincipal(item);
12358
+ return {
12359
+ id: buildLegacyEvidenceId(item),
12360
+ ownerId: principalId,
12361
+ text: item.content,
12362
+ sourceRef: buildLegacyMemorySourceRef(item),
12363
+ confidence: clampLegacyConfidence(item.confidence),
12364
+ createdAt: item.createdAt
12365
+ };
12366
+ };
12367
+
12368
+ // packages/ai/memory/vnext/shadowRead.ts
12369
+ var SHADOW_TIMEOUT_MS = 2e4;
12370
+ var ERROR_MESSAGE_MAX = 120;
12371
+ var normalizeTextKey = (text) => text.trim().replace(/\s+/g, " ").toLowerCase();
12372
+ var legacyItemKeys = (item) => {
12373
+ const keys = [normalizeTextKey(item.content ?? "")];
12374
+ return keys.filter((key) => key.length > 0);
12375
+ };
12376
+ var vnextResultKeys = (result) => {
12377
+ const keys = [];
12378
+ for (const entity of result.entities) {
12379
+ if (entity.name) keys.push(normalizeTextKey(entity.name));
12380
+ }
12381
+ for (const state2 of result.states) {
12382
+ if (state2.text) keys.push(normalizeTextKey(state2.text));
12383
+ }
12384
+ return keys.filter((key) => key.length > 0);
12385
+ };
12386
+ var vnextContextChars = (result) => result.entities.reduce(
12387
+ (sum, entity) => sum + (entity.name?.length ?? 0),
12388
+ result.states.reduce((sum, state2) => sum + (state2.text?.length ?? 0), 0)
12389
+ );
12390
+ var shortError = (error) => {
12391
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
12392
+ return message.length > ERROR_MESSAGE_MAX ? `${message.slice(0, ERROR_MESSAGE_MAX)}\u2026` : message;
12393
+ };
12394
+ var withTimeout = async (promise, timeoutMs, label) => {
12395
+ let timer;
12396
+ const timeout = new Promise((_, reject) => {
12397
+ timer = setTimeout(() => reject(new Error(label)), timeoutMs);
12398
+ });
12399
+ try {
12400
+ return await Promise.race([promise, timeout]);
12401
+ } finally {
12402
+ if (timer) clearTimeout(timer);
12403
+ }
12404
+ };
12405
+ var runMemoryVNextShadowRead = async (input) => {
12406
+ const now = input.ctx.now ?? (() => performance.now());
12407
+ const defaultEmit = (observation2) => {
12408
+ const payload = {
12409
+ event: "memory_vnext_shadow_read",
12410
+ ...observation2
12411
+ };
12412
+ console.info("[memory] vnext shadow read", payload);
12413
+ };
12414
+ const emit = input.emit ?? defaultEmit;
12415
+ const legacyKeys = new Set(
12416
+ input.legacyItems.flatMap((item) => legacyItemKeys(item))
12417
+ );
12418
+ const vnextStartedAt = now();
12419
+ let vnextHitCount = 0;
12420
+ let vnextChars = 0;
12421
+ const vnextKeys = /* @__PURE__ */ new Set();
12422
+ let vnextError;
12423
+ try {
12424
+ const shadowTimeoutMs = input.ctx.shadowTimeoutMs ?? SHADOW_TIMEOUT_MS;
12425
+ const perOwner = async (owner) => {
12426
+ const principal = resolveLegacyMemoryPrincipal({
12427
+ ownerType: owner.ownerType,
12428
+ ownerId: owner.ownerId
12429
+ });
12430
+ const recall = createMemoryVNextRecall({
12431
+ db: input.ctx.db,
12432
+ ownerId: principal.principalId,
12433
+ provider: input.ctx.provider,
12434
+ timeoutMs: input.ctx.timeoutMs
12435
+ });
12436
+ return recall(input.ctx.query);
12437
+ };
12438
+ const results = await withTimeout(
12439
+ Promise.all(input.ctx.owners.map((owner) => perOwner(owner))),
12440
+ shadowTimeoutMs,
12441
+ `memory vnext shadow read timed out after ${shadowTimeoutMs}ms`
12442
+ );
12443
+ for (const result of results) {
12444
+ vnextHitCount += result.refs.length;
12445
+ vnextChars += vnextContextChars(result);
12446
+ for (const key of vnextResultKeys(result)) vnextKeys.add(key);
12447
+ }
12448
+ } catch (error) {
12449
+ vnextError = shortError(error);
12450
+ }
12451
+ const vnextLatencyMs = Math.round((now() - vnextStartedAt) * 10) / 10;
12452
+ let overlapCount = null;
12453
+ let legacyOnlyCount = null;
12454
+ let vnextOnlyCount = null;
12455
+ if (!vnextError) {
12456
+ let overlap = 0;
12457
+ for (const key of vnextKeys) if (legacyKeys.has(key)) overlap += 1;
12458
+ overlapCount = overlap;
12459
+ legacyOnlyCount = Math.max(0, legacyKeys.size - overlap);
12460
+ vnextOnlyCount = Math.max(0, vnextKeys.size - overlap);
12461
+ }
12462
+ const observation = {
12463
+ legacyHitCount: input.legacyItems.length,
12464
+ vnextHitCount,
12465
+ overlapCount,
12466
+ legacyOnlyCount,
12467
+ vnextOnlyCount,
12468
+ legacyLatencyMs: input.legacyLatencyMs,
12469
+ vnextLatencyMs,
12470
+ legacyContextChars: input.legacyContextChars,
12471
+ vnextContextChars: vnextChars,
12472
+ ...vnextError ? { vnextError } : {}
12473
+ };
12474
+ emit(observation);
12475
+ return observation;
12476
+ };
12477
+ var isMemoryVNextShadowReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_SHADOW_READ === "1" || env.NOLO_MEMORY_VNEXT_SHADOW_READ === "true";
12478
+
12479
+ // packages/ai/memory/vnext/applyMutation.ts
12480
+ async function validateMutation(db, ownerId, mutation) {
12481
+ const pending = {
12482
+ evidenceIds: /* @__PURE__ */ new Set(),
12483
+ entityIds: /* @__PURE__ */ new Set(),
12484
+ stateIds: /* @__PURE__ */ new Set(),
12485
+ relationIds: /* @__PURE__ */ new Set()
12486
+ };
12487
+ for (const ev of mutation.evidence ?? []) {
12488
+ if (!ev.id || typeof ev.id !== "string") {
12489
+ throw new Error("evidence id must be a non-empty string");
12490
+ }
12491
+ if (pending.evidenceIds.has(ev.id)) {
12492
+ throw new Error(`duplicate evidence id in mutation: ${ev.id}`);
12493
+ }
12494
+ pending.evidenceIds.add(ev.id);
12495
+ }
12496
+ for (const ent of mutation.entities ?? []) {
12497
+ if (!ent.id || typeof ent.id !== "string") {
12498
+ throw new Error("entity id must be a non-empty string");
12499
+ }
12500
+ if (pending.entityIds.has(ent.id)) {
12501
+ throw new Error(`duplicate entity id in mutation: ${ent.id}`);
12502
+ }
12503
+ pending.entityIds.add(ent.id);
12504
+ }
12505
+ for (const st of mutation.states ?? []) {
12506
+ if (!st.id || typeof st.id !== "string") {
12507
+ throw new Error("state id must be a non-empty string");
12508
+ }
12509
+ if (pending.stateIds.has(st.id)) {
12510
+ throw new Error(`duplicate state id in mutation: ${st.id}`);
12511
+ }
12512
+ pending.stateIds.add(st.id);
12513
+ }
12514
+ for (const rel of mutation.relations ?? []) {
12515
+ if (!rel.id || typeof rel.id !== "string") {
12516
+ throw new Error("relation id must be a non-empty string");
12517
+ }
12518
+ if (pending.relationIds.has(rel.id)) {
12519
+ throw new Error(`duplicate relation id in mutation: ${rel.id}`);
12520
+ }
12521
+ pending.relationIds.add(rel.id);
12522
+ }
12523
+ const supersededIds = /* @__PURE__ */ new Set();
12524
+ for (const sid of mutation.supersededStateIds ?? []) {
12525
+ if (supersededIds.has(sid)) {
12526
+ throw new Error(`duplicate supersededStateId in mutation: ${sid}`);
12527
+ }
12528
+ supersededIds.add(sid);
12529
+ }
12530
+ for (const ev of mutation.evidence ?? []) {
12531
+ if (ev.ownerId !== ownerId) {
12532
+ throw new Error(
12533
+ `evidence ${ev.id} has ownerId ${ev.ownerId}, expected ${ownerId}`
12534
+ );
12535
+ }
12536
+ }
12537
+ for (const ent of mutation.entities ?? []) {
12538
+ if (ent.ownerId !== ownerId) {
12539
+ throw new Error(
12540
+ `entity ${ent.id} has ownerId ${ent.ownerId}, expected ${ownerId}`
12541
+ );
12542
+ }
12543
+ }
12544
+ for (const st of mutation.states ?? []) {
12545
+ if (st.ownerId !== ownerId) {
12546
+ throw new Error(
12547
+ `state ${st.id} has ownerId ${st.ownerId}, expected ${ownerId}`
12548
+ );
12549
+ }
12550
+ }
12551
+ for (const rel of mutation.relations ?? []) {
12552
+ if (rel.ownerId !== ownerId) {
12553
+ throw new Error(
12554
+ `relation ${rel.id} has ownerId ${rel.ownerId}, expected ${ownerId}`
12555
+ );
12556
+ }
12557
+ }
12558
+ for (const st of mutation.states ?? []) {
12559
+ if (supersededIds.has(st.id)) {
12560
+ throw new Error(
12561
+ `state ${st.id} appears in both states and supersededStateIds; a record cannot be created and retired in the same mutation`
12562
+ );
12563
+ }
12564
+ }
12565
+ const facetSlots = /* @__PURE__ */ new Set();
12566
+ for (const st of mutation.states ?? []) {
12567
+ const slot = `${st.entityId} ${st.facet}`;
12568
+ if (facetSlots.has(slot)) {
12569
+ throw new Error(
12570
+ `mutation writes parallel current states for entity ${st.entityId} facet ${st.facet}`
12571
+ );
12572
+ }
12573
+ facetSlots.add(slot);
12574
+ }
12575
+ for (const ev of mutation.evidence ?? []) {
12576
+ const existing = await getMemoryEvidenceVNext(db, ownerId, ev.id);
12577
+ if (existing) {
12578
+ throw new Error(
12579
+ `evidence ${ev.id} already exists (owner ${ownerId}); use a unique id`
12580
+ );
12581
+ }
12582
+ }
12583
+ for (const ent of mutation.entities ?? []) {
12584
+ const existing = await getMemoryEntityVNext(db, ownerId, ent.id);
12585
+ if (existing) {
12586
+ throw new Error(
12587
+ `entity ${ent.id} already exists (owner ${ownerId}); use a unique id`
12588
+ );
12589
+ }
12590
+ }
12591
+ for (const st of mutation.states ?? []) {
12592
+ if (!pending.entityIds.has(st.entityId)) {
12593
+ const entity = await getMemoryEntityVNext(db, ownerId, st.entityId);
12594
+ if (!entity) {
12595
+ throw new Error(
12596
+ `memory state ${st.id} references missing entity ${st.entityId} (owner ${ownerId})`
12597
+ );
12598
+ }
12599
+ }
12600
+ for (const evidenceId of st.evidenceIds) {
12601
+ if (!pending.evidenceIds.has(evidenceId)) {
12602
+ const ev = await getMemoryEvidenceVNext(db, ownerId, evidenceId);
12603
+ if (!ev) {
12604
+ throw new Error(
12605
+ `memory state ${st.id} references missing evidence ${evidenceId} (owner ${ownerId})`
12606
+ );
12607
+ }
12608
+ }
12609
+ }
12610
+ const existing = await getMemoryStateVNext(db, ownerId, st.id);
12611
+ if (existing) {
12612
+ if (existing.retiredAt) {
12613
+ throw new Error(
12614
+ `cannot update retired memory state ${st.id} (owner ${ownerId})`
12615
+ );
12616
+ }
12617
+ if (existing.entityId !== st.entityId || existing.facet !== st.facet) {
12618
+ throw new Error(
12619
+ `state ${st.id} already exists with different entity/facet (${existing.entityId}/${existing.facet} vs ${st.entityId}/${st.facet}); use supersede instead`
12620
+ );
12621
+ }
12622
+ }
12623
+ if (!existing) {
12624
+ const existingStates = await listMemoryStatesForEntityVNext(db, ownerId, st.entityId);
12625
+ for (const es of existingStates) {
12626
+ if (es.facet === st.facet && !es.retiredAt) {
12627
+ if (!supersededIds.has(es.id)) {
12628
+ throw new Error(
12629
+ `entity ${st.entityId} facet ${st.facet} already has current state ${es.id}; supersede it or use a different facet`
12630
+ );
12631
+ }
12632
+ }
12633
+ }
12634
+ }
12635
+ }
12636
+ for (const sid of mutation.supersededStateIds ?? []) {
12637
+ const existing = await getMemoryStateVNext(db, ownerId, sid);
12638
+ if (!existing) {
12639
+ throw new Error(
12640
+ `cannot supersede missing memory state: ${sid} (owner ${ownerId})`
12641
+ );
12642
+ }
12643
+ if (existing.retiredAt) {
12644
+ throw new Error(
12645
+ `cannot supersede already retired memory state: ${sid} (owner ${ownerId})`
12646
+ );
12647
+ }
12648
+ const replacement = (mutation.states ?? []).find(
12649
+ (st) => st.entityId === existing.entityId && st.facet === existing.facet
12650
+ );
12651
+ if (!replacement) {
12652
+ throw new Error(
12653
+ `superseded state ${sid} (entity ${existing.entityId} facet ${existing.facet}) has no replacement in this mutation`
12654
+ );
12655
+ }
12656
+ }
12657
+ for (const rel of mutation.relations ?? []) {
12658
+ for (const [side, ref] of [
12659
+ ["from", rel.from],
12660
+ ["to", rel.to]
12661
+ ]) {
12662
+ if (pending.entityIds.has(ref) || pending.stateIds.has(ref) || pending.evidenceIds.has(ref)) {
12663
+ continue;
12664
+ }
12665
+ const resolved = await getMemoryEntityVNext(db, ownerId, ref) ?? await getMemoryStateVNext(db, ownerId, ref) ?? await getMemoryEvidenceVNext(db, ownerId, ref);
12666
+ if (!resolved) {
12667
+ throw new Error(
12668
+ `memory relation ${rel.id} references missing ${side} ${ref} (owner ${ownerId})`
12669
+ );
12670
+ }
12671
+ }
12672
+ }
12673
+ }
12674
+ var applyMemoryInterpreterMutation = async (db, ownerId, mutation) => {
12675
+ await validateMutation(db, ownerId, mutation);
12676
+ const batch = db.batch();
12677
+ for (const ev of mutation.evidence ?? []) {
12678
+ _appendEvidenceBatch(batch, ev);
12679
+ }
12680
+ for (const ent of mutation.entities ?? []) {
12681
+ _appendEntityBatch(batch, ent);
12682
+ }
12683
+ for (const st of mutation.states ?? []) {
12684
+ _appendStateBatch(batch, st);
12685
+ }
12686
+ for (const sid of mutation.supersededStateIds ?? []) {
12687
+ const existing = await getMemoryStateVNext(db, ownerId, sid);
12688
+ if (!existing) {
12689
+ throw new Error(
12690
+ `cannot supersede missing memory state: ${sid} (owner ${ownerId})`
12691
+ );
12692
+ }
12693
+ const replacement = (mutation.states ?? []).find(
12694
+ (st) => st.entityId === existing.entityId && st.facet === existing.facet
12695
+ );
12696
+ const retired = {
12697
+ ...existing,
12698
+ retiredAt: replacement?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
12699
+ };
12700
+ _appendRetiredStateBatch(batch, retired);
12701
+ }
12702
+ for (const rel of mutation.relations ?? []) {
12703
+ _appendRelationBatch(batch, rel);
12704
+ }
12705
+ await batch.write();
12706
+ };
12707
+
12708
+ // packages/ai/memory/vnext/legacyMigrationApply.ts
12709
+ var isSameLegacyMemoryEvidence = (left, right) => left.id === right.id && left.ownerId === right.ownerId && left.text === right.text && left.sourceRef === right.sourceRef && left.confidence === right.confidence && left.createdAt === right.createdAt;
12710
+ var applyLegacyMemoryEvidence = async (db, item) => {
12711
+ const incoming = buildLegacyMemoryEvidence(item);
12712
+ const existing = await getMemoryEvidenceVNextStrict(db, incoming.ownerId, incoming.id);
12713
+ if (existing) {
12714
+ return isSameLegacyMemoryEvidence(existing, incoming) ? { status: "already_exists", evidence: existing } : { status: "conflict", existing, incoming };
12715
+ }
12716
+ await putMemoryEvidenceVNext(db, incoming);
12717
+ return { status: "created", evidence: incoming };
12718
+ };
12719
+
12720
+ // packages/ai/memory/vnext/types.ts
12721
+ var MEMORY_ENTITY_TYPES = [
12722
+ "person",
12723
+ "organization",
12724
+ "project",
12725
+ "place",
12726
+ "object",
12727
+ "activity",
12728
+ "concept"
12729
+ ];
12730
+ var MEMORY_RELATION_TYPES = [
12731
+ "related_to",
12732
+ "part_of",
12733
+ "uses",
12734
+ "involves",
12735
+ "supersedes"
12736
+ ];
12737
+
12738
+ // packages/ai/memory/vnext/interpreterWireProtocol.ts
12739
+ var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
12740
+ var isString = (value) => typeof value === "string" && value.trim().length > 0;
12741
+ var isStringArray = (value) => Array.isArray(value) && value.every(isString);
12742
+ var optionalArray = (value, validate2) => value === void 0 || Array.isArray(value) && value.every(validate2);
12743
+ var ACTIONS = /* @__PURE__ */ new Set([
12744
+ "no_op",
12745
+ "create",
12746
+ "update",
12747
+ "specialize",
12748
+ "supersede",
12749
+ "ambiguous"
12750
+ ]);
12751
+ var validateEvidence = (value) => {
12752
+ if (!isObject(value)) return false;
12753
+ return isString(value.key) && isString(value.text) && typeof value.confidence === "number" && Number.isFinite(value.confidence) && value.confidence >= 0 && value.confidence <= 1 && (value.sourceRef === void 0 || isString(value.sourceRef));
12754
+ };
12755
+ var validateEntity = (value) => {
12756
+ if (!isObject(value)) return false;
12757
+ return isString(value.key) && MEMORY_ENTITY_TYPES.includes(value.type) && isString(value.name) && (value.subtype === void 0 || isString(value.subtype)) && (value.aliases === void 0 || isStringArray(value.aliases));
12758
+ };
12759
+ var validateState = (value) => {
12760
+ if (!isObject(value)) return false;
12761
+ return (value.stateId === void 0 || isString(value.stateId)) && (value.supersedes === void 0 || isString(value.supersedes)) && isString(value.entityRef) && isString(value.facet) && "value" in value && isString(value.text) && isStringArray(value.evidenceRefs);
12762
+ };
12763
+ var validateRelation = (value) => {
12764
+ if (!isObject(value)) return false;
12765
+ return isString(value.fromRef) && MEMORY_RELATION_TYPES.includes(value.type) && isString(value.toRef);
12766
+ };
12767
+ var stripJsonFence = (raw) => {
12768
+ const trimmed = raw.trim();
12769
+ const match = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
12770
+ return match ? match[1].trim() : trimmed;
12771
+ };
12772
+ var parseMemoryInterpreterWireMutation = (raw) => {
12773
+ let parsed;
12774
+ try {
12775
+ parsed = JSON.parse(stripJsonFence(raw));
12776
+ } catch {
12777
+ return { ok: false, error: "interpreter output is not valid JSON" };
12778
+ }
12779
+ if (!isObject(parsed)) return { ok: false, error: "interpreter output must be an object" };
12780
+ if (!isString(parsed.action) || !ACTIONS.has(parsed.action)) {
12781
+ return { ok: false, error: "invalid reconciliation action" };
12782
+ }
12783
+ if (!isString(parsed.reason)) return { ok: false, error: "reason is required" };
12784
+ if (!optionalArray(parsed.evidence, validateEvidence)) return { ok: false, error: "invalid evidence array" };
12785
+ if (!optionalArray(parsed.entities, validateEntity)) return { ok: false, error: "invalid entities array" };
12786
+ if (!optionalArray(parsed.states, validateState)) return { ok: false, error: "invalid states array" };
12787
+ if (!optionalArray(parsed.relations, validateRelation)) return { ok: false, error: "invalid relations array" };
12788
+ return { ok: true, value: parsed };
12789
+ };
12790
+ var buildMemoryInterpreterWireContract = () => `
12791
+ Return ONLY one JSON object:
12792
+ {
12793
+ "action": "no_op|create|update|specialize|supersede|ambiguous",
12794
+ "reason": "short explanation",
12795
+ "evidence": [{ "key": "e1", "text": "...", "confidence": 0.9, "sourceRef": "optional" }],
12796
+ "entities": [{ "key": "n1", "type": "person|organization|project|place|object|activity|concept", "name": "...", "subtype": "optional", "aliases": [] }],
12797
+ "states": [{ "stateId": "optional-existing-state-id", "supersedes": "optional-existing-state-id-this-statement-replaces", "entityRef": "existing-entity-id-or-new-entity-key", "facet": "...", "value": {}, "text": "...", "evidenceRefs": ["e1"] }],
12798
+ "relations": [{ "fromRef": "existing-id-or-local-key", "type": "related_to|part_of|uses|involves|supersedes", "toRef": "existing-id-or-local-key" }]
12799
+ }
12800
+
12801
+ Do not generate persistent ids, owner ids, timestamps or storage keys. Runtime owns identity and time.
12802
+ Use short local keys only to connect records created in the SAME response. Every local key must be unique across evidence/entities.
12803
+ State evidenceRefs may reference Evidence emitted in this response. Evidence ids marked referenceable in the supplied memory context may be referenced directly. Do not reference any other prior Evidence id.
12804
+ When updating an existing State, reuse its exact stateId, exact entityRef and exact facet. Runtime preserves that State's original entity/facet/createdAt and appends new Evidence provenance.
12805
+ When creating a new State, omit stateId.
12806
+ For supersede: emit the replacing statement as a NEW State (omit stateId) and set supersedes to the exact id of the replaced current State. Runtime retires the replaced State \u2014 it stays recoverable as history but is no longer current, and the new State becomes the only current one for that facet. Never update or supersede an already retired State.
12807
+ supersedes and stateId are mutually exclusive on one State.
12808
+ Do not emit an existing Entity again merely to update its State; reference its exact id in entityRef.
12809
+ Relations may reference only known persisted Entity/State/Evidence ids or local Entity/Evidence keys emitted in the same response.
12810
+ Do not invent new Entity or Relation types. Keep expressive detail in subtype/facet/value/text.
12811
+ `.trim();
12812
+ var assertUniqueLocalKeys = (wire) => {
12813
+ const seen = /* @__PURE__ */ new Set();
12814
+ for (const item of [...wire.evidence ?? [], ...wire.entities ?? []]) {
12815
+ if (seen.has(item.key)) throw new Error(`duplicate local key: ${item.key}`);
12816
+ seen.add(item.key);
12817
+ }
12818
+ };
12819
+ var materializeMemoryInterpreterMutation = (input) => {
12820
+ assertUniqueLocalKeys(input.wire);
12821
+ const now = input.now ?? (/* @__PURE__ */ new Date()).toISOString();
12822
+ const nextId = input.nextId ?? ulid;
12823
+ const existingStates = new Map((input.existingStates ?? []).map((state2) => [state2.id, state2]));
12824
+ const existingStateIds = new Set(existingStates.keys());
12825
+ const existingEvidenceIds = new Set(
12826
+ [...existingStates.values()].flatMap((state2) => state2.evidenceIds)
12827
+ );
12828
+ const existingEntityIds = new Set(input.existingEntityIds ?? []);
12829
+ const entityRefs = /* @__PURE__ */ new Map();
12830
+ const evidenceRefs = /* @__PURE__ */ new Map();
12831
+ const evidence = (input.wire.evidence ?? []).map((item) => {
12832
+ const id = nextId();
12833
+ evidenceRefs.set(item.key, id);
12834
+ return {
12835
+ id,
12836
+ ownerId: input.ownerId,
12837
+ text: item.text,
12838
+ ...item.sourceRef ? { sourceRef: item.sourceRef } : {},
12839
+ confidence: item.confidence,
12840
+ createdAt: now
12841
+ };
12842
+ });
12843
+ const entities = (input.wire.entities ?? []).map((item) => {
12844
+ const id = nextId();
12845
+ entityRefs.set(item.key, id);
12846
+ return {
12847
+ id,
12848
+ ownerId: input.ownerId,
12849
+ type: item.type,
12850
+ name: item.name,
12851
+ ...item.subtype ? { subtype: item.subtype } : {},
12852
+ ...item.aliases ? { aliases: item.aliases } : {},
12853
+ createdAt: now,
12854
+ updatedAt: now
12855
+ };
12856
+ });
12857
+ const resolveEntityRef = (ref) => {
12858
+ const created = entityRefs.get(ref);
12859
+ if (created) return created;
12860
+ if (existingEntityIds.has(ref)) return ref;
12861
+ throw new Error(`unknown entity ref: ${ref}`);
12862
+ };
12863
+ const supersededStateIds = [];
12864
+ const referenceableEvidenceIds = new Set(input.referenceableEvidenceIds ?? []);
12865
+ const resolveEvidenceRef = (ref) => {
12866
+ const created = evidenceRefs.get(ref);
12867
+ if (created) return created;
12868
+ if (referenceableEvidenceIds.has(ref)) return ref;
12869
+ throw new Error(`unknown evidence ref: ${ref}`);
12870
+ };
12871
+ const states = (input.wire.states ?? []).map((item) => {
12872
+ const prior = item.stateId ? existingStates.get(item.stateId) : void 0;
12873
+ if (item.stateId && !prior) {
12874
+ throw new Error(`unknown existing state: ${item.stateId}`);
12875
+ }
12876
+ if (prior?.retiredAt) {
12877
+ throw new Error(`retired state cannot be updated: ${item.stateId}`);
12878
+ }
12879
+ if (prior && item.entityRef !== prior.entityId) {
12880
+ throw new Error(`existing state entityRef changed: ${item.stateId}`);
12881
+ }
12882
+ if (prior && item.facet !== prior.facet) {
12883
+ throw new Error(`existing state facet changed: ${item.stateId}`);
12884
+ }
12885
+ let supersededStateId;
12886
+ if (item.supersedes !== void 0) {
12887
+ if (input.wire.action !== "supersede") {
12888
+ throw new Error(
12889
+ `supersedes is only valid for the supersede action, got ${input.wire.action}`
12890
+ );
12891
+ }
12892
+ if (item.stateId !== void 0) {
12893
+ throw new Error("supersedes and stateId are mutually exclusive on one state");
12894
+ }
12895
+ const superseded = existingStates.get(item.supersedes);
12896
+ if (!superseded) {
12897
+ throw new Error(`unknown superseded state id: ${item.supersedes}`);
12898
+ }
12899
+ if (superseded.retiredAt) {
12900
+ throw new Error(`retired state cannot be superseded: ${item.supersedes}`);
12901
+ }
12902
+ if (supersededStateIds.includes(item.supersedes)) {
12903
+ throw new Error(`duplicate superseded state id: ${item.supersedes}`);
12904
+ }
12905
+ supersededStateId = item.supersedes;
12906
+ }
12907
+ const newEvidenceIds = item.evidenceRefs.map(resolveEvidenceRef);
12908
+ const id = prior?.id ?? nextId();
12909
+ if (supersededStateId !== void 0) supersededStateIds.push(supersededStateId);
12910
+ return {
12911
+ id,
12912
+ ownerId: input.ownerId,
12913
+ entityId: prior?.entityId ?? resolveEntityRef(item.entityRef),
12914
+ facet: prior?.facet ?? item.facet,
12915
+ value: item.value,
12916
+ text: item.text,
12917
+ evidenceIds: [.../* @__PURE__ */ new Set([...prior?.evidenceIds ?? [], ...newEvidenceIds])],
12918
+ createdAt: prior?.createdAt ?? now,
12919
+ updatedAt: now
12920
+ };
12921
+ });
12922
+ const resolveRelationRef = (ref) => {
12923
+ const createdEntity = entityRefs.get(ref);
12924
+ if (createdEntity) return createdEntity;
12925
+ const createdEvidence = evidenceRefs.get(ref);
12926
+ if (createdEvidence) return createdEvidence;
12927
+ if (existingEntityIds.has(ref) || existingStateIds.has(ref) || existingEvidenceIds.has(ref)) {
12928
+ return ref;
12929
+ }
12930
+ throw new Error(`unknown relation ref: ${ref}`);
12931
+ };
12932
+ const relations = (input.wire.relations ?? []).map((item) => ({
12933
+ id: nextId(),
12934
+ ownerId: input.ownerId,
12935
+ from: resolveRelationRef(item.fromRef),
12936
+ type: item.type,
12937
+ to: resolveRelationRef(item.toRef),
12938
+ createdAt: now
12939
+ }));
12940
+ return {
12941
+ action: input.wire.action,
12942
+ reason: input.wire.reason,
12943
+ ...evidence.length ? { evidence } : {},
12944
+ ...entities.length ? { entities } : {},
12945
+ ...states.length ? { states } : {},
12946
+ ...supersededStateIds.length ? { supersededStateIds } : {},
12947
+ ...relations.length ? { relations } : {}
12948
+ };
12949
+ };
12950
+
12951
+ // packages/ai/memory/vnext/interpreterPrompt.ts
12952
+ var MEMORY_VNEXT_ENTITY_CREATION_CONTRACT = `
12953
+ Entity creation is NOT named-entity recognition.
12954
+
12955
+ Create a new long-lived Entity only when the subject has future continuity value.
12956
+ A mention alone is insufficient.
12957
+
12958
+ Prefer leaving information as Evidence until at least one strong continuity signal exists:
12959
+ 1. The subject recurs across independent dialogs, or the user explicitly describes it as enduring.
12960
+ 2. The user connects it to their own preferences, relationships, goals, identity, worldview, ongoing work, or repeated activity.
12961
+ 3. Future conversations are likely to refer back to it under different wording, so a stable anchor materially improves cross-dialog continuity.
12962
+ 4. Creating the anchor is necessary to update or relate existing long-lived State.
12963
+
12964
+ Do NOT create an Entity merely because the text contains a named person, product, place, historical event, book, philosopher, food, device, or concept.
12965
+ When uncertain, keep Evidence and defer Entity creation.
12966
+
12967
+ Concept-specific rule:
12968
+ - concept is for abstract subjects that become part of the user's personal meaning world, such as freedom, absurdism, privacy, modernity, beauty, loneliness, safety, or maintainability.
12969
+ - Do not create a Concept Entity for every topic discussed or external fact queried.
12970
+ - Promote a concept only when it recurs, carries a durable user stance/interest/tension, connects multiple memories, or is likely to become a future recall/navigation anchor.
12971
+ - A one-off question such as "when was Kant born?" should normally create no long-lived Concept or Person Entity. Repeated discussion about Kant, freedom, and the user's own values may justify them.
12972
+ `.trim();
12973
+ var MEMORY_VNEXT_THIRD_PARTY_RELEVANCE_CONTRACT = `
12974
+ Third-party relevance test:
12975
+ - A fact about another person is durable only when it concerns the user's own world. Observation-only third-party facts \u2014 someone's appearance, news, habits, or the doings of a person the user merely encounters \u2014 stay Evidence, no matter how often they recur.
12976
+ - Closeness of that person, and repeated mentions across independent dialogs, do not by themselves make such an observation durable: never invent a user-world consequence to justify promotion (for example "the user keeps watching this person").
12977
+ - Matters that are part of the user's own shared life \u2014 household or family arrangements the user takes part in, a family member's health, or what the user relies on someone for \u2014 do belong to the user's world: state the user-world side (caregiving, changed time, changed plans, a sustained constraint) instead of a chronicle of the other person's doings.
12978
+ `.trim();
12979
+ var MEMORY_VNEXT_RECONCILIATION_CONTRACT = `
12980
+ When durable understanding changes, choose the smallest correct reconciliation:
12981
+ - no_op: no durable change.
12982
+ - create: genuinely new durable state/entity.
12983
+ - update: advance an existing state without changing its scope.
12984
+ - specialize: add a scoped exception/qualification; do not replace the broader state.
12985
+ - supersede: a newer statement explicitly replaces old current state. Emit the replacement as a NEW State and name the replaced current State in its supersedes field; runtime retires the old one (kept as recoverable history, no longer current).
12986
+ - ambiguous: evidence conflicts with current state, but replacement vs exception cannot be determined reliably.
12987
+
12988
+ Examples:
12989
+ - "\u56DE\u7B54\u7B80\u5355" then "\u5B89\u5168\u548C bug \u6392\u67E5\u8BE6\u7EC6" => specialize, not supersede.
12990
+ - "\u6211\u6709 Ollama Pro" then "\u6211\u5DF2\u7ECF\u4E0D\u7528 Ollama Pro \u4E86" => supersede.
12991
+ - Repeatedly choosing thin noodles without explicitly rejecting thick noodles => update or ambiguous, not automatic supersession.
12992
+
12993
+ Preserve ambiguity. Do not ask the user merely to clean memory. A later task may ask only if the unresolved state materially changes the answer.
12994
+ `.trim();
12995
+ var buildMemoryVNextInterpreterPrompt = () => [
12996
+ "You maintain long-lived adaptive relationship memory backed by evidence.",
12997
+ "External dialogs/files/web facts remain authoritative outside memory.",
12998
+ "Prefer a small stable set of Entities and updateable States over an ever-growing bag of facts.",
12999
+ MEMORY_VNEXT_ENTITY_CREATION_CONTRACT,
13000
+ MEMORY_VNEXT_THIRD_PARTY_RELEVANCE_CONTRACT,
13001
+ MEMORY_VNEXT_RECONCILIATION_CONTRACT,
13002
+ buildMemoryInterpreterWireContract()
13003
+ ].join("\n\n");
13004
+
13005
+ // packages/ai/memory/vnext/legacyMigrationShadow.ts
13006
+ var LEGACY_MIGRATION_SHADOW_INSTRUCTION = `
13007
+ This Evidence came from a legacy memory record.
13008
+ Legacy kind and subject metadata are advisory hints only.
13009
+ Re-evaluate it under the current vNext contract.
13010
+ Do not mechanically map:
13011
+ - semantic -> State
13012
+ - procedural -> procedure State
13013
+ - subjectType=agent -> agent Entity
13014
+ - visibility -> scope
13015
+ Prefer Evidence-only when durable semantic value is unclear.
13016
+ `.trim();
13017
+ var serializeExisting = (existing) => JSON.stringify({
13018
+ entityIds: existing?.entityIds ?? [],
13019
+ states: (existing?.states ?? []).map((state2) => ({
13020
+ stateId: state2.id,
13021
+ entityId: state2.entityId,
13022
+ facet: state2.facet,
13023
+ text: state2.text
13024
+ }))
13025
+ });
13026
+ var buildLegacyMigrationInterpreterInput = (input) => [
13027
+ LEGACY_MIGRATION_SHADOW_INSTRUCTION,
13028
+ `The legacy record's Evidence is marked referenceable with id "${input.evidence.id}" and sourceRef "${input.evidence.sourceRef}". Evidence ids marked referenceable in the supplied memory context may be referenced directly. When a State cites it, reference that exact id in evidenceRefs. Do not emit another Evidence for this legacy record.`,
13029
+ `Imported Evidence (text is the authoritative legacy content, referenceable directly):
13030
+ ${JSON.stringify(
13031
+ {
13032
+ ...input.evidence,
13033
+ referenceable: true
13034
+ },
13035
+ null,
13036
+ 2
13037
+ )}`,
13038
+ `Legacy metadata (advisory hints only, NOT vNext semantics):
13039
+ ${JSON.stringify(
13040
+ {
13041
+ kind: input.item.kind,
13042
+ visibility: input.item.visibility,
13043
+ subjectType: input.item.subjectType,
13044
+ subjectId: input.item.subjectId,
13045
+ facet: input.item.facet,
13046
+ importance: input.item.importance,
13047
+ resident: input.item.resident
13048
+ },
13049
+ null,
13050
+ 2
13051
+ )}`,
13052
+ `Existing vNext context for this principal (caller-supplied shadow snapshot):
13053
+ ${serializeExisting(
13054
+ input.existing
13055
+ )}`
13056
+ ].join("\n\n");
13057
+ var mergeImportedEvidence = (mutation, imported) => {
13058
+ const emitted = mutation.evidence ?? [];
13059
+ const duplicatedIds = new Set(
13060
+ emitted.filter(
13061
+ (item) => item.sourceRef === imported.sourceRef || // A re-emitted copy that drops sourceRef is still the same legacy record:
13062
+ // text equality is the only identity left on the wire to catch it.
13063
+ item.sourceRef === void 0 && item.text === imported.text
13064
+ ).map((item) => item.id)
13065
+ );
13066
+ const rewrite = (id) => duplicatedIds.has(id) ? imported.id : id;
13067
+ return {
13068
+ ...mutation,
13069
+ evidence: [imported, ...emitted.filter((item) => !duplicatedIds.has(item.id))],
13070
+ ...mutation.states ? {
13071
+ states: mutation.states.map((state2) => ({
13072
+ ...state2,
13073
+ evidenceIds: [...new Set(state2.evidenceIds.map(rewrite))]
13074
+ }))
13075
+ } : {},
13076
+ ...mutation.relations ? {
13077
+ relations: mutation.relations.map((relation) => ({
13078
+ ...relation,
13079
+ from: rewrite(relation.from),
13080
+ to: rewrite(relation.to)
13081
+ }))
13082
+ } : {}
13083
+ };
13084
+ };
13085
+ var runLegacyMemoryMigrationShadow = async (input) => {
13086
+ const principal = resolveLegacyMemoryPrincipal(input.item);
13087
+ const evidence = buildLegacyMemoryEvidence(input.item);
13088
+ const completion = await input.provider.complete(
13089
+ [
13090
+ { role: "system", content: buildMemoryVNextInterpreterPrompt() },
13091
+ {
13092
+ role: "user",
13093
+ content: buildLegacyMigrationInterpreterInput({
13094
+ item: input.item,
13095
+ evidence,
13096
+ ...input.existing ? { existing: input.existing } : {}
13097
+ })
13098
+ }
13099
+ ],
13100
+ input.timeoutMs === void 0 ? void 0 : { timeoutMs: input.timeoutMs }
13101
+ );
13102
+ const parsed = parseMemoryInterpreterWireMutation(completion.content);
13103
+ if (!parsed.ok) {
13104
+ throw new Error(`legacy migration shadow: unparsable interpreter response (${parsed.error})`);
13105
+ }
13106
+ const candidate = materializeMemoryInterpreterMutation({
13107
+ // The principal identity (user:/space:/system:<id>) is the migration owner
13108
+ // space, so a space migration can never land in a user space.
13109
+ ownerId: evidence.ownerId,
13110
+ wire: parsed.value,
13111
+ ...input.existing?.states ? { existingStates: [...input.existing.states] } : {},
13112
+ ...input.existing?.entityIds ? { existingEntityIds: [...input.existing.entityIds] } : {},
13113
+ referenceableEvidenceIds: [evidence.id],
13114
+ ...input.now === void 0 ? {} : { now: input.now },
13115
+ ...input.nextId ? { nextId: input.nextId } : {}
13116
+ });
13117
+ const mutation = mergeImportedEvidence(candidate, evidence);
13118
+ return {
13119
+ principal,
13120
+ evidence,
13121
+ wire: parsed.value,
13122
+ mutation,
13123
+ action: mutation.action,
13124
+ reason: mutation.reason
13125
+ };
13126
+ };
13127
+
13128
+ // packages/ai/memory/vnext/lazyPromotion.ts
13129
+ var ERROR_MESSAGE_MAX2 = 120;
13130
+ var inFlight = /* @__PURE__ */ new Set();
13131
+ var shortError2 = (error) => {
13132
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
13133
+ return message.length > ERROR_MESSAGE_MAX2 ? `${message.slice(0, ERROR_MESSAGE_MAX2)}\u2026` : message;
13134
+ };
13135
+ var loadExistingContext = async (db, ownerId) => {
13136
+ const entities = await listMemoryEntitiesVNext(db, ownerId);
13137
+ const states = (await Promise.all(
13138
+ entities.map((entity) => listMemoryStatesForEntityVNext(db, ownerId, entity.id))
13139
+ )).flat();
13140
+ return {
13141
+ entityIds: entities.map((entity) => entity.id),
13142
+ states
13143
+ };
13144
+ };
13145
+ var withoutImportedEvidence = (mutation, importedEvidenceId) => ({
13146
+ ...mutation,
13147
+ evidence: (mutation.evidence ?? []).filter((evidence) => evidence.id !== importedEvidenceId)
13148
+ });
13149
+ var hasWrites = (mutation) => (mutation.evidence?.length ?? 0) > 0 || (mutation.entities?.length ?? 0) > 0 || (mutation.states?.length ?? 0) > 0 || (mutation.supersededStateIds?.length ?? 0) > 0 || (mutation.relations?.length ?? 0) > 0;
13150
+ var runMemoryVNextLazyPromotion = async (input) => {
13151
+ const clock = input.clock ?? (() => performance.now());
13152
+ const startedAt = clock();
13153
+ const emit = input.emit ?? ((observation) => console.info("[memory] vnext lazy promotion", {
13154
+ event: "memory_vnext_lazy_promotion",
13155
+ ...observation
13156
+ }));
13157
+ const finish = (partial) => {
13158
+ const observation = {
13159
+ ...partial,
13160
+ latencyMs: Math.round((clock() - startedAt) * 10) / 10
13161
+ };
13162
+ try {
13163
+ emit(observation);
13164
+ } catch {
13165
+ }
13166
+ return observation;
13167
+ };
13168
+ const deterministicEvidence = buildLegacyMemoryEvidence(input.item);
13169
+ const flightKey = `${deterministicEvidence.ownerId}\0${deterministicEvidence.id}`;
13170
+ if (inFlight.has(flightKey)) {
13171
+ return finish({ status: "in_flight" });
13172
+ }
13173
+ inFlight.add(flightKey);
13174
+ try {
13175
+ const evidenceResult = await applyLegacyMemoryEvidence(input.db, input.item);
13176
+ if (evidenceResult.status === "conflict") {
13177
+ return finish({ status: "conflict" });
13178
+ }
13179
+ const evidence = evidenceResult.evidence;
13180
+ const existing = await loadExistingContext(input.db, evidence.ownerId);
13181
+ const alreadyCovered = (existing.states ?? []).some(
13182
+ (state2) => !state2.retiredAt && state2.evidenceIds.includes(evidence.id)
13183
+ );
13184
+ if (alreadyCovered) {
13185
+ return finish({ status: "already_covered" });
13186
+ }
13187
+ const interpreted = await runLegacyMemoryMigrationShadow({
13188
+ item: input.item,
13189
+ provider: input.provider,
13190
+ existing,
13191
+ ...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
13192
+ ...input.now === void 0 ? {} : { now: input.now },
13193
+ ...input.nextId ? { nextId: input.nextId } : {}
13194
+ });
13195
+ const semanticMutation = withoutImportedEvidence(interpreted.mutation, evidence.id);
13196
+ if (!hasWrites(semanticMutation)) {
13197
+ return finish({ status: "no_op", action: semanticMutation.action });
13198
+ }
13199
+ await applyMemoryInterpreterMutation(input.db, evidence.ownerId, semanticMutation);
13200
+ return finish({ status: "promoted", action: semanticMutation.action });
13201
+ } catch (error) {
13202
+ return finish({ status: "error", error: shortError2(error) });
13203
+ } finally {
13204
+ inFlight.delete(flightKey);
13205
+ }
13206
+ };
13207
+ var isMemoryVNextLazyPromotionEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_LAZY_PROMOTION === "1" || env.NOLO_MEMORY_VNEXT_LAZY_PROMOTION === "true";
13208
+
12076
13209
  // packages/ai/memory/runtime.ts
12077
13210
  var COLD_STORAGE_CONFIDENCE = 0.3;
12078
13211
  var MEMORY_OVERLAY_TOKEN_BUDGET = DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET;
@@ -12196,6 +13329,7 @@ var resolveMemoryRuntime = async (input) => {
12196
13329
  return { selectedItems: [], promptBlock: null };
12197
13330
  }
12198
13331
  const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
13332
+ const legacyStartedAt = performance.now();
12199
13333
  const candidates = await loadMemoryCandidatesFromDb(input.db, {
12200
13334
  owners,
12201
13335
  subjects: buildMemorySubjectsForAgent({
@@ -12222,13 +13356,40 @@ var resolveMemoryRuntime = async (input) => {
12222
13356
  input.userInput
12223
13357
  );
12224
13358
  const selected = [...residentItems, ...ranked];
13359
+ const legacyLatencyMs = Math.round((performance.now() - legacyStartedAt) * 10) / 10;
13360
+ const promptBlock = selected.length === 0 ? null : buildMemoryOverlay(selected, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET });
13361
+ const shadowEnabled = input.vNextShadowProvider != null && isMemoryVNextShadowReadEnabled();
13362
+ if (shadowEnabled) {
13363
+ await runMemoryVNextShadowRead({
13364
+ ctx: {
13365
+ db: input.db,
13366
+ owners,
13367
+ query: input.userInput,
13368
+ provider: input.vNextShadowProvider
13369
+ },
13370
+ legacyItems: selected,
13371
+ legacyLatencyMs,
13372
+ legacyContextChars: promptBlock?.length ?? 0
13373
+ });
13374
+ }
13375
+ const promotionCandidate = selected[0];
13376
+ const lazyPromotionEnabled = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
13377
+ if (lazyPromotionEnabled && promotionCandidate) {
13378
+ void runMemoryVNextLazyPromotion({
13379
+ db: input.db,
13380
+ item: promotionCandidate,
13381
+ provider: input.vNextShadowProvider,
13382
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
13383
+ }).catch(() => {
13384
+ });
13385
+ }
12225
13386
  if (selected.length === 0) {
12226
13387
  return { selectedItems: [], promptBlock: null };
12227
13388
  }
12228
13389
  await touchMemoryItemsInDb(input.db, selected);
12229
13390
  return {
12230
13391
  selectedItems: selected,
12231
- promptBlock: buildMemoryOverlay(selected, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET })
13392
+ promptBlock
12232
13393
  };
12233
13394
  };
12234
13395
 
@@ -12272,7 +13433,8 @@ var queryLocalMemory = async (env, agentKey, userInput, spaceId) => {
12272
13433
  userId: machineId,
12273
13434
  agentKey,
12274
13435
  userInput,
12275
- ...spaceId ? { spaceId } : {}
13436
+ ...spaceId ? { spaceId } : {},
13437
+ ...isMemoryVNextShadowReadEnabled(env) ? { vNextShadowProvider: void 0 } : {}
12276
13438
  });
12277
13439
  return resolution.promptBlock;
12278
13440
  };