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